Wordpress Wp_Send_Json_Success() Returns Undefined on Success
I'm New to Ajax Queries in Wordpress. I've Got a Jquery Request in Js and a Php Handler That Is Running Successfully and Executing as It Should. However, the...
I'm new to Ajax queries in wordpress. I've got a jquery request in JS and a PHP handler that is running successfully and executing as it should. However, the response that is sent back using wp_send_json_success() is returning undefined and I can't work out why.
The javascript request:
$('.iflo-visibility-option-item').on('click', function() {
var post_id = $(this).attr( 'id' );
console.log(post_id);
$.ajax({
type: 'POST',
url: ajax_object.ajaxurl,
data: {
action: 'iflo_update_post_visibility',
post_id: post_id,
visibility: 'Library',
success: function ( response, status, XHR ) {
alert(status);
}
}
});
});
});
The PHP block in the handler that should return.
update_post_meta ( $post_id, $key, $_REQUEST ['visibility']);
$response = array('response' => 'Visibility was updated.',);
iflo_write_log($response);
wp_send_json_success( $response );
When the response is written to the log I get this:
Array ( [response] => Visibility was updated. )
The database update happens successfully. Any ideas why the response isn't getting to the client?
1 Answer
I am pretty sure it is due to you putting the success function inside the data: attribute. Also, I do not see you declaring the Datatype. Try forming your ajax function like this:
$.ajax({
url: ajax_object.ajaxurl,
type: 'POST',
data: $(form).serialize() + "&action=" + "validate_email_input",
dataType: 'json',
beforeSend: function () {
//Before sending, like showing a loading animation
},
success: function(data){
console.log(data);
},
error: function(data) {
console.log(data);
},
});
That should fix the undefined response.