I am having a problem with ckeditor data. I have some ckeditor html data saved in my data base as a description. So when i need to update that description i need to set the data from the database and show it in the textarea in order to show user what was it. I'm using laravel 5.3.
In order to do this i have tried this
var old_description = '<?php echo $Product->description;?>';
$('#detail').val(old_description);
But this is giving the following error
Uncaught SyntaxError: Invalid or unexpected token
What is the problem and what should i do?
You should just use json_encode() from http://www.php.net/manual/en/function.json-encode.php
var old_description = '<?php echo json_encode($Product->description); ?>';
It takes care of converting < / >, escaping any other special characters as necessary, preserve spaces, etc.
The description you are passing contains multiple lines witch produces a javascript error. Try encoding the variable when echoing.
<?php echo json_encode($Product->description);?>
Related
I need to pass a parameter from PHP to JavaScript, so I do this:
var title='<?php echo ($home->title); ?>';
console.log(title);
but I obtain
Uncaught SyntaxError: Invalid or unexpected token
Can anyone help me?
This is the output:
var titolo_it='<p><strong>ddddddddddd</strong></p>
';
The line break in $home->title is breaking the JavaScript syntax. You cannot include a literal line break in a JavaScript string that way.
To fix this, you need to be sure the data is properly encoded, so any apostrophes, line breaks, etc. are in proper format for JavaScript. Use the built-in function json_encode(), like this:
var title=<?php echo json_encode($home->title); ?>;
console.log(title);
I encoded an array using json_encode() function and it gave me a string like this..
"[{"details":"power - 2000w \nac-220-240v \/ 50-60hz\n369 degree cordless base\n","model_id":"MC-EK3428 \/ MC-EK3328"}]"
as you can see it contains special characters like "\n"..I want these special characters to be replaced with "" because in javascript I am using the JSON.parse(); function to convert this string to an object..
but it gives me an error
syntaxerror : missing ) after argument list
I think this is because of the special characters in the string..how can I escape these?
Edit
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = JSON.parse('<?php echo $jsonencoded_array; ?>');//this line gives me the error
update :
found out that the error is given in this :
'<?php echo $jsonencoded_array; ?>'
The problem here is that \n (and various other combinations) have special meaning inside a JavaScript string, and you are dumping your JSON into a JavaScript string without doing any conversion of those characters.
Since JSON is heavily inspired by JavaScript literal syntax, you can use json_encode to convert a PHP string into a JavaScript string.
There are some gotchas, the main one being that </script> can appear in a JSON text without causing any problems, but having that in the middle of your JavaScript <script> element is going to cause the HTML parser to cut off your JavaScript in the middle of the string … but PHP's default encoding rules will generate <\/script> which solves that problem.
So:
<?php
$json_array = json_encode($array);
$javascript_string = $json_encode($json_array);
?>
var products = JSON.parse(<?php echo $javascript_string; ?>);
That said. A JSON array is also a JavaScript array, so you can skip that step entirely.
<?php
$json_array = json_encode($array);
?>
var products = <?php echo $json_array; ?>;
There must something that you are missing or there is some other reason for your issue while parsing in JavaScript; because json_encode handles \n and other special characters such " \ etc. very well and escape them properly without any explicit work.
I would suggest you to check the JSON produced and you are supplying to JavaScript and see if there is something missing in between.
Note: You can do a str_replace but it is not advised. Better stick to json_encodesince its s standard function and it works well.
Edit:
You should be echoing $view->jsonencoded_array not just $jsonencoded_array, no need to parse already JSON object.
php :
$view->jsonencoded_array = json_encode($array);
javascript :
var products = <?php echo $view->jsonencoded_array; ?>;
json_encode() twice helped me to solve this issue..
$view->jsonencoded = json_encode(json_encode($array));
Following situation:
I have a txt file which contains some text. I read it with PHP via "file_get_contents".
Now i want to submit multiple forms with some ajax request.
To do this i need to get the variable into JS.
var results = "<?php echo htmlspecialchars($results); ?>";
doesnt work. It returns "Unexpected token ILLEGAL"
The string itself contains only characters, and maybe a few specials.
An example of the content is something like this:
Email: MyName#mail.net - Pass: ^s2p3r(s3cr3t& - City: aCity
Email: OtherName#mail.net - Pass: ^s2p3r(s3cr3t& - City: anotherCity
So why JS cant read that?
Thanks
EDIT:
in the html output it totally got correctly displayed.
even with all special charaqcters like ^ , ( or &
(i edited the above string to what exactly would allready give me that error)
Is $results a JSON string?
If so, you want to parse it using
htmlspecialchars(json_encode(json_decode($results,true)))
so that the information can then be first decoded into an array, then encoded as Javascript-ready JSON.
The only problem I see with that is that you seem to not be using valid JSON in that it is not in the proper quotes so depending on the version of PHP you are using, it may or may not be able to parse the data. The ideal situation would be for your data to look like
['Email' : 'MyName&mail.net', 'Pass' : 's2p3rs3cr3t', 'City' : 'aCity']
This will save you the headache of trying to use a regex to parse the information into a readable format, since there are time the regex could incorrectly replace/parse information that you may need. Still I believe that decoding and encoding the data using JSON should work.
Maybe it's the Unicode U+200B Zero-width space character ? That character is known to cause the Unexpected token ILLEGAL JavaScript syntax error.
If your intent is to send that string to another request why dont your json encode your content?
or try this
str_replace("\xe2\x80\x8b", '', $str);
Following like is something you looking for?
<?php
$var='MyName#mail.net - Pass: s2p3rs3cr3t - City: aCity';
?>
<script type="text/javascript">
var mymail = '<?php echo json_encode($var); ?>';
alert(mymail);
</script>
if not, could you please tell the exact output you want..
I'm currently making a web app for my workplace, that downloads around 40,000 rows of data from an SQL table in one go, places the data into nested PHP arrays, and then attempts to echo the JSON encoded array, where a JavaScript variable should capture the contents.
If I attempt to echo the data straight into the tags, it works fine - everything is displayed perfectly - formatted as a JSON encoded string. If, however, I attempt to echo the data into <script> tags, between speech marks '' or "", it throws an error in chrome, saying 'Uncaught SyntaxError: Unexpected identifier' - and when I attempt to scroll to the end of the (very long) string, it appears to have been chopped off, only a few thousand characters in.
The string is actually 1,476,075 characters long.
How do I get around this? I'm remaking the application - it originally basically combined javascript with the SQL results whilst iterating through the results rows, but this was so slow and clunky, so I figured an easier and quicker way to move the data from PHP to JavaScript, would be with a large JSON encoded string.
Any advice would be greatly appreciated.
Dan.
json_encode() takes care of ALL the quoting/escaping that needs to be done:
<?php
$foo = 'this is a simple string';
?>
<script>
var foo = "<?php echo json_encode($foo); ?>"; // incorrect
var bar = <?php echo json_encode($foo); ?>; // correct
The above construct would create:
var foo = ""this is a simple string"";
^--- your quote
^---the quote json_encode added
var bar = "this is a simple string"; // all-ok here.
What would be the easiest way to append form data to a json url prior to sending the request? I know next to nothing about php but Im trying either way
The PHP I have so far, I need to replace the ZIP before.json with the content im getting from $_GET['zip']
<?php
$zip = $_GET['zip'];
$zip_data = file_get_contents($zip);
$weather_data = file_get_contents("http://api.wunderground.com/api/myapi/conditions/q/ZIP.json");
echo $weather_data;
?>
In PHP if you just put the variable name inside a string that is quoted with double quotes, it puts the value into the string:
$weather_data = file_get_contents(".../q/$zip.json");
You can also put curly brackets around it to make it cleaner to read:
$weather_data = file_get_contents(".../q/{$zip}.json");
Or you can close the string, use the dot operator to concatenate, and reopen the string:
$weather_data = file_get_contents(".../q/" . $zip . ".json");
Replace
"http://api.wunderground.com/api/myapi/conditions/q/ZIP.json"
With
sprintf("http://api.wunderground.com/api/myapi/conditions/q/%s.json", $_GET['zip'])
(or whatever variable you want to take it's place)
More on string formatting with sprintf