-1

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
PHPLover
  • 1
  • 51
  • 158
  • 311
  • Check for error message length or make a status code and check for that – Spokey Nov 05 '14 at 12:02
  • Just check for `result.error_message` or returns error header from PHP to fire ajax error callback – A. Wolff Nov 05 '14 at 12:02
  • send a 500/403 or some other error codes and `.fail()` will get trigger. check [**this**](http://stackoverflow.com/questions/1632159/how-to-send-a-server-error-response-using-php) – itachi Nov 05 '14 at 12:04
  • I just want to print the alert when error comes in response. How to print that alert? I can put any custom message in alert. – PHPLover Nov 05 '14 at 12:06

2 Answers2

2

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);
      }
    }
Deepak
  • 112
  • 10
-1
on php file if u found data acc to ur parameter
than it ok if there is no data acc to ur parameter than this time u can call its an error so in thsi case  echo "error";

and on ajax page check for result if its value is error then do what else u want 
success: function(result, success) {
          $("#city").val(result.place_name);
          $("#state_code").val(result.state_code);
        }
kki3908050
  • 165
  • 2
  • 9