How can I get a PHP variable to AJAX?

2019-02-20 02:49发布

问题:

I don't think I am passing the variable the right way between my separate PHP and AJAX files.

I am debugging this by triggering the second condition $status = 'info'; in my PHP file.

Currently, status is coming up as "undefined" for alert(data.status);

signup_process.php

if (condition){

   $status = 'success';

else {

    $status = 'info';

    }

AJAX

function send() {
var data = $('#signup_form').serialize();
    $.ajax({
        type: "POST",
        url: "signup_process.php",
        data: data,
        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;
};

I know that the 2nd condition is being triggered because I put a header redirect there just for testing and it worked fine.

回答1:

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;
};


回答2:

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.