jquery - PHP AJAX call to MySQL database. How to properly escape HTML data returned (json_encode) to page? -
my database contains records included html scripting tags. have read many different options on how handle scenario while using json_encode/ajax.
should use js function escape special characters client side or might there php solution i'm missing?
edit assumption: user not want strip/remove html tags, wants way or suggestion in encoding them either on server or client side!
php (process.php):
$records = array(); if($results = $db->query("select * cust_tbl")) { if($results->num_rows) { while($row = $results->fetch_object()) { $records[] = $row; } echo json_encode($records); $results->free(); } }
ajax:
function show() { clear(); $.ajax({ type: "post", datatype: "json", url: "process.php", data: "action=show", success: function(data) { $.each(data, function(index, data) { $('#tablebody').append('<tr>'); $('#tablebody').append('<td>' + data.jl_job_date + '</td>'); $('#tablebody').append('<td>' + data.jl_yr + '</td>'); $('#tablebody').append('</tr>'); }); } }); }
if looking encode html sent: can use htmlentities()
if looking remove html tags , leave text: use strip_tags()
update:
i noticed in $.each
have 2 arguments using data
for. in $.each
typically this:
$.each(data, function() { //use data.<column name> });
unless need index of data suggest leaving out readability. documentation on $.each
can found here.
also, try doing full append @ once.
$.each(data, function() { $('#tablebody').append( '' + '<tr>' + '<td>' + data.<column name> + '</td>' + '<td>' + data.<column name> + '</td>' + '</tr>' + ''); });
doing way creates new row adds table datas end of table instead of in tr
want in.
Comments
Post a Comment