Escape Utf-8 inside of json array using php or javascript - php

I created a php script which execute select statement on postgres database. I transform the result into json string and pass it to javascript variable using <? echo $a; ?> line.Problem I can't solve is that my json from php contain polish characters (utf-8) encoded, and when javascript get this value i get Uncaught SyntaxError: Unexpected identifier and it is totally fine because the string is not escaped.Here it is how i do this:php generation of json:
<? $result_json = json_encode($result); ?>
and how I pass it into js:
options_json='<? echo $result_json; ?>';
When I debug in the browser my options_json look like:
options_json='[{"code":"za\u0105e ba\u0144stre.".....
I tried escape() utf8_encode() and addslashes(). First with no result, the addslashes() function removed the error but it destroyed json structure so I could not pares it back..

Simply try to return json encoded values like this example :
$arr_rslt=array();
$query=" Select col1,col2,col3 from tbl";
$result = mysql_query($query);
while( $row = mysql_fetch_array( $result ) )
{
$arr_rslt[] = $row;
}
echo json_encode($arr_rslt);
on client side if you using $.ajax or $.post then manipulate this in their callbacks.
also use this in your $.ajax.
contentType: "application/json; charset=UTF-8",

It might be useful for you i am using the below function to encode the arrays those having arabic texts.Just try the below function. I am not dealing with slashes.
public function utf8_encode_all($dat) // -- It returns $dat encoded to UTF8
{
if (is_string($dat)) return utf8_encode($dat);
if (!is_array($dat)) return $dat;
$ret = array();
foreach($dat as $i=>$d) $ret[$i] = $this->utf8_encode_all($d);
return $ret;
}

Related

Echo JSON through a loop in PHP?

I have a loop that grabs DB values and creates an object. I want to echo a JSON object every time the loop is iterated through. As of now, I just get blank in my console. Also, those commented out printf statements work fine. Any help would be much appreciated!
AJAX call
$.ajax({
url:'ajax/ipGet.php',
type: 'GET',
dataType:'json',
success:function(response){
console.log(response);
}
});
PHP Data Generation
$infoArray = new Array();
while($row = mysqli_fetch_array($getIpQuery, MYSQLI_NUM)){
for($x=0;$x<count($row);$x++)
{
$getIpInfo = mysqli_query($dbcon,"SELECT * FROM ipInfo WHERE address='$row[$x]'");
$retrievedInfo = mysqli_fetch_array($getIpInfo,MYSQLI_NUM);
$ipInfo->ipAddress = $retrievedInfo[0];
$ipInfo->port = $retrievedInfo[1];
$ipInfo->status = getStatus($ipInfo->ipAddress, $ipInfo->port);
array_push($infoArray,$ipInfo);
}
}
echo json_encode($infoArray);
Thanks for any help!
~Carpetfizz
json must be a single self-contained entity. You're outputting MULTIPLE separate bits of JSON text, which is incorrect.
JSON encoding should be the very LAST thing you do, e.g.
while(...) {
$array[] = ....
}
echo json_encode($array);
Consider what you're doing from the client perspective... building an array of ipinfo, so you run the loop once and produce
{"ipAddress":"127.0.0.1","port":80,....}
But you're doing it multple times, so you end up with
{"ipAddress":"127.0.0.1","port":80,....}{"ipAddress":"127.0.0.1","port":80,....{"ipAddress":"127.0.0.1","port":80,....}
as your output, and now you've got illegal javascript. Remember that JSON text is essentialy the right-hand-side of a Javascript assignment operation, e.g.
var somevar = ...json_goes_here...;
So you're doing
var stuff = {...}{...}{...};
which is an outright syntax error, instead of
var stuff = [{...},{...},{...}];
which would be correct.

Echo/return an array in php

Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);

Encode HTML for JSON string

I am storing html in a mysql database as raw html. I am pulling the contents and placing it into an array as follows. The array is the json_encoded, but if there is any double quotes or urls then the javascript displaying the JSON string breaks.
Is it possible to encode html to work through JSON?
Here is an extract of what I am using
<?php
$rows = array();
$sql ="SELECT html FROM table";
try {
$sth = $dbh->query($sql);
while($r = $sth->fetch(PDO::FETCH_OBJ)) {
$rows[] = $r;
}
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that. $e";
}
?>
var json = JSON.parse('<?php print json_encode(json_encode($rows)); ?>');
The json string currently outputting throws a javascript error saying unexpected <
[{"html":"<a href="http:\/\/www.url.com">\n<img src="http:\/\/www.url.com\/img\/logo.png">\n<\/a>"}]
Please no lectures on why this may be a bad thing. This is what my client has requested specifically and I just need to know if it is possible.
I agree with Mark B's answer but you could use fetchAll() and json_encode() the result of this function. Why do you use PDO Object fetching instead of array fetching?
<?php
$rows = array();
$sql ="SELECT hmtl FROM table";
try {
$sth = $dbh->query($sql);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that. $e";
}
?>
var json = <?= json_encode($rows); ?>;
Moreover consider getting it via AJAX.
There's no need for the json.parse business. JSON IS valid javascript after all, so a simple
var json = <?php echo json_encode($rows); ?>;
is all you need.
The line
var json = JSON.parse('<?php print json_encode(json_encode($rows)); ?>');
...is susceptible to single quotes in the resulting JSON (and other things; you'd have to double-escape lots of stuff). But you don't need or want to do that. Do this:
var json = <?php print json_encode(json_encode($rows)); ?>;
json_encode returns valid JSON, and JSON is a subset of JavaScript object initializer syntax, and so the above will result in valid JavaScript code describing the object. If you're outputting JavaScript code, as you appear to be from that line, there's no reason to go indirectly through a string. And as you've found, there's a reason not to.
Before filling the JSON object, you could use htmlentities() to convert all applicable characters to HTML entities, and then when printing them out just use html_entity_decode() if you use an ISO standard as character set. Sorry if I might have misunderstood the question.

jQuery ajax() returning json object but not alerting properly

How come i can't return id using data[0].id?
$(document).ready(function(){
$.ajax({
type: 'POST',
dataType: "json",
url: '<?php echo matry::base_to('tests/map_it');?>',
success: function (data)
{
alert(data[0])
$('#alerts').html(data);
data[0].id
}
});
});
Here's the alert that's returning.
{"id":19385,"first":"RLY","last":"MAZI",
"trainer_address1":"19 NE 13H CRT",
"trainer_address2":null,"CITY":"MII","STATE":"AL",
"trainer_zip":"33333","trainer_phone":"(721)222-4444","trainer_fax":null,
"trainer_cell":"(213)213- 2133","website_trainer_id":115,"trainer_email":"MO#gmail.COM",
"trainer_group":"","inactive":null}
Any help would be greatly appreciated.
EDIT
Here is the php that returns that json:
$mapit = sql::results("Select * from event.ACS.trainer where inactive is null or inactive=0");
foreach ($mapit as $row)
{
$return[] = json_encode($row, JSON_FORCE_OBJECT);
}
echo json_encode($return);
I have to loop through and encode each row because, otherwise, the ajax function doesn't think there is json that is returned (and my data var is empty)
Your real issue is in your PHP:
$mapit = sql::results("Select * from event.ACS.trainer where inactive is null or inactive=0");
foreach ($mapit as $row)
{
$return[] = json_encode($row, JSON_FORCE_OBJECT);
}
echo json_encode($return);
You are double json_encoding your data, which is causing the inner JSON to be treated as a string in JSON form when returned to your Javascript.
You should be doing it as follows:
$mapit = sql::results("Select * from event.ACS.trainer where inactive is null or inactive=0");
foreach ($mapit as $row)
{
$return[] = $row;
}
echo json_encode($return);
Notice I've removed the innermost json_encode.
Now, you don't need to use the .parseJSON() call in your Javascript. This solution will be much more efficient than the accepted solution, which didn't address the real problem.
It will be more efficient because
You aren't double encoding data that doesn't need to be encoded in
PHP.
You aren't decoding data that didn't need to be encoded in
Javascript.
Thus, you eliminate 2 needless operations, and many wasted cycles (because those operations are contained within loops).
data[0] looks like JSON, so you'll have to parse it before you can use it as an object. e.g. $.parseJSON(data[0]).id
It looks like it is just a single object being returned rather than an array so you should be able to access the id property using data.id , no need to specify an array index.
Try adding "Content-Type: application/json" to your response headers. Adding this header Google Chrome, Opera, Safari and IE will automatically convert your string to a JSON oject.
The parseJSON will only be needed on Firefox if you add this header.
If you don't wish to add that header then "JSONObject = jQuery.parseJSON(response);" is required in your javascript to convert the string to a JSON object.

Passing PHP array to Javascript via GET

I'm trying to pass an array to Javascript after it has sent a GET request to PHP.
Sending and retrieving the data works perfectly but I couldn't find anything about passing the data back as an array like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo $result_as_javascript_array;
?>
<script>
$('result').innerHTML = httpGet.responseText
</script>
Convert the data you get from MySQL to JSON. First build a "normal" PHP array as you would normally do, then pass it through the json_encode() function and return it.
On the client you have to parse the JSON string into a JS array or object. See this SO question for details: Parse JSON in JavaScript?
And please use something else for accessing MySQL. The extension you are using is basically obsolete: http://si1.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
you should use json_encode, which works fine, when directly assigning output to a javascript variable
<?php
$result = mysql_query('blablabla');
//first convert result to an associative array
$myarray = array();
while($fetch = mysql_fetch_assoc($result)){
$myarray[]=$fetch;
}
//converting $result to an array?
echo "<script>";
echo "var myArray = ".json_encode($myarray).";";
echo "</script>";
?>
<script>
//now you can use myArray global javascript variable
$('result').innerHTML = myArray.join(",");
</script>
You are looking for json_encode.
Use json_encode like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo json_encode($result);
?>
You probably won't want to put the response text right into the innerHTML of your element though unless you are wanting to display the json text in the element.
$arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = $row;
}
echo $arr;
However, mysql_ is deprecated, use mysqli instead.
If you want to pass it as JSON, use this:
echo json_encode($arr);

Categories