• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1070
  • Last Modified:

Printing out JSON array returned

I have the following JSON array, successfully returned by some PHP script:

[ {"occurences":"1","post_title":"Test 1","ID":"16"},    
 {"occurences":"1","post_title":"Test 2","ID":"19"},
 {"occurences":"1","post_title":"\u543b\u60a8\u7684\u5c41\u80a1","ID":"21"}]

The following js, however, fails to print out:

success:function(data){
     $.each(data, function(i, post){
     content = '';
     content += '<li>' + post.post_title + '</li>';
   });

   $(content).appendTo("#search-results");

   }

Open in new window


But the display only showed "Undefined" instead supposedly of the post_titles, and the Console showed no errors.

This is the HTML part, just in case:
<form id="search" action="">
<div class="toolbar">
    <h1>Search</h1>
    <a href="#" class="back">Back</a>
</div>
<ul class="rounded">
    <li><input type="text" name="search-text" placeholder="Search" id="search-text" /></li>
</ul>
<ul class="edgetoedge" id="search-results">
    <li class="sep">Results</li>                
</ul>
</form>

Open in new window


Any clue why? Please.
0
josefyeung
Asked:
josefyeung
  • 4
  • 4
3 Solutions
 
Julian HansenCommented:
Are you sure that the event handler passing the data to your success function is parsing the JSON data?

Usually with data passed by a $.post or $.ajax you specify you want your data as JSON before it is returned to you as such otherwise you have to do the following

Also note the content=''; is in the wrong place - should be outside of the each()
success:function(data){
   var json = eval(data); // eval the return 
     content = ''; // Moved from inside the each
     $.each(json, function(i, post){
     content += '<li>' + post.post_title + '</li>';
   });

   $(content).appendTo("#search-results");

   }
                                  

Open in new window


If you are using the JQuery AJAX call then

$(function() {
  $.ajax({
    url: 't15.php',
    dataType: 'json', // Make sure this is here
    data: {x: 1},
    success: function(data) {
      var  content = ''; // This line was moved from inside the each
      $.each(data, function(i, post){
        content += '<li>' + post.post_title + '</li>';
      });

      $(content).appendTo("#search-results");
    }
  });
});

Open in new window

0
 
Michel PlungjanIT ExpertCommented:
As already said: the content var belongs outside the each. I post with a demo this since I wrote it before I saw it had already been answered - I am not keen on the eval though

var content = '';      
$.each(data, function(i, post){      
    content += '<li>' + post.post_title + '</li>';    
});    
$(content).appendTo("#search-results");  

DEMO
0
 
josefyeungAuthor Commented:
Hi,

Problem solved. You're right on the "content=' '" point, though.

function (data) {
    var content = '';
    var json = jQuery.parseJSON(data);

    $.each(json, function(i, post) {
        content += '<li>' + post.post_title + '</li>';
    });

    $(content).appendTo("#search-results");
}

Open in new window


The data had been declared JSON and passed back from PHP in json_encode form.

Thanks!
0
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

 
josefyeungAuthor Commented:
I've requested that this question be closed as follows:

Accepted answer: 0 points for josefyeung's comment #a38292782
Assisted answer: 250 points for julianH's comment #a38292591
Assisted answer: 250 points for mplungjan's comment #a38292770

for the following reason:

the &lt;code&gt;jQuery.parson(data) &lt;/code&gt;<br />must be used
0
 
Julian HansenCommented:
josefyeung, you need to click the Accept Multiple answers under the answer you want to accept - if you do it on your on it generets a close request
0
 
Julian HansenCommented:
@josefyeung, as a matter of interest why is it necessary to call the parsJSON explicitly - which call method are you using?

$.post
$.ajax

?
0
 
josefyeungAuthor Commented:
@julian

I called standard admin-ajax.php, and it returned an array to my function (data) before which the array needed to be "json_encoded" in the PHP.

After being returned to js, the data then needed to be parsed in JSON form, i.e.jQuery wouldn't know  otherwise.

That's it.
0
 
Julian HansenCommented:
Ok but I was asking how you called the .php file? did you use one of the JQuery methods?

i.e.

$.post('admin-ajax.php',{param: param, ...}, function(data) {
  // process code here
}, 'json');

While automatically parse the JSON for you as will the $.ajax sample I posted above with dataType: 'json'.

I was just wondering why you needed to do an explicit call to parseJson if you were using one of the above methods?
0
 
josefyeungAuthor Commented:
@julian

Hope this can help make myself clear:

$.ajax({
									
					  url: 'http://xxxxxxxx/wp-admin/admin-ajax.php',
					  
					  data:{
						   'action':'go_ajax',
						   'fn':'spw_autosuggest', 
						   'queryString': inputString
						   },  
					  
					  dataType: 'JSON',
					  
					  success:function(data){
						
								var content = '';  //this is reminded by julian
								var data = $.parseJSON(data);

								$.each(data, function(i, post) {
									content += '<li>' + post.post_title + '</li>';
								});

								$(content).appendTo("#search-results");
							},

						
						error: function(errorThrown){
						   alert('error');
						   console.log(errorThrown);
						}
			 
			}); 

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: Certified Penetration Testing

This CPTE Certified Penetration Testing Engineer course covers everything you need to know about becoming a Certified Penetration Testing Engineer. Career Path: Professional roles include Ethical Hackers, Security Consultants, System Administrators, and Chief Security Officers.

  • 4
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now