user2839497 user2839497 - 7 months ago 10
Javascript Question

How to show alert when error comes from the PHP as response to ajax request in following case?

The jQuery AJAX function is as follows :

$(document).ready(function() {
$("#zip_code").keyup(function() {
var el = $(this);
var module_url = $('#module_url').val();

if (el.val().length === 5) {
$.ajax({
url : module_url,
cache: false,
dataType: "json",
type: "GET",
async: false,
data: {
'request_type':'ajax',
'op':'get_city_state',
'zip_code' : el.val()
},
success: function(result, success) {
$("#city").val(result.place_name);
$("#state_code").val(result.state_code);
}
});
}
});
});


The PHP code is as follows :

case "get_city_state":

// to get the city and state on zip code.
$ret = $objUserLogin->GetCityState($request);

if(!$ret) {
$error_msg = $objUserLogin->GetAllErrors();
$data = array();
$data['error_message'] = $error_msg;
$data = json_encode($data);
echo $data;
die;
} else {
$data = array();
$data = $objUserLogin->GetResponse();
echo json_encode($data);
die;
}
break;


Now I'm able to print the success when the response comes without any error but what about showing the alert message when some error happens. How to achieve it? What change needs to make to the above code? Please help me.

Answer

Use below condition in success:

    success: function(result, success) {
      if($.inArray( "error_message", result)) {
          alert("Error message");
      } else {

          $("#city").val(result.place_name);
          $("#state_code").val(result.state_code);
      }
    }