Getting a php variable into javascript - javascript

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..

Related

Cannot echo strings with "" , '' and /n from PHP to JavaScript

I tried to show a description from the YouTube API to p element but it's not working. I think the problem is with the quotes, single quote and new line; ie. "" , '' and \n.
This is the description text:
Another contestant attempts to overcome 'Head Case'! Will Daniel be able to "master" his fear of the unknown and be able to carry on singing?\n\nSubscribe for more awesome clips!\n\nSubscribe now!
$description = $vid["items"][0]["snippet"]["description"];
echo "<script>$('.pClass:nth-of-type(4)').text($description);</script>";
Note that it's working like this: $('.pClass:nth-of-type(4)').text('test');, but it's not working when read from the API.
You're outputting data to JavaScript, so you need to escape it in a way that will be safe for JavaScript to consume. Since JSON is a subset of JavaScript, you can use json_encode() for this purpose.
You should also avoid outputting JS in a double-quoted string; you can have problems with JS values being interpreted as PHP variables.
<?php
$description = json_encode($vid["items"][0]["snippet"]["description"]);
?>
<script>
$('.pClass:nth-of-type(4)').text(<?=$description?>);
</script>

How to set ckeditor html data in a javascript variable

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);?>

Why am I getting an error message about "unexpected non-whitespace after JSON data"

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.

Escape an already encoded json string

at the moment i have to work with some json strings where the quotes are not correctly escaped. The strings looks like this
{ "foo" : "hello my name is "michael"" }
Is there any realistic chance in JS/PHP to escape the quotes in the value without doing it manually so i can parse the string?
You haven't provided us much to work with, but it looks like you're generating the json something like this way:
$userInput = $_GET['userInput'];
$json = '{ "foo" : "' . $userInput . '" }';
This is pretty bad. Here's the appropriate way to generate the json safely:
$outputData = array(
"foo" => $_GET['userInput']
);
$json = json_encode($outputData);
See the reference here: http://php.net/manual/en/function.json-encode.php
As to your original question, Is there any realistic chance in JS/PHP to escape the quotes? No. Suppose the "actual value" of the string is a series of paragraphs containing quote marks, you know, like a continuation of a quotation, where each paragraph starts with a ". No, that is not able to be fixed.
You need to fix the source of your json. If you are getting that json string from some third-party service, you need to tell them that the strings they are sending you is not valid json.

PHP or JavaScript issue when parsing JSON encoded PHP array into JavaScripts JSON.parse()

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.

Categories

Resources