Bilal Zafar Bilal Zafar - 2 months ago 5
Javascript Question

Parse json array in jquery php

I am new to JSON, and I am trying to get the JSON response and then parse it in jquery.

Here is my sample code,

$.ajax({
type: "GET",
url: 'ajax-script.php',
data: {
TERMINAL_CODE: value
},
success: function(data) {
$('#arrivals').html(data.Success);
//alert(data.length);
}
});


ajax-script.php

$code = $_GET['TERMINAL_CODE'];

$jsonData = '{"Success" : true ,"Response": [{
"TERMINAL_CODE": 16,
"TERMINAL_NAME": "FAISALABAD"
}, {
"TERMINAL_CODE": 17,
"TERMINAL_NAME": "JHANG"
}, {
"TERMINAL_CODE": 1,
"TERMINAL_NAME": "LAHORE"
}, {
"TERMINAL_CODE": 5,
"TERMINAL_NAME": "MULTAN"
}, {
"TERMINAL_CODE": 23,
"TERMINAL_NAME": "NOWSHERA"
}, {
"TERMINAL_CODE": 25,
"TERMINAL_NAME": "PESHAWAR"
}, {
"TERMINAL_CODE": 22,
"TERMINAL_NAME": "RAWALPINDI"
}, {
"TERMINAL_CODE": 31,
"TERMINAL_NAME": "SIALKOT"
}]
}
';

echo $jsonData;


This code gives me the complete array in arrivals div, But i need
TERMINAL_CODE
and
TERMINAL_NAME
separately?
How can I achieve this?

Answer

Use JSON.parse() to parse the json first and then iterate over the data as

var json = {"Success" : true ,"Response": 
[{"TERMINAL_CODE":16,"TERMINAL_NAME":"FAISALABAD"},
{"TERMINAL_CODE":17,"TERMINAL_NAME":"JHANG"},
{"TERMINAL_CODE":1,"TERMINAL_NAME":"LAHORE"},
{"TERMINAL_CODE":5,"TERMINAL_NAME":"MULTAN"},
{"TERMINAL_CODE":23,"TERMINAL_NAME":"NOWSHERA"},
{"TERMINAL_CODE":25,"TERMINAL_NAME":"PESHAWAR"},
{"TERMINAL_CODE":22,"TERMINAL_NAME":"RAWALPINDI"},
{"TERMINAL_CODE":31,"TERMINAL_NAME":"SIALKOT"}]};

$.each(json.Response, function(i, v) {
  var str = "<div>TERMINAL CODE " + v.TERMINAL_CODE + "</div>"
    $('#push').append(str);
  var str1 = "<div>TERMINAL NAME " + v.TERMINAL_NAME + "</div>"
  $('#push').append(str1);


})

SNIPPET

var json = {"Success" : true ,"Response": 
[{"TERMINAL_CODE":16,"TERMINAL_NAME":"FAISALABAD"},
{"TERMINAL_CODE":17,"TERMINAL_NAME":"JHANG"},
{"TERMINAL_CODE":1,"TERMINAL_NAME":"LAHORE"},
{"TERMINAL_CODE":5,"TERMINAL_NAME":"MULTAN"},
{"TERMINAL_CODE":23,"TERMINAL_NAME":"NOWSHERA"},
{"TERMINAL_CODE":25,"TERMINAL_NAME":"PESHAWAR"},
{"TERMINAL_CODE":22,"TERMINAL_NAME":"RAWALPINDI"},
{"TERMINAL_CODE":31,"TERMINAL_NAME":"SIALKOT"}]};

$.each(json.Response, function(i, v) {
  var str = "<div>TERMINAL CODE " + v.TERMINAL_CODE + "</div>"
	$('#push').append(str);
  var str1 = "<div>TERMINAL NAME " + v.TERMINAL_NAME + "</div>"
  $('#push').append(str1);
  

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="push">

</div>