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);
Related
I have a php variable which I am changing into JS array
orderform.blade:
<?php
foreach ($entries as $entry){
$name[] = $entry->name;
$quantity[] = $entry->quantity;
}
?>
<script type="text/javascript">
var entries = JSON.parse('<?php echo json_encode($entries) ?>');
// console.log(entries);
</script>
Then in my JS file I am using the variable
var output = entries.reduce(function (orderA, orderB){...
This works on local host perfectly. But when I put on digital ocean cloud server I get:
Uncaught SyntaxError: missing ) after argument list
Uncaught ReferenceError: entries is not defined at javascript.js:12
The missing ) error is highlighting this:
var entries = JSON.parse('[{"id":2,"name":"Britannia","mint":"The Royal Mint","quantity":"3","weight":"31.15","price":"19.00","description":"Royal Mint flagship silver bullion. CGT free.","created_at":"2018-05-01 03:08:38","updated_at":"2018-05-01 03:27:23"},{"id":3,"name":"Maple Leaf","mint":"The Royal Canadian Mint","quantity":"12","weight":"31.15","price":"17.50","description":"Canada's flagship bullion coin. Prone to milk spots.","created_at":"2018-05-01 10:41:57","updated_at":"2018-05-01 10:41:57"}]');
What can cause this to work in one environment and not on another? How do I address this? I can not see any syntax error here?
The syntax error is due to your string literal using apostrophe delimiter \' inside itself. You need to escape your JSON. Where is this JSON string generated?
What's formally happening:
'Canada's more characters... ')
StringLiteral 'Canada' + [ lookahead ~= { ) } ]
So, you obviously shouldn't just pass your raw JSON to JavaScript source. Escape quotes and apostrophes from your PHP server.
(I think preg_replace won't replace all occurrences of the quotes, but in JS I know json.replace(/'"\''/g, s =>\${s}) would.)
preg_replace('("|\')', '\\$0', $json)
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);?>
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));
Can anybody tell me what the problem is with this:
I am echoing out a PHP array into javascript as follows:
<?php
$myArray=array();
foreach ($persons as $person) {
array_push($myArray,$person['id']);
}
?>
$(document).ready(function() {
populatePersons(JSON.parse(<?php echo json_encode($myArray);?>));
});
So basically I am echo'ing out a PHP array in json format, and then parsing it in javascript but I am getting this error in my console log:
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
Can anybody tell me what I am doing wrong?
Can anybody tell me what I am doing wrong?
While json_encode produces JSON, you are echoing it into JavaScript. As such it will be interpreted as a JavaScript array literal, not a string containing JSON. Hence you cannot use JSON.parse.
Just get rid of it:
populatePersons(<?php echo json_encode($myArray);?>);
If you looked at the generated code, you would something like:
populatePersons(JSON.parse([1,2,3]));
But JSON.parse expects a string (containing JSON). Because JavaScript performs type conversion, it will convert the array to a string first, which likely does not result in valid JSON.
Again: You already have an array, there is no need to parse anything.
Its because youre feeding JSON.parse an array. Just get rid of the JSON.prase in your javascript and replace it with JSON.stringify if youre trying to display the json. If not, then json_encode($myArray) should be enough for operations.
<div id = 'test'></div>
<script>
var test = document.getElementById('test');
test.innerHTML = JSON.stringify(<?php echo json_encode($myArray)?>);
</script>
Try putting the json_encode string in quotes.
populatePersons(JSON.parse('<?php echo json_encode($myArray);?>'));
As the parameter expected is string.
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..