My goal is to update a WordPress post using AJAX. My code is:
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 variable $responsein my PHP function is passed to the success function in my script, and the value is displayed on the page $response.
I want to change my success function to do something like this:
success: function( data ) {
if( $error == 'true' ) {
} else {
}
},
The problem is that I find it hard to pass variables $responseand $errorin my PHP-function features of success in my session.
- Can anyone tell me how to pass
$response and $error in my success function script? - Is there a better approach I should take?
I'm new to AJAX, so forgive me if the question is very simple.