How to escape text coming from PHP in JavaScript? - javascript

I am using jPlayer to display some videos and I create the playlist on the fly in a php foreach statement:
var playlistacting =
[
<?php foreach($this->result as $val){?>
{
title: '<?php echo $val->getTitle();?>',
artist: '<?php echo $val->getDes();?>',
poster: "<?php echo $val->getVideoId();?>.jpg",
thumb: "<?php echo $val->getVideoId();?>.jpg",
flv: "<?php echo $val->getVideoId();?>.flv",
},
<?php }?>
];
and $val->getDes() example would be I have a one-hour (approximately) solo musical revue called "Manhattan With A Twist". The entire...
the error I get is
unterminated string literal
[Break On This Error]
artist: 'I have a one-hour (approximately)solo musical revue called "Manhattan W...
jquery.js (line 2, col 32)
and is poining to the ' at the beginning of the string.
I can do this: title: "<?php echo htmlspecialchars($val->getTitle());?>",
and I will get the same error but with " instead of '.
I'm not sure what is happening here. Is it complaining about that ' not being escaped or what?
Any ideas?

simply use json_encode:
var playlistacting = <?php echo json_encode($this->result);?>;

Related

stripe form not showing when billing name has an apostrophe

I have the following stripe payment form on my page:
stripe.createToken(card,{name: '<?php echo $order->customer['firstname'] . ' ' . $order->customer['lastname']; ?>', address_line1 : '<?php echo $order->customer['street_address']; ?>', address_city : '<?php echo $order->customer['city']; ?>', address_state : '<?php echo $order->customer['state']; ?>', address_country : '<?php echo $order->customer['country']['title']; ?>' }).then(function(result) {
if (result.error) {
// Inform the user if there was an error
var errorElement = document.getElementById('card-errors');
errorElement.textContent = result.error.message;
} else {
// Send the token to your server
stripeTokenHandler(form, result.token);
}
});
});
I recenetly found out that a customer with the last name o'brian was not being shown the portion of the form that allows them to enter the credit card info. It took a while to find out why they were having that issue.
In any case, should I just be removing the apostrophe with a str_replace? That seems a bit strange to have to remove the apostrophe? Or is there something else I should be doing?
The apostrophe matches the single quote that starts the JavaScript string, and ends the string, causing unmatched quotes in the JavaScript.
Use json_encode() to safely translate a PHP value into the equivalent JavaScript literal, rather than echoing the raw value inside quotes.
stripe.createToken(card,{
name: <?php echo json_encode($order->customer['firstname'] . ' ' . $order->customer['lastname']); ?>,
address_line1 : <?php echo json_encode($order->customer['street_address']); ?>,
address_city : <?php echo json_encode($order->customer['city']); ?>,
address_state : <?php echo json_encode($order->customer['state']); ?>,
address_country : <?php echo json_encode($order->customer['country']['title']); ?>
}).then(function(result) {
Isn't it enough to use double quotes instead of apostrophes to enclose strings?
Something like:
stripe.createToken(card,{name: "<?php echo $order->customer["firstname"] . ' ' . $order->customer["lastname"]; ?>"

using php _GET within javascript function

I have some javascript embedded into an html file that I am running in a browswer.
document.getElementById('home-search-text-inp').value = <?php echo htmlspecialchars($_GET['search_for']); ?>;
Why does this not fill the textbox?
Note that:
document.getElementById('home-search-text-inp').value = "hi";
puts "hi" into the textbox and:
<?php echo htmlspecialchars($_GET['search_for']); ?>
writes text just fine.
Thanks in advance
You're missing quotes around your string value:
document.getElementById('home-search-text-inp').value = <?php echo htmlspecialchars($_GET['search_for']); ?>;
^^^^ ^^^^
HERE HERE
should be:
document.getElementById('home-search-text-inp').value = "<?php echo htmlspecialchars($_GET['search_for']); ?>";

Transform a PHP array to a Javascript array

Basically I used these codes to transform:
echo "<script>";
echo " var img_array=new Array();";
foreach($img_arr as $img_url){
$url=(string)$img_url;
echo "img_array.push('".$url."');";
}
echo "console.log(img_array);";
echo "</script>";
However, errors occur(firefox debug window) :
Error: unterminated string literal
Source File: http://127.0.0.1/CubeCart/index.php?_a=account
Line: 1, Column: 42
Source Code:
var img_array=new Array();img_array.push('http://gtms01.alicdn.com/tps/i1/T1mL3LFhhhXXaCwpjX.png
but after I checked the souce file of the html page, the script is shown like this:
<script> var img_array=new Array();img_array.push('http://gtms01.alicdn.com/tps/i1/T1mL3LFhhhXXaCwpjX.png
');img_array.push('http://gtms01.alicdn.com/tps/i1/T1DQtTFsdFXXaCwpjX.png');console.log(img_array);</script>
With which I don't see anything is wrong.
$jsArray = json_encode ($phpArray);
There is a newline in one of the items in your your php array. Use this:
echo "<script>";
echo " var img_array=new Array();";
foreach($img_arr as $img_url){
$url=(string)$img_url;
echo "img_array.push('". htmlentities(trim($url))."');";
}
echo "console.log(img_array);";
echo "</script>";

What is this Javascript Syntax Error

I have this code which sends a variable to JS from a PHP file.
<script type="text/javascript">
var pids = new Array(<?php echo implode(', ', $pids); ?>);
var permalink = "My name is <?php the_permalink(); ?>";
</script>
For reasons beyond my comprehension, when take away "My name is", it's a syntax error.
<script type="text/javascript">
var pids = new Array(<?php echo implode(', ', $pids); ?>);
var permalink = "<?php the_permalink(); ?>";
</script>
There is no output, the script dies on.
[Syntax Error]
= new Array(67, 68, 69, 70, 71,
The first code was working, now has spontaneously stopped, despite no changes. Now, neither works.
I discovered the problem is the preceding code:
When the less-than sign is changed to less-than-or-equal to, there is a javascript syntax error. Somehow this must break the array or the implode function
$pids = array();
$i=0;
$result = count($wpdb->last_result);
while($i < $result) {
$pids[] = $wpdb->last_result[$i]->pid;
$i++;
}
?>
<script type="text/javascript">
var pids = new Array(<?php echo implode(', ', $pids); ?>);
var permalink = "My name is <?php the_permalink(); ?>";
</script>
try it:
var permalink = "My name is '<?php the_permalink(); ?>'";
Try this :
var permalink = "My name is " + <?php the_permalink(); ?>;
you probably have ' or " inside one of the php output functions, try to escape them.
this could happened also if one of your pids is a wrong type and implode fails to finish.

Why this Javascrript Error Is coming at line 2 character 1

I have The Following Javascript Error
"Line 2 Character 1" coming in the entire app
I have researched Follwing thing in SOF i have found this link .
Javascript Line 1 Syntax error in IE
So my JS script is something like this
<script type ="text/javascript">
$(document).ready(function(){
var sv = "<?php echo $var1 ;>";
var sv1 = "<?php echo $var2 ;>";
var sv2 = "<?php echo $var3 ;>";
var sv3 = "<?php echo $var4 ;>";
var sv4 = "<?php echo $var5 ;>";
});
</script>
But when i put the same code under JSLINT it is saying "Problem at line 1 character 2: Expected 'html' and instead saw 'script'."
.How can I make by script corrected .Can any one please explain what iam doing wrong
You need to declare html tags first, and THEN you can start typing your script.
Wrap it in tags.
You're also having some weird PHP tags there, they need to be finished with ?>, not ;>
You aren't properly closing your PHP tags
<script type ="text/javascript">
$(document).ready(function(){
var sv = "<?php echo $var1 ?>";
var sv1 = "<?php echo $var2 ?>";
var sv2 = "<?php echo $var3 ?>";
var sv3 = "<?php echo $var4 ?>";
var sv4 = "<?php echo $var5 ?>";
});
</script>
Are you sending the PHP directly to the browser? If not, we'll need to see the code as it appears to the browser. If there was a double quote being printed, for example, it would cause syntax errors.
Also, there shouldn't be whitespace between your type attribute and the = character.

Categories