Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  147] [ 6]  / answers: 1 / hits: 27383  / 11 Years ago, tue, january 7, 2014, 12:00:00

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.


More From » php

 Answers
19

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

[#73331] Sunday, January 5, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cristoferjordih

Total Points: 513
Total Questions: 96
Total Answers: 105

Location: Croatia
Member since Fri, Sep 11, 2020
4 Years ago
;