Passing angled bracket in hex via JSON AJAX from PHP to JS - php

My system runs some MySQL queries in PHP to retrieve data. The data that is retrieved is structured in an array similar to below:
$ret = array(
"name" => "John Doe",
"location" => "Antarctica",
"description" => "Height < 200"
);
I return this through AJAX via:
echo json_encode($ret);
The AJAX error event is fired and upon inspection of the returned data (jqXHR.responseText) via Chrome console, I'm noticing:
"description" : "Height \x3c 200"
which is throwing a parse error.
I know that \x3c is the hex representation of "<" and apparently, that form renders the JSON invalid. I can't seem to find a way to make it such that I'm able to pass the angled bracket via JSON in a valid form. Direct string replace of "\x3c" on the PHP side doesn't work.
Further, I know that specifying the AJAX return as HTML will work, but I'm passing a set of data hence the use of JSON.

Try this:
echo json_encode( $ret, JSON_HEX_TAG );
Use json_last_error() to debug.
http://www.php.net/manual/en/function.json-decode.php

Using the native Chrome JSON object (window.JSON), i am able to parse the output from you php program no problem,
"description" : "Height \x3c 200"
and am able to serialize that into a javascript JSON object.
var jsonString = JSON.stringify({"description": "Height \x3c 200"});
//jsonString has the value "{"description":"Height < 200"}"
var jsonObject = JSON.parse(jsonString);
//jsonObject has an object that looks like this
//Object
//description: "Height < 200"
//__proto__: Object
if you need compatibility with browsers that don't support a native JSON object, i would recommend using a library such as JQuery.
Additionally, the json_encode() function in PHP can be passed a configuration object to customize exactly how your JSON is encoded, if you don't like the '\x3c', you can change it to something your javascript parser may like better like '&lg;' :)
http://php.net/manual/en/function.json-encode.php

Related

Send xml string in json object using php slim

I have written a REST Api using slim framework 3, and returning response in JSON like this,
return $response->withHeader(
'Content-type',
'application/json; charset=utf-8'
)->withJson($data, 200);
which is working fine.
$xml = '<?xml version="1.0" encoding="UTF-8"?><dialog createdBy=""createDate=""><dialog>' // looks like this
$data = [
'name' => 'xmlName',
'xml' => $xml // fetching from db
]
Now, I have xml string stored in database and want to send it to the client end, I have to save that xml string as in another database as it is.
But when I encode xml string, my json gets break.
I have also tried like,
json_encode($data, JSON_HEX_TAG);
which converts my xml to.
"\u003C?xml version=\"1.0\" encoding=\"UTF-8\"?\u003E\n\u003Cdialog createdBy=\"\"
How can I correctly encode the xml in JSON and then get back the original xml string as it is?
Your feedback is much appreciated.
If you look at the withJson() source code you'll see that all it does with data is processing it with json_encode()—nothing special on the Slim side. In fact, your XML is just fine: \u003C and \u003E are the entities for < and >. Remember that JSON is a data format for computers, not people!
Additionally, the JSON spec states that you need to have a top level object or array. So you can't just send a string back to the client and expect it to be processed as JSON because it will not be JSON. If json_encode() does not just crash it's because it has been designed to encode partial JSON since it's a useful feature some times. You absolutely need to design a valid JSON structure, e.g.:
->withJson(array($xml), 200)
Actually I just found my answer by the hint of htmlentities #Álvaro González gave.
I just converted my xml string like,
[
'name' => 'xmlName',
'xml' => htmlentities($xml)
]
I am able to receive the xml string as it is without any json break.

When using GET in php for data generated with jQuery's $.param(data), there are %5B and %5D

I have JSON data called rowdata that I use in an ajax call. If I use:
JSON.stringify(rowdata)
it looks like like the following:
{"Description":"qwerty","Code":"12345","Size":"11","Colour":"green"}
I do send it to php and use a GET statement (Joomla's
JRequest::getVar("Description", "", "", "")
statement) to get the elements of rowdata but I cannot succeed.
If I look at the ajax data that has been send I do have the following:
rowdata%5BDescription%5D=qwerty
etc. after applying:
$.param(data)
I have used many version instead of "Description", but to no avail. I tried to get rowdata on its own and access its elements, but no success. I cannot find out what the %5B and %5D means, searching for that is problematic with the % sign. Anyone who can help to get the values of Description, Code, etc. in php?
You are sending JSON, but trying to parse it as application/x-www-form-urlencoded data.
Don't convert the object to JSON.
$.get('example.php', {"Description":"qwerty","Code":"12345","Size":"11","Colour":"green"});
I believe %5B is [ and %5D is ]. Your URL is encoding special characters. It's called URL encoding.
Do not use JSON if you want to push data with get... otherwise it will be encoded to satisfy JSON format and you will get those entities.
$.get('target.php', {"Description":"qwerty","Code":"12345","Size":"11","Colour":"green"});

Beginner to creating and reading JSON objects

Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can't get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
Your PHP file contains JSON, which is not valid PHP, and will therefore error.
If you're working with PHP the easiest way to build JSON is to first prepare your data as an array (associative or indexed, as required) then simply convert it via json_encode(). (You can also decode JSON, with the corresponding json_decode().
[EDIT - in response to comment, just have a look at the PHP docs for json_encode() - it's very self explanatory. You take an array, pass it to json_encode(), and you get a JSON string.
$arr = array('one', 'two', 'three');
echo json_encode($arr); //JSON string
JSON is not a programming language, and it's certainly not executable as PHP. It's just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any <?php tags. (Of course, as with HTML, you can also make it a .php file and just not have any PHP in it, other than something to set the Content-Type since the file suffix won't do it automatically. But that's wasteful.)
If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
<?= json_encode( array(
'Contact' => array('ID' => 1, 'Name' => 'Brett Samuel' )
) ); ?>
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).
you need to use json_encode and json_decode
refer this json php manual

Pass a list from php or xmlhttp.responseText to javascript

I have a list in javascript that is to be changed by the content of a database when the user clicks a link or slides a bar. I currently use a xmlhttp request to fetch a php page which generates the list.
I have a static list working in this form:
var mark_list = [
{ "EntID" : 3, "x" : 100, "y" : 400},
];
I tried to have the php page generate the { "EntID" : 3, "x" : 100, "y" : 400} and set mark_list equal to responseText but I believe that's just a string. I'm struggling to find a way to get this new list into the variablie.
Does anyone have any suggestions or solutions? Your help would be greatly appreciated.
Kallum
Make sure the browser has a JSON object by including the json script from here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
It will defer to the native browser JSON object if available, and if not, will add it so that this functionality is available in browsers that don't currently support it.
Then in your code, after you receive the output from the PHP script, run this:
var mark_list = JSON.parse(responseText);
Based on the output from the PHP script, you may need to do this:
var stuff = JSON.parse(responseText);
var mark_list = [stuff];
This will convert the JSON string the PHP returns into an actual javascript object.
In your PHP code you can do something like this:
$output = array(
array(
'EntId' => 3,
'x' => 100,
'y' => 400,
),
);
echo json_encode($output);
Then you can use the var mark_list = JSON.parse(responseText); option in your JavaScript.
responseText will indeed just be a text represented by a string, so the way you are outputting it right now won't just do the trick all on its own. There are basically two ways you can do this:
In your javascript, you parse the output the server is giving you. This can be done onn a pure string in whatever way you feel like doing it. For example, you could write javascript to parse the format you gave with curly braces and a colon based syntax. Alternatively, you could use another format (like XML) which will reduce the work a little, but will still leave the interpreting of the output for you to do in the javascript.
You can output to a format used to describe objects and lists. JSON would be the big example of such a format. If you output in JSON, you will get something that resembles the format you used above (JSON stands for Javascript Object Notation and is based on parts of the syntax of javascript) and all you will have to do to be able to use it is to get to the data you want to get to. You can use JSON.parse() for this on most browsers, but an alternative with more widespread support is jQuery's jQuery.parseJSON() (for which you would use jQuery, which you should also provide in that case)

JSON Encode/decode doesn't work as it should

I am preparing and sending a JSON string from my PHP file to my Javascript function like this:
$json = array();
$json['slice'] = false;
$json['G500'] = false;
$json['KG1'] = false;
$encoded = json_encode($json);
die($encoded);
However, in my JS function, if I do this, it is unable to decode the JSON object:
var d = req.responseText;
var jsonObject = eval(d);
The only way, I can get it to eval the JSON object is by adding parentheses manually
jsonObject = eval("(" + d + ")");
I have the same problem going in reverse as well. Sending a JSON object to PHP and trying to decode it there fails. I believe I would need to remove the parentheses in my PHP script before attempting to decode.
Why is this happening? Is there something I can do to work around this incompatibility?
EDIT:
PHP to JS is now working if I use JSON.parse. I'm still having trouble the other way around.
This is how I'm sending the data to the PHP:
var JSONstring =
{
"Product": document.getElementById('item').value,
"Size": document.getElementById('size').value,
"Quantity": document.getElementById('quantity').value
};
url = "maintainOrder.php?json=" + JSON.stringify(JSONstring);
req.open("GET", url, true);
However, the PHP script is unable to decode it.
$newItem = json_decode($_GET['json']);
array_push($_SESSION['order'],$newItem);
Your Javascript
eval has an issue with leading { characters, because of an ambiguity with block scope.
Using the parentheses to force the input to be parsed as an expression is a solution, but you should avoid eval entirely and use a proper JSON decoding function.
Your PHP
We'd need to see the data that you send to your PHP script to know why it won't parse. In general, as long as JSONLint accepts your JSON, so will PHP's json_decode. So give that a go.
For the php to javascript issue refer to the Tomalak Geret'kal answer.
For the javascript to php maybe I have the solution:
If you want an associative array in php then you have to pass assoc parameter as true into json_decode (default to false)
Example:
$array = json_decode($jsonString, true);
I was bitten a couple of times by this: by default json_decode try to create an object if it receive a javascript object (it make perfect sense if you think of) and you have to force it to render an associative array if you need this behaviour
I think you need to do some string processing, all you need to do is echo and see the exact format of your JSON string and make sure it conforms to the standard format, then use string processing both on the server and client sides to achieve the desired effect
Are you sure php is not adding slashes to the json text?, try saving the json text in a file in the server side to verify

Categories