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.
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