Bilal Zafar
Bilal Zafar

Reputation: 457

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?

Upvotes: 2

Views: 3750

Answers (5)

Shubham Khatri
Shubham Khatri

Reputation: 282080

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>

Upvotes: 1

Veshraj Joshi
Veshraj Joshi

Reputation: 3589

Yes your ajax-script.php is correct, I think it will be better to organize data something differently and output string will be same and suggest to change following code in another snippet,

$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;

to

$code = $_GET['TERMINAL_CODE'];
$jsonData = array('success' =>  true,
                  'Response' => array(
                                  array(
                                    'TERMINAL_CODE'=>16,
                                    'TERMINAL_NAME'='FAISALABAD'
                                   ),
                                   array(
                                    'TERMINAL_CODE'=>17,
                                    'TERMINAL_NAME'='JHANG'
                                   ),
                                   array(
                                    'TERMINAL_CODE'=>1,
                                    'TERMINAL_NAME'='LAHORE'
                                   ),
                                   array(
                                    'TERMINAL_CODE'=>5,
                                    'TERMINAL_NAME'='MULTAN'
                                   ),
                                   array(
                                    'TERMINAL_CODE'=>23,
                                    'TERMINAL_NAME'='NOWSHERA'
                                   ),
                                   array(
                                    'TERMINAL_CODE'=>25,
                                    'TERMINAL_NAME'='PESHAWAR'
                                   ),
                                   array(
                                    'TERMINAL_CODE'=>22,
                                    'TERMINAL_NAME'='RAWALPINDI'
                                   ),
                                   array(
                                    'TERMINAL_CODE'=>31,
                                    'TERMINAL_NAME'='SIALKOT'
                                   ),

                                )
             );

echo json_encode($jsonData);

and in ajax-part

$.ajax(
     {
       type: "GET",
       url: 'ajax-script.php',
       data: { TERMINAL_CODE: value},
       // add another line here to convert response text i.e data to json format, server will send response text in string to do so,
       dataType : 'json',
       success: function(data) {
                // if you didnot add line dataType: 'json', you can simply convert response text to json object by 
                data = JSON.parse(data); 
                $('#arrivals').html(data.Success);
                //alert(data.length);
            }
        });

Upvotes: 1

Shailesh Chauhan
Shailesh Chauhan

Reputation: 570

To get response as json we need to pass dataType as json.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script type="text/javascript">
jQuery(document).ready(function($){
	$.ajax({
		type: "GET",
		url: 'ajax-script.php',
		dataType:'json',
		data: { TERMINAL_CODE: value},
		success: function(data) {				
			for (i in data.Response) {
				var row = data.Response[i];
				$('#arrivals').append('TERMINAL_CODE : ' + row.TERMINAL_CODE +',TERMINAL_NAME:'+ row.TERMINAL_NAME+'<br/>');
			}                  
		}
	});		
});	  
</script>
<div id="arrivals"></div>

Upvotes: 1

Haresh Vidja
Haresh Vidja

Reputation: 8496

You can use for() or each() method. I am suggesting to use getJSON() method for load JSON data from server.

$.getJSON('ajax-script.php'{TERMINAL_CODE: value}).done(function(data) {
              $('#arrivals').html(data.Success);
              $.each(data.Response, function( i, item ){
                 console.log(item .TERMINAL_NAME)
                 console.log(item .TERMINAL_CODE)
              })
              //alert(data.length);
            }
      });

Sample

var data = {
	"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"
	}]
} 

terminal_codes=[];
$.each(data.Response, function( i, item ){
                     console.log(item .TERMINAL_NAME)
                     console.log(item .TERMINAL_CODE);
                      terminal_codes.push(item .TERMINAL_CODE);
                  });

$('#arrivals').html(terminal_codes.join(","));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="arrivals"></div>

Check examples of getJSON()

Upvotes: 1

guradio
guradio

Reputation: 15565

var data = {
	"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"
	}]
}

data = data.Response
$.each(data, function(i,v){
console.log(v.TERMINAL_NAME)
console.log(v.TERMINAL_CODE)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

use .each() to iterate over the data

Description: Iterate over a jQuery object, executing a function for each matched element.

Upvotes: 1

Related Questions