Reputation: 21
Currently I am using this to send success or failure to ajax:
$response = array( 'success' => true );
wp_send_json_success($response);
However, say the user is not logged in and I would like to end the php function right there, and send the error message that would prompt a login modal to popup. How would I do that? Like:
if(!is_user_logged_in)) {
wp_send_json_error('not logged in');
die()
}
or I could use the more common json_encode($response);
if(!is_user_logged_in)) {
echo json_encode($response);
die()
}
but how would this handler even know an error occurred? If I put all my options for success and errors into an array, how do I die() the function while still returning the json response? and how do I tell php which response to send?
Once it reached my ajax call, I am confident I can figure it out. Something like this is what I read:
var dataArray = jQuery.parseJSON(data);
Some examples would be of great help. Thank you in advance!
Upvotes: 1
Views: 281
Reputation: 409
you can use json_encode and make your own protocol like this:
if(isset($_POST['operation']) && $_POST['operation'] == 'is_user_logged_in'){
if(!is_user_logged_in()){
$response->success = false;
$response->msg = "not logged in";
}else{
$response->success = true;
}
echo json_encode($response);
exit;
}
Then in your ajax:
$.post('AJAX-URL-HERE',{"operation":"is_user_logged_in"},function(response){
if(response.success){
//do whatever
}else{
var message = response.msg
//pop up the login modal
}
},'json').error(function(){alert('Call error')});
Upvotes: 0
Reputation: 32340
This should work:
if(!is_user_logged_in()) {
$response = array(
'loggedIn' => false,
'alertMsg' => 'not logged in :,-(',
);
} else {
$response = array(
'loggedIn' => true,
'success' => true,
'alertMsg' => 'test!',
);
}
wp_send_json_success($response);
die();
The Ajax call is something like:
jQuery.get('pathToYourJsonFunctionURL', function(data) {
if (data.loggedIn == true) {
jQuery('#divForLoggedInStatus').text('You are logged in');
} else {
jQuery('#divForLoggedInStatus').text('You are NOT logged in');
}
window.alert(data.alertMsg);
});
When you return JSON data, you do not use parseJSON
(the data is already (parsed) json). data.loggedIn
is the same as in PHP returned array('loggedIn' => value);
Upvotes: 1