F. Certainly. F. Certainly. - 1 year ago 102
Ajax Question

How to remove quotes from each element in a javascript array containing JSON encoded html strings returned from a mysql database with php

Ajax call to the mysql data base using data1.php file with pdo returns hmtl strings that are put into an array, encoded with json and sent to the ajax response function for display in html. Of course the elements in the array have tags and quotations, which are difficult to remove. Easiest and closest solution so far is to replace the quotes in the strings with javascript .replace(). This doesn't work for the array of arrays unless the single element is referenced. What's the way around this? Here is the code.

Ajax call:

function processForm_L(){
var topic = $("#topic").val();
// send data
url: "../php/get_data1.php",
data: {
type: 'POST',
dataType: 'json',
success: processResult_L
}); // end .onclick

The response function:

function processResult_L(data, textStatus){
// Required Callback Function
if(data['status']['response'] == 1){
//if(data[0] == 1){
table_1 = [];
table_2 = [];
table_3 = [];

table_1 = data.table['a'].replace( /"/g,"");
table_2 = data.data.replace(/"/g,"");
table_3 = data.table['b'].replace( /"/g,"");

//table_1 = JSON.parse(data.table['a']);
//table_2 = JSON.parse(data.data);
//table_3 = JSON.parse(data.table['b']);
}//end if response == 1

else if(data.response == 0){
//var response = data + textStatus;
var table_4 = data.error;
}//end if response==0
}//end process results

The query part of get_data1.php

$ret_s = Array();//return status
$ret_t = Array();//return table
$ret_d = Array();//return data
$result = Array();
$row_1 = 1;



//connect to database and insert data
// include "db_connect_df.php";

// select everything from the raw_data database
$sql = "SELECT * FROM `raw_data`";

// prepare the sql statement
$stmt_s = $db->prepare($sql);
$result = $stmt_s->fetchAll(PDO::FETCH_ASSOC);

//set response variable
$ret_s['response'] = 1;

//table header
$ret_t['a'] ="<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr>";

//fetch each row from database as html
foreach($result as $row){
$ret_d[$row_1] = "<tr>" ."<td>" . $row['ID'] . "</td>" ."<td>" .
$row['Organization'] . "</td>" ."<td>" . $row['Telephone'] . "</td>" . "<td>" . $row['Email'] . "</td>" ."<td>" . $row['Website'] . "</td>" ."<td>" . $row['Country'] . "</td>" ."<td>" . $row['Region'] . "</td>" ."<td>" . $row['City'] . "</td>" ."<td>" . $row['Street'] . "</td>" ."<td>" . $row['Unit'] . "</td>" ."<td>" . $row['Postal_Code'] . "</td>" ."<td>" . $row['Topic'] . "</td>" ."<td>" . $row['Message'] . "</td>" ."<td>" . $row['ts'] . "</td>" ."</tr>";
// end table tag
$ret_t['b'] = "</table>";

//echo and encode array
echo json_encode(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d),JSON_HEX_QUOT|JSON_HEX_TAG);

// echo json_encode(stripslashes_nested(array('status' => $ret_s, 'table' => $ret_t,'data'=> $ret_d)),JSON_HEX_QUOT|JSON_HEX_TAG);
}//end connect
}//end try

catch (PDOException $e) {
$error16 = '<span class="error_s">Try again another time.</span>';
$error17 = '<span class="error_s">ERROR:' . $e->getMessage();
$ret_s['response'] = 0;
$ret_s['error'] = $error16 . $error17;
echo json_encode($ret_s);
} //end failure
}//end if is !empty($_POST)

Note: this queries a localhost database served through xampp. This isn't all the code but everything works just fine except the following:

table_2 = data.data.replace(/"/g,"");
returns 'data.data.replace() is not a function, because the array is an object not a string

2) when comment out above line and comment in only
result in console is:

<table id='display_table'><tr><th>ID</th><th>Organization</th><th>Contact Names</th><th>Telephone</th><th>Email</th><th>Website</th><th>Country</th><th>Region</th><th>City</th><th>Street</th><th>Unit</th><th>Postal Code</th><th>Topic</th><th>Message</th><th>Date</th></tr>
So that works.

3) similarly commenting in only
returns in console:

so that also works.

4) if comment in
table_2 = data.data;
and enter table_2 into console result is:


5) tried this code to remove quotes from the array of arrays:

a) putting a function in the js init file for the page:

function replace_quotes(x){
for(var i=0; i < x.length; i++) {
x[i] = x[i].toString().replace(/"/g,"");

and using that function on the data array in the data object created by the response callback function (so x = data.data)

result is undefined, and it doesn't work.

just runs into a
right away and won't parse, for any of the strings in the data array (table_2 or table 3).

didn't work.

Presumably looping through the array data.data with a function and using .replace() and a reg exp to replace quotes with nothing should be the easiest solution. Any tips on how to loop through a json_encoded array of html strings in an array returned in an ajax callback?

Answer Source

Don't replace anything anywhere. The only thing you need is to add htmlspecialchars() when you building the HTML string.

// ...
$rows = [];
foreach ($result as $r) {
    $rows[] = '<tr><td>'.htmlspecialchars($r['id'])
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => join("\n", $rows)));

Then, when you receive such JSON, just put it into HTML as it is.


But there is better way to implement this. -- Send only data without markup via JSON and build markup in JS:

// ...
$rows = [];
foreach ($result as $r) {
    $rows[] = [
        'id' => $r['id'],
        'phone_number' => $r['phone_number']
header('Content-Type: application/json; encoding=utf-8');
echo json_encode(array('table_rows' => $rows));

And then:

// ...
for(var i = 0; i < received_data.table_rows.length; i++) {
    var r = received_data.table_rows[i];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download