tags:

views:

8892

answers:

7

Hey,

i am trying to find the best way to display results on my page via an Ajax call using jQuery, do you think the best way is to pass it as JSON or plain text? I have worked with ajax calls before, but not sure which is preferred over the other and for the JSON version what is the best way to read from a JSON file generated by a PHP page to display my results.

i know I would include a .each to run through it to display them all./

Thanks,

Ryan

+5  A: 

JQuery has an inbuilt json data type for Ajax and converts the data into a object. PHP% also has inbuilt json_encode function which converts an array into json formatted string. Saves a lot of parsing, decoding effort.

braindead
+1  A: 

You can create a jQuery object from a JSON object:

$.getJSON(url, data, function(json) {
    $(json).each(function() {
        /* YOUR CODE HERE */
    });
});
strager
+1  A: 

Hey,

i did see both of those and i am encoding my JSON using PHP, then reading it using a code similar to above, but ia m confused on retrieving those values to print would they look like:

json.DATA or where data is, is my object I am sending from my JSON?

Ryan

Coughlin
+4  A: 

Something like this:

$.getJSON("http://mywebsite.com/json/get.php?cid=15",
        function(data){
          $.each(data.products, function(i,product){
            content = '<p>' + product.product_title + '</p>';
            content += '<p>' + product.product_short_description + '</p>';
            content += '<img src="' + product.product_thumbnail_src + '"/>';
            content += '<br/>';
            $(content).appendTo("#product_list");
          });
        });

Would take a json object made from a PHP array returned with the key of products. e.g:

Array('products' => Array(0 => Array('product_title' => 'Product 1',
                                     'product_short_description' => 'Product 1 is a useful product',
                                     'product_thumbnail_src' => '/images/15/1.jpg'
                                    )
                          1 => Array('product_title' => 'Product 2',
                                     'product_short_description' => 'Product 2 is a not so useful product',
                                     'product_thumbnail_src' => '/images/15/2.jpg'
                                    )
                         )
     )

To reload the list you would simply do:

$("#product_list").empty();

And then call getJSON again with new parameters.

Jay
For performance reason that $(content).appendTo("#product_list") should be outside of the loop. Appending to DOM is slow and should be done only once.
Rosdi
+1  A: 

Perfect! Thank you Jay, below is my HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml"&gt;
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Facebook like ajax post - jQuery - ryancoughlin.com</title>
<link rel="stylesheet" href="../css/screen.css" type="text/css" media="screen, projection" />
<link rel="stylesheet" href="../css/print.css" type="text/css" media="print" />
<!--[if IE]><link rel="stylesheet" href="../css/ie.css" type="text/css" media="screen, projection"><![endif]-->
<link href="../css/highlight.css" rel="stylesheet" type="text/css" media="screen" />
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
/* <![CDATA[ */
$(document).ready(function(){
    $.getJSON("readJSON.php",function(data){
     $.each(data.post, function(i,post){
      content += '<p>' + post.post_author + '</p>';
      content += '<p>' + post.post_content + '</p>';
      content += '<p' + post.date + '</p>';
      content += '<br/>';
      $(content).appendTo("#posts");
     });
    });   
});
/* ]]> */
</script>
</head>
<body>
        <div class="container">
                <div class="span-24">
                       <h2>Check out the following posts:</h2>
         <div id="posts">
         </di>
                </div>
        </div>
</body>
</html>

And my JSON outputs:

{ posts: [{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"This is a post","author":"Ryan Coughlin"}]}

I get this error, when I run my code:

object is undefined
http://localhost:8888/rks/post/js/jquery.js
Line 19
Coughlin
I got it, i changed: $.each(data.posts, function(i,post){So data.post -> data.posts
Coughlin
+1  A: 

I have my new code: http://pastie.org/326665 - but it is display two results of my first entry and when I check in my tables using NaviCat, it shows only 2 results, and when I print it it has TWO of the first and one of the second

Any thoughts?

Below is my JSON output:

{ posts: [

{"id":"1","date_added":"0001-02-22 00:00:00","post_content":"Check out my content, this is loaded via ajax and parsed with JSON","author":"Ryan Coughlin"},

{"id":"2","date_added":"0000-00-00 00:00:00","post_content":"More content, loaded. Lets try to add a form in and post via ajax and append the new data","author":"Billy Bob"}

]}
Coughlin
you need to update your question with these details and not post new answers like this. These are not answers.
spoon16
Sorry spoon, I will for further questions.Ryan
Coughlin
+1  A: 

Coughlin,

My mistake:

content += '<p>' + post.post_author + '</p>';

Should read:

content = '<p>' + post.post_author + '</p>';
Jay
Thank you so much for this and the code! I understand this now.Ryan
Coughlin
Any idea...why my latest post at the bottom is printing out duplicate results. I should updated my post, instead of posting a new answer...Ryan
Coughlin
Are you still having a problem?
Jay