Return Subscript in JSON - javascript

I am trying to return a JSON object via AJAX using jQuery, that may contain elements that need HTML Tags. It is not great practice to include HTML tags within a JSON response and even so, it will be encoded at the other end so may cause more problems.
Consider this result:
{
"Country_Code":"EL",
"Country_Name":"Greece",
"Total_Value":5,
"Formatted_Value":"5m3"
}
The 'Formatted_Value' needs to look like this: 5m3. My question is simply, what would be the best way to achieve this with a returned JSON object?
If HTML is the best way then I will implement this, but only as a last resort as returning markup in a JSON request is not very good.

you could change the Json in this way:
"Formatted_Value":"5m³"
Using ³ (³) entity: http://code.google.com/p/doctype-mirror/wiki/Sup3CharacterEntity

Related

Passing php array to javascript function from external php file

I'm working on autofilling an html form based on data from a sqlite database.
I'm using a modified version of the code from this site and in its basic feature it works as expected.
The main input element calls, "onkeyup", a javascript function called "lookup", that in turn calls a external php script passing the current string to query the database.
The script returns a string to update the input form:
echo '<li onClick="fill(\''.$result->value.'\');">'.$result->value.'</li>';
The javascript function "fill" is as follows:
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
"#inputstring" is simply an input element.
What I would like to do instead of returning a string is to return an array and parse it inside the "fill" function to assign the different values to different elements in html.
The problem is that to pass the php array to javascript I have to convert it somehow. I've tried to make it a json string as suggested many times here on stack, but for what I suppose is a problem of quotes, it always return a null value.
I've tried:
$valuetopass = json_encode($query_result);
whithout
echo '<li onClick="fill('.$valuetopass.');">'.$query_result['text'].'</li>';
and with quotes
echo ''.$query_result['text'].'';
And both fail.
I'm aware that similar question have been already asked 1, 2,ecc... But all of the answers suggest to embed php when assigning the javascript variable. In my case the php is called from the function "lookup" and from that php script I want to return to the function "fill".
How can I produce from inside php a string that includes a json string with a format that can be passed to the "fill" function?
Or alternatively how can I rework the problem so that I don't need to do it at all?
Your JSON string is likely to contain ", so of course you get a syntax problem when you insert that into onClick="fill(...);" untreated.
Using PHP’s htmlspecialchars should be able to fix this in this instance.
In the long term, you might want to look more into the separation of code and data though.
Attaching event handlers using inline HTML attributes is kinda “old-school”, today that should rather be done from inside the script, using addEventListener resp. whatever wrapper methods a JS framework might provide for that. The JSON data could then for example be put into a custom data attribute, so that the script can read the data from there.

What is the right way to pass data from PHP application to JS?

Let's say i want to open a PHP page and without another request, pass some JSON data directly to the browser, so it will be accessible to my Javascript functions.
I don't know the right way to do it, but what i do currently is something like this :
<textarea id="mydata" style:"display:none">[{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}]</textarea>
I put the data inside a invisible textarea and now the data inside 'mydata' textarea is accessible by JS doing something like this :
var myData = JSON.parse($('#mydata').val());
Although this works, somehow it does not seem to me the right way to do it... I know i could avoid to 'dirty' the html code by getting the data using Ajax after the page opens, but what i'm trying to do here is avoid more requests, so with only one request, everything will be accessible. Actually in my application i have about 5 textareas like these, so with only 1 request to the server i get all data needed.
Thanks
From PHP's perspective, there is no difference between this:
<textarea id="mydata" style:"display:none">[{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}]</textarea>
and this:
var myData = [{code:1,name:'John'},{code:2,name:'Mary'},{code:3,name:'Paul'}];
Both of the above take the form of:
[a string][the serialized object][a string]
Whether you're surrounding the values with HTML or with JavaScript, that surrounding decoration is just raw output strings as far as PHP is concerned. So there's no need to add the extra step of outputting the JSON to a form element and then using JavaScript to get the form element's value as a string and parse it back to an object. You can just emit the object itself directly to JavaScript code.

How to read Python list in Javascript [in a Django template]

I'm programming in oTree (which is a Django based environment for social experiments) and I have the following problem. I defined some lists in Python and I'd like to import them and use them in an HTML template. If I print them in HTML I manage to see them without any problem, however, once I need to use them in Javascript, the program fails to read them and the single quotes of the elements of the list are converted in '.
The list is imported like this var filtered_elements = {{ array }};.
I think the problem is exactly here, as JS cannot work with them. Do you have any suggestion on how to do that? I considered using JSON, but since I'm quite new to programming, I cannot understand if it's just a waste of time or there is a simpler way out.
Thanks for your answers!
It sounds like your data is already JSON, otherwise you would be getting single quotes and u prefixes. So the only issue is Django autoescaping; you can disable it with the safe filter:
var filtered_elements = {{ array|safe }};
Your data should be JSON, instead of putting the Python list into the contact directly, put "array": json.dumps(array) in the context dictionary.
The JSON string doesn't need HTML escaping inside a tag, but it does need JS escaping! Otherwise some string may include something like </script><script>absolutely anything goes here... to run arbitrary JavaScript, if the JSON contains user data.
So use |escapejs:
var filtered_elements = {{ array|escapejs}};

Return JSON with object model or JSON with parsed view

I'm creating website with lots of AJAX logic. I started to wondering should I return JSON with object model (because I have to make some requests and then replace/insert some html nodes in response) like:
{ 'Author' : 'Name#Surname', 'Email': 'some#email', 'listOfSomething' = [...], ...} //very advanced JSON
and then use some js template engine to parse my object and insert in the right place in the DOM
OR
return JSON with parsed razor template so something like:
{listOfSomething: [{id:0, parsedView:ASP.NET.ParseViewWithModel(MyModel[0])},{id:1, parsedView:ASP.NET.ParseViewWithModel(MyModel[1])}, ... ]}
the pros of second choice is that it will require much less logic but. Which approach should be use and when? Is the second approach may be good solution?
If what is being returned is only used in one place, then I would say option two is a good approach since you can tailor the HTML specifically for where it is going to be used and all you have to do is simply inject it into the DOM.
Otherwise, if what the AJAX returns is used in multiple places, then I would stick to returning JSON and let each client do what it needs with the raw data.
Also, if third-party developers are using it, then JSON is definitely the way to go.

Does anyone recogonize this format?

I saw this string from an ajax call on some. It's clearly some sort of template. a:15 means there're 15 items in the {} expression. i:0 means item0, s:63: means the length of the string after it. I google for a while, but could not find any JS template engine that can take input like this one. It is possible they use Regex to parse the data.
a:15:{i:0;s:63:\"http://ww2.some.web/mw600/c01b8166jw1e4cf9fu2s0j20dw08v0v4.jpg\";i:1;s:63:\"http://ww4.some.web/mw600/c01b8166jw1e4cf9h284bj20dw0980ut.jpg\";i:2;s:63:\"http://ww1.some.web/mw600/c01b8166jw1e4cf9ksczrj20dw097n20.jpg\";i:3;s:63:\"http://ww3.some.web/mw600/c01b8166jw1e4cf9jvzymj20dw09840f.jpg\";i:4;s:63:\"http://ww2.some.web/mw600/c01b8166jw1e4cf9m9j9rj20dw0av41i.jpg\";i:5;s:63:\"http://ww3.some.web/mw600/c01b8166jw1e4cf9n1iq2j20dw0990ue.jpg\";i:6;s:63:\"http://ww2.some.web/mw600/c01b8166jw1e4cf9q062tj20dw09en17.jpg\";i:7;s:63:\"http://ww3.some.web/mw600/c01b8166jw1e4cf9sprglj20dw0a1djh.jpg\";i:8;s:63:\"http://ww1.some.web/mw600/c01b8166jw1e4cf9srts5j20dw097jui.jpg\";i:9;s:63:\"http://ww2.some.web/mw600/c01b8166jw1e4cf9wj84oj20dw08zn02.jpg\";i:10;s:63:\"http://ww1.some.web/mw600/c01b8166jw1e4cf9ws795j20dw09o418.jpg\";i:11;s:63:\"http://ww3.some.web/mw600/c01b8166jw1e4cf9xpixhj20dw0990ty.jpg\";i:12;s:63:\"http://ww3.some.web/mw600/c01b8166jw1e4cfa05o8fj20dw099die.jpg\";i:13;s:63:\"http://ww4.some.web/mw600/c01b8166jw1e4cfa0ah9yj20dw0aa76h.jpg\";i:14;s:63:\"http://ww3.some.web/mw600/c01b8166jw1ehttp://ww2.some.web/mw600/c01b8166jw1e4cf9fu2s0j20dw08v0v4.jpgcfa1jpsaj20dw099myq.jpg\";}
Looks like result of PHP serialize() function
You can use this js function to parse it.
This is PHP serialization format. You can unserialize with php:
unserialize(...)
And you'll get an array (with your example) if I'm not wrong

Categories