?
Solved

Printing out JSON array returned

Posted on 2012-08-14
11
Medium Priority
?
1,044 Views
Last Modified: 2012-08-19
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
Comment
Question by:josefyeung
  • 4
  • 4
9 Comments
 
LVL 60

Assisted Solution

by:Julian Hansen
Julian Hansen earned 1000 total points
ID: 38292591
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
 
LVL 75

Assisted Solution

by:Michel Plungjan
Michel Plungjan earned 1000 total points
ID: 38292770
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
 

Accepted Solution

by:
josefyeung earned 0 total points
ID: 38292782
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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

Author Comment

by:josefyeung
ID: 38293349
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
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38293350
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
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38293361
@josefyeung, as a matter of interest why is it necessary to call the parsJSON explicitly - which call method are you using?

$.post
$.ajax

?
0
 

Author Comment

by:josefyeung
ID: 38293767
@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
 
LVL 60

Expert Comment

by:Julian Hansen
ID: 38294072
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
 

Author Comment

by:josefyeung
ID: 38294645
@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

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

PROBLEM: The other day I was working on adding an ajax request to a webpage that already had a dialog box on the page.  The dialog box was using relative positioning to be positioned next to a form field I had on the page.  Everything was working…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month14 days, 11 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question