Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables from PHP to AJAX success function

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.

like image 591
henrywright Avatar asked Jan 07 '14 15:01

henrywright


People also ask

Is AJAX successful deprecated?

The parameter is not being deprecated, the success method is. You can continue using success: function re-read it carefully.

How do I pass a value to a PHP script using AJAX?

php $userAnswer = $_POST['name']; $sql="SELECT * FROM <tablename> where color='". $userAnswer. "'" ; $result=mysql_query($sql); $row=mysql_fetch_array($result); // for first row only and suppose table having data echo json_encode($row); // pass array in json_encode ?>

What triggers AJAX success?

AJAX success is a global event. Global events are triggered on the document to call any handlers who may be listening. The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds.

How do you pass an outside variable to AJAX success function?

Maybe the best way to tackle this is to add each response to an item of an array and then call a new function to log what you need once they have all completed. declare a global variable before the ajax call. and assign the response from the ajax call to the data inside the function.


3 Answers

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
    }
},
like image 163
taxicala Avatar answered Oct 09 '22 21:10

taxicala


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.

like image 21
Jonast92 Avatar answered Oct 09 '22 22:10

Jonast92


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);   
like image 21
Phil Avatar answered Oct 09 '22 22:10

Phil