How can I get a PHP variable to AJAX?

岁酱吖の 提交于 2019-12-01 10:54:38

Good to use json while return back data from php to ajax.

$return_data = array();
if (condition){
   $return_data['status'] = 'success';
} else {
    $return_data['status'] = 'info';
}

echo json_encode($return_data);
exit();

Now, if you are return back json data to ajax, then you need to specify return data type into ajax call as below

function send() {
var data = $('#signup_form').serialize();
    $.ajax({
        type: "POST",
        url: "signup_process.php",
        data: data,
        dataType: 'json', 
        success: function (data) {
        alert(data.status);
            if (data.status == 'success') {
                // everything went alright, submit
                $('#signup_form').submit();
            } else if (data.status == 'info')
            {
                console.log(data.status);
                $("label#email_error").show(); 
                return false; 
            }
        }
    });
    return false;
};

You should send a JSON object back from php:

$data = array();
if (condition){
   $data['status'] = 'success';
else {
   $data['status'] = 'info';
}

header('Content-type: application/json');
echo json_encode($data);

The json_encode() method converts the array to a JSON object so you can access each array key by name on the js side.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!