0

jQuery code of 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",
        data: {
            'request_type':'ajax', 
            'op':'get_city_state',
            'zip_code' : el.val()
        },
        success: function(result, success) { alert(result.join('\n'));
          $("#city").val(result.place_name);
          $("#state_code").val(result.state_code);
        }
      }); 
    }
  });
});

PHP code snippet 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();
        list($data) = prepare_response($request);
        $smarty->assign('data', $data);    
      } else {
        $data = $objUserLogin->GetResponse();

        echo $data;
      }     

      die;
      break;

In PHP code the $data contains data in following manner :

<pre>Array
(
    [id] => 23212
    [zip_code] => 28445
    [place_name] => Holly Ridge
    [state_code] => NC
    [created_at] => 1410875971
    [updated_at] => 1410875971
)
</pre>

From the above data(i.e. response which will be available in variable result in ajax response) I want to access only two fields place_name and state_code.

I tried printing the content of result variable using alert(result) in console but I get the word Array

How to achieve this is my doubt?

Thanks in advance.

1 Answer 1

2

You should encode your result to json. So instead of the statement echo $data

use

echo json_encode($data);

it will return your result in json format. like

{"id":23212,"place_name":"Holly Ridge"...}

and in your javascript your can access your data

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot man, it worked for me. One more thing I want to disable the click anywhere on the page until the response comes. Can you please tell me how could I achieve this?
You have the possibility in you $.ajax request to set the parameter 'async: false'
That also worked for me. But how to print the alert when the error comes in above code? Can you please help me in this?
Similar to your sucess: function in you ajax call you can write an error function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.