kaya new kaya new - 27 days ago 16
Ajax Question

if else condition in jquery ajax response

I have one Ajax function which is running properly.but i want when my Ajax response is

No Couriers found near by you.please select another location


i want to display some error message else i want to display another map div in else condition.
but every time when i hit Ajax only else condition is working..but when i alert response and see the output it shows this message when

No Couriers found near by you.please select another location

but still it not comes in if condition..can anyone help me to do this....

<script>
$('#weight0,#weight1,#weight2,#weight3').click(function() {
var checked = $(this).is(':checked');
if($(this).is(":checked")) {
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Orders","action" => "searchCourier")); ?>',
data: {
frmlat: $("#PoolLatitude").val(),
frmlong: $("#PoolLongitude").val(),
mylocation: $("#PoolLocation").val()
},
dataType: "html",
success: function(response) {
alert(response);
if(response =="<h3>No Couriers found near by you.please select another location</h3>"){
alert(thanks);
} else {
$('#map_canvas').css('display', 'none');//used to hide map after ajax success response.
$("#load_map").html(response);
}
},
complete: function() {
$('.spinicon').hide();
}
});
} else {
$("#secretcode").val("");
}
});
</script>

Answer

First of all, i suggest you to use status for ajax response something like:

1 for success
0 for failure 

Than, as per your statement, your are getting the correct response in:

alert(response);

Than, you must need to check either response having <h3></h3> tags or not.

In your code, the main issue is that, you are using string without quotes in alert alert(thanks); this will return undefined thanks in console and treated as a variable.

This should be alert("thanks");

One more suggestion, it's always better to check browser console when you are not getting success in Ajax or any other script, this will help you to find the errors.