2

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?

1
  • Use JSON.parse(data) to convert it to a JS object. Then you can reference the properties of each object in the response array. Commented Sep 19, 2016 at 4:46

5 Answers 5

1

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>

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

Comments

1

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.

Comments

1

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()

2 Comments

I have used this above console.log $('#arrivals').html(item.TERMINAL_CODE); but it gives me only the last terminal code?
You are overriting #arrivals html all time in loop so you getting only last element value. you need to do something like this.. as I have added in code snippet.
1

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>

Comments

1

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);
            }
        });

Comments

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.