HTML output via JSON activated by ajax

Reference Information:

I have a page that dynamically pulls out a modal window that displays extended information in a row (with multiple columns) through mySQL. I am having problems when the JSON code will not correctly fill in the information so that it can be output. I tried several nested arrays, while loops and loops. However, I need to return only one row from the database. Scratching my head, I ask the help of all SO experts. Any pointers are greatly appreciated.

Ajax code for a population group (works)

var data_id = $(this).data('id'); $.ajax({ url: 'view_agency_info.php', type: 'POST', data: {id: data_id}, dataType: 'json', success: function(data){ $('.view_modal_content').html(data.html); // LOAD THE DATA INTO THIS DIV }, error: function(jqXHR, textStatus, errorThrown){ $('.view_modal_content').html(''); // LOAD THE DATA INTO THIS DIV alert('Error Loading Information'); } }); 

JSON code for outputting information and returning HTML

 <?php $customer_id=$_SESSION['customer']['customer_id']; $id = (int)$_POST['id']; $query = "SELECT * FROM collections_list WHERE id={$id} && customer_id=$customer_id LIMIT 1"; //expecting one row $result = mysql_query( $query ); //$message = mysql_fetch_assoc( $result ); //expecting just one row $message=array(); while ($row = mysql_fetch_assoc($result)) { $message[]=$row['agency_name']; $message[]=$row['account_number']; $message[]=$row['phone']; } $json = array(); $json['html'] = '<p><pre><code>id:'.$id.'.<br>Agency Name: '.$message[0].'<br>Account Number:'.$message[1]."<br>Phone:".$message[2].'</code></pre></p>'.'<br><br>test'; header('Content-Type: application/json'); echo json_encode( $json ); ?> 

Additional question:

Is it possible to refer to headers in an array using "$ message ['agency_name']" inside the returned html?

After solving this problem, I will need to turn the output html into a structure so that my users can view the information in a correctly understandable format. I know how to do this in html, but I am not familiar with JSON ... Is there a way to output information without having to manually encode the structure?

Thanks in advance.

+4
source share
1 answer
 $con = mysql_connect("localhost","user","password"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db(db_nname", $con); $result = mysql_query("SELECT phone,agency_name FROM '''' "); $rows = array(); while($r = mysql_fetch_assoc($result)) { $rows['results'][] = $r; } print json_encode($rows); ?> 

and in your html

  <table id ="listtable"></table> var listdiv = $("#listtable"); $.getJSON("whatever.php",function(json){ $.each(json.results,function(i,data){ listdiv.append("<tr><th>" + data.phone + "</th><th>" + data.agency_name + "</th></tr>"); }); }); 

and in add usage data. and regardless of your data.agency_name data.phone fields

etc....

+2
source

All Articles