When I load a php page, i put within a javascript function, a name. The problem comes when this string has special chars like '.
Here I paste the code of a click event:
showSocialShare(event, '<?php echo $object->slug; ?>', '<?php echo htmlspecialchars($object->title); ?>', '<?php echo $object->image; ?>')
I thought that the function htmlspecialchars code somehow the string but the result is:
showSocialShare(event, '4049269', 'collection-'Noun'', '/img/Original.jpg')
As can be seen, at the second parameter, the name contains characters like ' and arises an error.
How can I avoid this?
Never output text from PHP directly into a Javascript context. As you're finding out, it's VERY easy to generate JS syntax errors.
Always use json_encode: e.g. given this
<?php $foo = 'bar'; ?>
<script>
var badly_broken = <?php echo $foo ?>;
var working_fine = <?php echo json_encode($foo); ?>;
</script>
You'll end up with
<script>
var badly_broken = bar; // oops - undefined variable "bar"
var working_fine = "bar";
</script>
And note that if you're outputting JS into an HTML attribute, you not only have to generate valid Javascript, you have to output valid HTML AS WELL:
<?php $foo = array('bar' => 'baz'); ?>
<a onclick="brokenCall(<?echo json_encode($foo) ?>)">
<a onclick="workinCall(<? echo htmlspecialchars(json_encode($foo)) ?>)">
produces:
<a onclick="brokenCall({"bar":"baz"})">
^--start attribute
^--end attribute - ruhroh
<a onclick="workingCall({"bar":"baz"}")>
Related
My script removes the http:// and www from urls displayed in a post's content but for some reason it either affects all the posts but the last one or just the first post of the page depending on where I place the script.
For instance if it's in the loop it will affect all the posts but the last but if it's outside the loop it only affects the first post.
I'm looking for a solution so that it takes affect on all urls being displayed on a page. Any help would be much appreciated.
<?php
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<Script>
$(document).ready(function removeFunction() {
let post_id = '<?php global $post; echo $post->ID; ?>';
var str = document.getElementById("link" + post_id).innerHTML;
var res = str.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
document.getElementById("link" + post_id).innerHTML = res;
});
</Script>
<p><?php the_content(); ?></p>
<!-- This is where the URL's are EX: <a id="link[return_post_id]" href="http://example.com/">http://example.com/</a> -->
<?php endwhile;
else :
echo '<p>No content found</p>';
endif;
?>
1.You tagged jQuery there so put jQuery code outside of loop.
2.It has to iterate over all <p> and do what you are doing.
3.Change <p><?php the_content(); ?></p> to <p data-id="<?php global $post; echo $post->ID; ?>"><?php the_content(); ?></p> (inside while loop)
4.After above steps followed, change jQuery code like below:
<Script>
$(document).ready(function() {
$('p').each(function(){
let post_id = $(this).data('id');
var str = $(this).html();
var res = str.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
$(this).html(res);
});
});
</Script>
there is a problem and this is on mixture of php and javascript.
Your php code Generate JS Within a Loop, in each loop it will create a function named removeFunction() and your browser interpreter mixed up things. it will replace the last one.
There Are 2 Solution for Your problem:
First is to make These Functions Distinct like This:
$(document).ready(function removeFunction<?php echo $post->ID; ?>() {
this will make function names as removeFunction1() removeFunction2() ...
The Second Sulotion is to Define The function outside The loop and in the php loop just call the function like this:
while (have_posts()) : the_post(); ?>
<script>
removeFunction(<?php global $post; echo $post->ID; ?>);
and your function definition would be like this:
removeFunction(post_id){
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']); ?>";
This is really weird..
I need to send a couple of variables through to jquery from PHP.. one is an INT and the other a string.
When $a is an INT it works fine but when i use a string, i get this error.. Uncaught ReferenceError: testString is not defined
Here is my code.
<?php $a = 'testString'; ?>
<script type="text/javascript">
var a = <?php echo $a; ?>;
alert(a);
</script>
I assumed that i needed to stick a (int) or (string) before the variable, but i wasn't entirely sure how to and unsuccessful in my googles/attempts.
Any ideas?
You forgot the quotes to make the value of var a a string:
var a = "<?php echo $a; ?>";
What you're writing into the document is:
var a = testString;
so javascript is looking for a variable called testString. Instead, you want the result to be:
var a = "testString";
so make sure you include the quotes around what php is writing in.
There are quotes missing in javascript code:
<script type="text/javascript">
var a = '<?php echo $a; ?>';
alert(a);
</script>
I had an onclick event as below.
<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')"></div>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
the function works fine with the name like Mary, Chris and etc.
However, if the student name contains a ', e.g. Cheng'li, the function won't work.
I need help to fix this. How can I make the function works by 'escaping' the quote mark in name?
Thanks.
You need to add a call to htmlentities around the data you wish to echo.
Not doing so exposes your code to XSS attacks.
use PHP function addslashes
<?php
$str = "Is your name O'reilly?";
// Outputs: Is your name O\'reilly?
echo addslashes($str);
?>
IN your case
<?php echo addslashes($student_name);?>
REFERENCE
http://www.php.net/addslashes
Note: If your code contain html tag than use htmlentities (Entoarox Answer)
you can either use escape()
<div onclick="display_function(escape('<?php echo $user_id;?>'),escape('<?php echo $student_id;?>'),escape('<?php echo $student_name;?>'))"></div>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
That is because you are passing the values in function in single quotes. When name will have a single quote, this will cause error.
try double quotes like
<div onclick="display_function(\"<?php echo $user_id;?>\",\"<?php echo $student_id;?>\",\"<?php echo $student_name;?>\")"></div>
Just add \ before ' to tell your script that it is a string. I hope it helps
<?php
$user_id = 1;
$student_id = 1;
$student_name = "Cheng\'li";
?>
<div onclick="display_function('<?php echo $user_id;?>','<?php echo $student_id;?>','<?php echo $student_name;?>')">Click</div>
<script>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+student_name); //<-- testing only. I have my own code here
}
</script>
If you cannot put \ directly in String, you need to use [addslashes][1]
<script>
function display_function(user_id,student_id,student_name)
{
alert(user_id+'-'+student_id+'-'+addslashes(student_name)); //<-- testing only. I have my own code here
}
</script>
If I have created a variable in php, say $test, how can I set a variable in javascript, say var test, to be equal to it.
I have already tried var test = <?php $test ?>
I guess
var test = <?php echo json_encode($test) ?>
The naive way var test = '<?php echo ($test) ?>' will fail if $test contains quotes or newlines, let alone is not of the string type (e.g. array, object)
var test = '<?php echo $test; ?>'
try like this :
var test = '<?php echo $test ?>';
var test = '<?php echo $test; ?>';
Or using shorthand echos, like this:
var test = '<?= test;?>';
var test = <?php echo json_encode($test); ?>
You can use
<pre>
var test = '<?php echo $test?>';
</pre>
below the definition of $test.
Change
var test = <?php $test ?>
to
var test = <?php echo $test; ?>
You are missing two things:
var test = <?php $test ?>
1) Echo statement.
2) Single Quotes around PHP snipplet.
So, the corrected code should be:
var test = "<?php echo $test ?>";
Within your page where you want your PHP to output to type:
var MyJavascriptVariable = <?php echo $myPHPVariable; ?>
Advise NOT to use short tags () as this can be disabled by webhosts and may break your code.