Due to the nature of my project. I am pulling data from my db and outputting to javascript. Things were working just fine till I got to the main content. It has strings like (;, :, - ''). How do I ensure that these are displayed without crushing my script coz as for now nothing seems to work.
If all you have is a single string value then see answer by Tomalak Geret'kal.
If there is any chance of getting something more than a single value from your database, like an array, object, null, or anything more complex, then I would suggest using json_encode. By using something like this:
<script>
var your_JavaScript_variable = <?php echo json_encode(your_PHP_variable); ?>;
</script>
you can pass complex data structures, arrays, or even single strings from PHP to JavaScript with all of your backslash escaping done automatically.
Additionally when you use JSON for moving your data from PHP to JavaScript it will be easy to make your application get the data from your server asynchronously without page refreshes using AJAX in the future.
You can use the PHP addslashes function for inserting into Javascript, and htmlspecialchars for inserting into HTML.
You should be encoding that data into json. PHP has a handy function to do this, json_encode.
Be sure to use the JSON_HEX_QUOTE option or the quotes in your data will break your js.
Read this: http://php.net/manual/en/function.json-encode.php
Related
I have a json_string in my database.
I echo and parse it to an object in javascript
I do
$.parseJSON('<?php echo $json_string;?>');
I get a json parse error.
What should I be doing?
This is my json_String
{"patches":[[{"diffs":[[1,"\u000a\u000a printhellon() {\u000a\u000a\u000a}d\u000a\u000a\u000a"]],"start1":0,"start2":0,"length1":0,"length2":26}],[{"diffs":[[0,") {\u000a\u000a\u000a}d"],[1,"s"],[0,"\u000a\u000a\u000a"]],"start1":15,"start2":15,"length1":11,"length2":12}],[{"diffs":[[0," {\u000a\u000a\u000a}ds"],[1,"d"],[0,"\u000a\u000a\u000a"]],"start1":16,"start2":16,"length1":11,"length2":12}]],"times":[1314489779299,1314489779408,1314489779581]}
I think JSON parsers don't like line breaks in strings for some reason. Parsing worked for me after removing the \u000a characters.
Edit: just like Brad said, it would be better to include the code directly as an object. Parsing JSON is usually more useful for data obtained using Ajax or something.
From your example, it appears like you're trying to insert PHP code into your javascript. You can't use PHP like that. PHP is server side, while Javascript runs in the browser after the page has been downloaded.
If you must get data from PHP to your javascript, you need to use AJAX. It's actually really easy with JQuery. Check out http://api.jquery.com/jQuery.ajax/
NOTE: this was a completely different question until I realized where the problem really was.
My current issue is that I am trying to output some JSON from PHP for use by jQuery. I am doing this cross-domain so I am using "JSONP". I have narrowed the problem down to the fact that there are single quotes in my JSON so when I output with the callback function I end up getting too many single quotes.
I have tried calling str_replace("'","\'",$value) in PHP and it seems to output as \\' in my JSON rather than \' which is apparently not readable by jQuery (though online JSON validators say the JSON is valid.
So what I need to know is how to get only a single slash in my string inside of PHP rather than 2 slashes.
What I'm gathering is this:
jQuery uses _ as a callback parameter to JSONP requests. It will automatically append ?_=jQuery<random_numbers> basically telling the server to call this unique function name when it returns. As such, as of recently (within the last year I want to say) .ajax takes care of making a callback function for you, then kind of "re-routes" it to a function you specify within the success property.
Also, your PHP code is using $_GET['callback'] when it now should be using $_GET['_'] (to stay more in-line with jQuery and what it's sending).
The "jQuery was not called" is just jQuery notifying you that anticipated callback wasn't included in the response, and it was looking to make sure it was getting called.
Short answer (as I see it) reference $_GET['_'] instead of $_GET['callback'] to satisfy jQuery.
try to use this in your PHP:
echo $_GET['callback'] . '(' . json_encode($your_array_data) . ')';
Regards.
I am trying to pass a php variable inside javascript bt it is not working.
Comment
Is it possible to do so or I may be incorrect somewhere...
Thanks for your response in advance! :)
First of all, you probably should change 'java' tag to 'javascript'.
Regarding your question - PHP is parsed on the server side, while Javascript runs on the client side. If you are not going to use AJAX and asynchronous calls, you could write values to the JS source, like this:
<script type="text/javascript">
var foo = <?php echo $yourData; ?>;
alert(foo);
</script>
Comment
You're dynamically generating Javascript. You will save yourself some headaches if when you need to do this you, keep it simple. Transfer the data from PHP to Javascript in the simplest way possible at the top of the page:
<script type="text/javascript" >
var $current = '<%? echo $current; %>';
</script>
As others have pointed out, you will want to encode and quote your php variable, using json_encode (in which case you probably won't need the quotes), or a simpler escape function if you know the possible values.
Now, your inline code can be simpler:
Comment
A final recommendation would be to pull this out into its own function, and use the "onclick" attribute.
Use json_encode() if your PHP has it.
This will automatically quote and escape your string and ensures that special characters are properly encoded to prevent cross-site scripting (XSS) attacks.
However, I think you will have to pass UTF-8 strings to this function.
And vol7ron has a good point – you should put a semicolon ; after your statement and put a space between that and the question mark ? for better legibility.
Comment
You can also pass booleans, ints and even entire arrays to json_encode() to pass them to JavaScript.
I need to be able to generate an effectively unlimited number of datasets, so what I want to do is something like this;
<input type="hidden" name="items[]" value="{id:1,name:'some-name'}" />
I tried JSON.stringify to convert my array in javascript and store it in the current hidden input element, but it wraps all the keys and values in double quotes, which obviously conflicts with HTML wrapping the entire value in double quotes. Somehow I need to escape the quotes, but I need this to work two ways...basically these elements are generated with PHP and placed in the page in order, then I can add or delete items on the user end and submit the page, which should have PHP iterating through these hidden elements and updating the records.
Anyone have any suggestions on an escaping method of some sort?
You can use escaping function presented here: http://phpjs.org/functions/htmlspecialchars:426
It should escape chars in json and make your string safe to use as value of html attribute.
If you want to do the escaping on PHP then you should use function htmlspecialchars() that is built in PHP.
What you want to do is grasp some of html5 data-* attrubites so you can dod
<div id="post-container" data-meta="{id:22,name:'Robert Pitt'}">
..
</div>
Then you can use htmlentites() to make the string safe and use javascript, you can get the data with javascript like so:
function ElementJson(id,attrib)
{
var post_c = document.getElementById(id);
for( var x = 0; x < post_c.attributes.length; x++)
{
if( post_c.attributes[x].nodeName.toLowerCase() == 'data-' + attrib.toLowerCase())
{
return post_c.attributes[x].nodeValue;
}
}
return false;
}
json = ElementJson('post-container','meta');
Via jQuery for instance you can do
json = $('#post-container[data-meta]').attr('data-meta');
A lot of large sites use it especially Facebook
base64_encode the data or run it through htmlentities() to turn the quotes in to entities :)
To be honest, if you are setting the value in javascript in the page then I am a little surprised that you ran into problems but here are a couple of suggestions: -
Of course the proper thing to do is HTML encode the data in the html attributes - but this requires calling htmlentities or similar so instead, why not URL encode the data using the "built in" javascript encode and decode and methods. URL encoding should escape double quotes to '%22'.
Or if you are already using jQuery, use the val() method to set (and get?) the value - I am sure that would deal with these issues for you (although I have not gone and actually checked this).
I'm playing with the flickr api and php. I want to pass some information from PHP to Javascript through Ajax. I have the following code:
json_encode($pics);
which results in the following example JSON string:
[{"id":"4363603591","title":"blue, white and red...another seattle view","date_faved":"1266379499"},{"id":"4004908219","title":"\u201cI just told you my dreams and you made me see that I could walk into the sun and I could still be me and now I can't deny nothing lasts forever.\u201d","date_faved":"1259987670"}]
Javascript has problems with this, however, due to the unescaped single-quote in the second item ("can't deny").
I want to use the function json_encode with the options parameter to make it strip the quotes, but that's only available in PHP 5.3, and I'm running 5.2 (not my server). Is there a fast way to run through the entire array and escape everything before encoding it in Json? I looked for a way to do this, but it all seems to deal with encoding it as the data is generated, something I cannot do as I'm not the one generating the data.
If it helps, I'm currently using the following javascript after the ajax request:
var photos = eval('(' + resptxt + ')');
Have you considered using JSON2 instead of eval()? Details here.
str_replace('\'', '\\'', json_encode($pics))
You'll have to do a (recursive) foreach to walk through the array and manipulate them manually. You can do a str_replace, but addslashes works just as fine (and addcslashes is even better.)