jQuery & AJAX - JSON or HTML output

JackTheKnife

Limp Gawd
Joined
Mar 27, 2006
Messages
272
I have a dilemma - my script is passing data as POST and getting message as JSON from another script which is doing insert query to the DB. Now instead of a message I need to get a full results page from a select query after insertion.

Which way is better to follow - to get output as JSON or to generate HTML and display as a big DIV?

Thanks
 
im actually working with jQuery and JSON at this moment.
either way works. it depends on how complicated the output is.

i would say to go with pure JSON, use jQuery.getJSON(), loop through the data object and generate the table. mainly because if you wanted to pull this same data into another page and use it in another way, it would be simpler to manipulate. it can also be a lot faster depending on if you are pulling the data from another server.
 
OK, I'm stuck on an output from the second script. Idk why I am getting only first row from the select query as an output while everything goes through the results loop. 'Echo on the screen' version works flawless...
 
Main part of the first script which is passing data to do DB insert query:

PHP:
<script>
               $(document).ready(function(){
                    
                        $('#waiting').show(500);
                        $('#output').hide(0);
                        
                        $.ajax({
                            type : 'POST',
                            url : 'mince_now.php',
                            dataType : 'json',
                            data: {
                                pattern : "<?php echo $pattern; ?>",
                                pattern_id  : "<?php echo $pattern_id; ?>"
                            },
                            success : function(data){
                                $('#waiting').hide(500);
                                $('#output').removeClass().addClass((data.error === true) ? 'error' : 'success')
                                    .html(data.out).show(500);
                            },
                            error : function(XMLHttpRequest, textStatus, errorThrown) {
                                $('#waiting').hide(500);
                                $('#output').removeClass().addClass('error')
                                    .text('There was an error.').show(500);
                            }
                        });
                        
                        return false;
                });
</script>

<div id="output" style="display: none;"></div>
<div id="waiting" style="display: none;"><b>We gather all data. Please wait...</b><br /></div>

And there is a part of the second script which should to insert then select inserted data from the DB:

PHP:
			$sql = "SELECT TOP 10 *
					FROM tbl_Patterns_log
					WHERE Pattern = '".$pattern."' AND date_run = '".$today."'
					ORDER BY ID ASC
					";	
		
			//execute the SQL query and return records
			$results = mssql_query($sql)
					or die( "<strong>ERROR: Query failed</strong>" );
	
			while (  $row = mssql_fetch_array($results) )
			{
				$name = $row['name'];
				$path = $row['path'];
				$description = $row['description'];
				$color = $row['color'];
		
				$today_pattens[] = array('name' => $name, 'path' => $path, 'description' => $description, 'color' => $color);
				
			}
		
			foreach($today_patterns as $index => $today_pattern){
			
				if(!empty($today_pattern['name'])){
					$output = "<div class=\"listing-wrapper\">";
					$output .= "<div id=\"patterns;\">";
					$output .= "<strong style=\"background-color:".$colors[$today_pattern['color']]."; display: inline; \"><a href=\"".$today_pattern['path']."\">".$today_pattern['name']."</a></strong> ";
					$output .= "<em>".$today_pattern['description']."</em>";
					$output .= "</div>";
					$output .= "<div style=\"clear: both;\"></div>";
					$output .= "</div>";
				}
				else {
					//some logic similar to above
				}
				
				$htmlout .= $output;
			}

						
	if (!$return['error'])
    	$return['out] = $htmlout;

echo json_encode($return);
 
ok, first of all trying to encode HTML as JSON never worked well for me.
on very basic things you might get lucky but usually it just breaks.

since it seams like you are printing out a table-like structure, what you need to do is have one variable that contains the data for each row, no HTML, just the data and what column it should be in

json_encode that array containing all of your rows
in this case, i think that json_encode($today_pattens) is what you need

the actual HTML generation is done client side, in the javascript
here is a simple example of something i worked on today (with names edited out)

Code:
<script>

$.getJSON("http://mywebsite.com/script.php", function(data)
{			
	$('#container').html('');
	$('#container').append("<table border='1' cellspacing='0' cellpadding='3'>");
	$('#container').append("<tr><th width='100px'>Col Name 1</th><th width='100px'>Col Name 2</th><th width='100px'>Col Name 3</th></tr>");
	
	$.each(data, function(sid, row)
	{						
		$('#container').append("<tr><td>"+row.col1+"</td><td>"+row.col2+"</td><td>"+row.col3+"</td></tr>");			
	});

	$('#container').append("</table>");			
});

</script>

there are better ways to generate this, such as not generating the entire table again, just the <tbody> but i am trying to keep it simple here
your case is different since you have div's but it should be easy to understand

the .ajax function you use it the same as this, it's function(data) that you care about
 
Last edited:
if you love us you'll switch the php/html tags to plain code tags ;)
 
I did some json/php stuff to check a file for the latest version etc for a self updating files I did..

dono if this would help but it works well for me...

Code:
$json = json_decode(file_get_contents('http://www.domain.com/update.json'),true);

if ($json) {
  foreach($json as $key => $val) {
    #stuff to do
  }
}
 
I have switched everything to HTML response because I don't have a clue how to use getJASON with POST data from ajax :\
 
Back
Top