I am trying to run an ajax request to pass some data to a function I have written. I return the response, and try and run some javascript based on the response, but it doesn’t seem to be running properly. Regardless of what the response is back, it always runs it as if the response was not ‘Everything’s Chimpy!’
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {
action: 'chimp_form',
form_action: 'validate_api_key',
api_key: apiKey,
data_center: dataCenter
},
success: function(validation_response) {
// alert(validation_response);
if(validation_response == "Everything's Chimpy!") {
jQuery('.mailChimp_api_key_preloader')
.fadeOut('fast', function() {
jQuery('.mailChimp_api_key_validation_message')
.html('<img src="/images/mc-checkmark.png" alt=message > Valid API Key')
.css("color", "green").fadeIn();
});
} else {
// alert(response);
jQuery('.mailChimp_api_key_preloader')
.fadeOut('fast', function() {
jQuery('.mailChimp_api_key_validation_message')
.html('<img src="/images/yikes-mc-error-icon.png" alt=message > Error: '+validation_response+'.')
.css("color", "red").fadeIn();
});
};
},
error: function(response) {
alert('There was an error processing your request...');
}
});
I am getting a response back from the ajax request, and it says ‘Everything’s Chimpy!’, but my conditional is not running. No matter what , the successfunction runs the second conditional. But I have tested the response and can see that it matches my first conditional statement.
Why isn’t the first one running?
Weirdest part about it…I developed this on localhost installation. When I transferred it over to my live site, this ajax request and success callback is not working as it does on localhost. I can’t think of a reason it would act differently on localhost than it does on the live site.
This is the response that is coming back:
Error: Everything’s Chimpy!.
Save yourself some effort and examine the
wp_send_json_success()
andwp_send_json_error()
functions instead. These will let you send data back from PHP and automatically send back success values for the javascript code to examine.One reason might be that the AJAX request per jQuery defaults to
async: true
, and the response comes too late (localhost is often faster). Tryasync: false
. That solved it at least in a similar case for me recently.Another important detail: your response HTTP status code should be 200. So in your callback, add this line at the top, before you send any output:
I ended up going with:
and it works like a charm. Thanks for the responses!