最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing variables from PHP to AJAX success function - Stack Overflow

programmeradmin2浏览0评论

My aim is to update a WordPress post using AJAX. My code so far:

Script:

$.ajax({
    type: 'POST',
    url: ajax_url,
    data: {
        'action': 'wp_post',
        'ID': post_id,
        'post_title': post_title
},
success: function( data ) {
        $( '.message' )
        .addClass( 'success' )
        .html( data );
},
error: function() {
        $( '.message' )
        .addClass( 'error' )
        .html( data );
    }       
});

PHP:

function wp_post() {

    $post['ID'] = $_POST['ID'];
    $post['post_title'] = $_POST['post_title'];
    $post['post_status'] = 'publish';

    $id = wp_update_post( $post, true );

    if ( $id == 0 ) {
        $error = 'true';
        $response = 'This failed';
        echo $response;
    } else {
        $error = 'false';
        $response = 'This was successful';
        echo $response;
    }

}

As you can see the $response variable in my PHP function is being passed to the success function in my script and the value of $response is displayed on the page.

I want to modify my success function to do something like this:

success: function( data ) {
    if( $error == 'true' ) {
        // do something
    } else {
        // do something else
    }
},

The problem is, I am having trouble passing both the $response and $error variables in my PHP function to the success function in my scipt.

  1. Can anyone let me know how to pass $response and $error to my script's success function?
  2. Is there a better approach I should be taking?

I'm newish to AJAX so forgive me if the question is very basic.

My aim is to update a WordPress post using AJAX. My code so far:

Script:

$.ajax({
    type: 'POST',
    url: ajax_url,
    data: {
        'action': 'wp_post',
        'ID': post_id,
        'post_title': post_title
},
success: function( data ) {
        $( '.message' )
        .addClass( 'success' )
        .html( data );
},
error: function() {
        $( '.message' )
        .addClass( 'error' )
        .html( data );
    }       
});

PHP:

function wp_post() {

    $post['ID'] = $_POST['ID'];
    $post['post_title'] = $_POST['post_title'];
    $post['post_status'] = 'publish';

    $id = wp_update_post( $post, true );

    if ( $id == 0 ) {
        $error = 'true';
        $response = 'This failed';
        echo $response;
    } else {
        $error = 'false';
        $response = 'This was successful';
        echo $response;
    }

}

As you can see the $response variable in my PHP function is being passed to the success function in my script and the value of $response is displayed on the page.

I want to modify my success function to do something like this:

success: function( data ) {
    if( $error == 'true' ) {
        // do something
    } else {
        // do something else
    }
},

The problem is, I am having trouble passing both the $response and $error variables in my PHP function to the success function in my scipt.

  1. Can anyone let me know how to pass $response and $error to my script's success function?
  2. Is there a better approach I should be taking?

I'm newish to AJAX so forgive me if the question is very basic.

Share Improve this question asked Jan 7, 2014 at 15:48 henrywrighthenrywright 10.2k25 gold badges96 silver badges153 bronze badges 4
  • why don't you use standard http result code instead of reinventing a protocol on top of a protocol? – njzk2 Commented Jan 7, 2014 at 15:50
  • Thanks njzk2 - as I said I'm newish to AJAX. Any chance you could provide an example of how to do that? – henrywright Commented Jan 7, 2014 at 15:51
  • 1 Encode the response as JSON object. Check out json_encode in PHP and JSON.parse in JavaScript. – elclanrs Commented Jan 7, 2014 at 15:52
  • 1 use php.net/manual/en/function.http-response-code.php to set a failure code, which will get you into the ajax error function. – njzk2 Commented Jan 7, 2014 at 15:57
Add a comment  | 

6 Answers 6

Reset to default 13

You shoud encode the response of the php script as json, as follows:

function wp_post() {

    $post['ID'] = $_POST['ID'];
    $post['post_title'] = $_POST['post_title'];
    $post['post_status'] = 'publish';

    $id = wp_update_post( $post, true );

    $response = array();

    if ( $id == 0 ) {
        $response['status'] = 'error';
        $response['message'] = 'This failed';
    } else {
        $response['status'] = 'success';
        $response['message'] = 'This was successful';
    }

    echo json_encode($response);

}

And then, in your javascript code:

success: function( data ) {
    if( data.status == 'error' ) {
        // error handling, show data.message or what you want.
    } else {
        // same as above but with success
    }
},

You can create a JSON array like this one, in the backend:

$arr = array('error' => true, 'something' => 'foo');
echo json_encode($arr);

And then parse the json array to fetch the returned values, like this:

success: function( data ) {
    var error = '';
    var something = '';
    for(var i = 0; i < data.length ; i++)
    {
        error = data[i].error;
        something = data[i].something;
    }
    if( error ) {
        // do something
    } else {
        // do something else
    }
},

Wherea you echoed the array from the backend to the frontend, you can't simply access PHP variables within the JavaScript.

Note that there might be a syntax error, since I'm not testing it.

What you are looking for is json_encode()

This converts a PHP array to JSON.

For example:

$dataArray = array( 'message' => 'Error', 'data' => data);
echo json_encode($dataArray);   

if you use:

echo json_encode($response);

on your .php function, remember to use:

var data = $.parseJSON(data);

on your ajax success.

Example:

function php_ajax_function() {

    // whatever you want to do...

    $response = array();

    if ( $id == 0 ) {
        $response['status'] = 'error';
        $response['message'] = 'This failed';
    } else {
        $response['status'] = 'success';
        $response['message'] = 'This was successful';
    }

    echo json_encode($response);
}

And then, in your javascript code:

success: function( data ) {

    console.log(data);

    var data = $.parseJSON(data);

    if( data.status == 'error' ) {
        // do something
    } else {
        // do other thing
    }
}

You cannot directly use PHP variables within JavaScript. The best you can do is manipulate PHP output in your JavaScript code.

For example, you could print $response as either 'error' or 'no_error' - and in your AJAX callback, check that var data does not equal 'error' (For example).

the javascript variable data contains your echoed $response variable. So using your example, it would be something like this. Be sure you are also asking for html as your return data in the ajax function. here is the docs on that: http://api.jquery.com/jquery.ajax/

success: function( data ) {
    if( data == 'This failed' ) {
        // do something
    } else {
        // do something else
    }
},
发布评论

评论列表(0)

  1. 暂无评论