I am trying to pass a variable through the onclick function into javascript.
So I am trying to pass
onclick = "purchase_song(<?php echo $row['filename']; ?> , <?php echo $row['price'] ?> )"
note the function works fine if I pass it a non php variable
onclick = "purchase_song( 'filename' , 1)"
And I use a similar technique to pass variables through hyperlinks and the GET function. Is it not possible to use PHP inside a javascript onlick? If so, what am I doing wrong.
Thanks,
If the values are valid strings then you are doing everything right except one thing : to pass php input as a string argument to the javascript function you should wrap it in single quotes ':
onclick = "purchase_song('<?php echo $row['filename']; ?>' , '<?php echo $row['price'] ?>')"
The values should need to be quoted.
onclick="<?php printf("purchase_song('%s', '%s')", $row['filename'], $row['price'] ?>"
This example uses printf as its easer to see what the output from the format string.
Related
I am trying to use innerHTML of javascript in order to edit html elements but it isn't working as it should. The code:
if($postSQL->num_rows > 0){
$postSQL->bind_result($userID,$userName, $postID, $desc, $image, $date);
$postSQL->fetch();
echo $userName."".$desc."".$date."".$image;
echo "<script>
document.getElementById('userName').innerHTML=$userName;
document.getElementById('description').innerHTML=$desc;
document.getElementById('date').innerHTML=$date;
</script>";
}
I noticed that when I try to change 'userName' using an int type variable, it works. So if I do like this:
document.getElementById('userName').innerHTML=$date;
It works but it won't do the same for string type variables.
The issue here is strings need quotes to work properly. Assume for a moment that $userName equals John. That PHP code is going to display
<script>
document.getElementById('userName').innerHTML=John;
...
</script>
However this is incorrect JavaScript, because all strings should be surrounded by quotes. So to fix your code, just add quotes around the values you want, such as
if($postSQL->num_rows > 0) {
$postSQL->bind_result($userID,$userName, $postID, $desc, $image, $date);
$postSQL->fetch();
echo $userName."".$desc."".$date."".$image;
echo "<script>
document.getElementById('userName').innerHTML='$userName';
document.getElementById('description').innerHTML='$desc';
document.getElementById('date').innerHTML='$date';
</script>";
}
Are you adding a tag around your userName for JavaScript to work with?, i.e.
echo '<div id="userName">' . $userName. '</div>';
You are generating HTML/JS code on server side. Use double quotes around variable:
document.getElementById('userName').innerHTML="$date";
document.getElementById('userName').innerHTML='$userName';
document.getElementById('description').innerHTML='$desc';
document.getElementById('date').innerHTML='$date';
I am passing a php value to javascript using onclick method, so it kind of looks like this
onclick="(method('<?php echo $variable; ?>'))"
But my problem is one of my values are "Ike's" , it contains a single qoute, which breaks the code. Any way in javascript to complete consider a passed parameter as a string,not anything else?
thanks
Your question seems to be more about PHP than Javascript, based on the code snippet you provided. Basically, you might want to escape the apostrophes with a backslash character.
onclick="(method('<?php echo $variable; ?>'))"
would then become something like this perhaps:
onclick="(method('<?php echo addslashes($variable); ?>'))"
... and please remove the parenthesis you have surrounding the onclick event, like so:
onclick="method('<?php echo addslashes($variable); ?>')"
You'll need to escape the string from PHP before passing it to Javascript. For example:
onclick="(method('<?php echo addslashes($variable); >'))"
If I understand well. I would prefer to use:
<div id="the_php_output">
<?php echo $variable; ?>
</div>
<input onclick="js_method()">
<script>
function js_method(){
$("#the_php_output").html();
}
</script>
I am trying to get array value from JSON string, and I do the work with json_decode PHP.
<?php
$jsonContent=file_get_contents('http://megarkarsa.com/gpsjson.php');
$jsonDecoded=json_decode($jsonContent,true);
foreach($jsonEncoded['BMS'] as $p){
echo '
ID: '.$p['id'].'
Tipe: '.$p['type'].'
';
echo "<br>";
?>
The PHP code works, and give the result of array from JSON string.
And this is my Javascript code
<script>
var bmsdata = <?php echo $jsonDecoded ?>;
alert(bmsdata["1"].id); // For check, i want to see the id of row 1
</script>
But nothing was shown up.
Am i doing right so far? Or i missing something to pass the value from PHP to Javascript? Any suggestion will be appreciated.
$jsonDecoded is the decoded json.
Please change
var bmsdata = <?php echo $jsonDecoded ?>;
to
var bmsdata = <?php echo json_encode($jsonDecoded); ?>;
or use the already exisiting variable $jsonContent:
var bmsdata = <?php echo $jsonContent; ?>;
This one should work, as I lookup JSON at http://megarkarsa.com/gpsjson.php ;)
<script>
var bmsdata = <?php echo json_encode($jsonDecoded); ?>;
alert(bmsdata.BMS["1"].id); // For check, i want to see the id of row 1
</script>
You just forgot 'BMS' key ;)
Looks like you're injecting a decoded, PHP-representation of the data into your javascript. You probably (if you want to continue doing it this way) want to echo the encoded version (jsonContent) instead.
Ultimately, you might want to rethink the approach. Fetching the data via ajax is often an easier way to work with it, since you don't need to worry about writing bare javascript via php, which has all sorts of escaping issues to get right.
I want to update innerhtml of div with id NotifyDiv
I want to change it with following html code.
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
I am using following code to change it.
echo "<script>document.getElementById('NotifyDiv').innerHTML='$html'</script>";
But no changes occur.
However it I remove id = 'js-news' from the above ul tag it works.But I'll need the id.
If you check the source code of your browser you will see this:
<script>document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>
So we can see that in the JavaScript string you are using apotrophes, but the string is already encloded with apostrophes, so it attempts to end the string early: (before the letter j in js-news)
'<ul id='js-news'><li>HELLO WORLD!</li></ul>'
This can be solved by using escaped quotation marks for the JS string:
echo "<script>document.getElementById('NotifyDiv').innerHTML=\"$html\"</script>";
Basically, the code you have causes a syntax error in JS:
echo "...innerHTML='$html'</script>";
expands to:
// opening ' closing ' => js-news === syntax error!
// \/ \/
echo "...innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'</script>";
Resulting JS code:
document.getElementById('NotifyDiv').innerHTML='<ul id='js-news'><li>HELLO WORLD!</li></ul>'
The syntax highlighting shows the problem
Note the single quotes around $html and the single quotes inside the $html string. The best way to echo PHP values in JS would be to use json_encode:
echo "...document.getElementById('NotifyDiv').innerHTML=", json_encode($html), "</script>";
The output should be something like:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!<\/li><\/ul>"</script>
Now, those slashes are escaped, and you probably don't want that. Thankfully, there's a second parameter you can pass to json_encode: cf the docs. Passing JSON_UNESCAPED_SLASHES is what you need to do here:
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
echo "<script>document.getElementById('NotifyDiv').innerHTML=".json_encode($html, JSON_UNESCAPED_SLASHES)."</script>";
The output:
<script>document.getElementById('NotifyDiv').innerHTML="<ul id='js-news'><li>HELLO WORLD!</li></ul>"</script>
DEMO
Perfect ans to your query is as under (just copy n paste and check it)
<?php
$html="<ul id='js-news'><li>HELLO WORLD!</li></ul>";
?>
<script type="text/javascript">
document.getElementById('NotifyDiv').innerHTML="<?php echo $html; ?>";
</script>";
You need to pass PHP variable with PHP syntax that is <?php ?>
Even if we can mix PHP, JavaScript and HTML together, we need to initialize proper languages before using their variables in case of JavaScript and PHP.
So, final code should be:
echo "<script>document.getElementById('NotifyDiv').innerHTML = '<?php echo $html;?>'</script>";
Otherwise, everything looks correct.
I have a php array containing email addresses that needs to be passed to a javascript function, but when javascript is trying to handle the addresses, i am getting a syntaxerror: illegal character error relating to the '#' in the email addresses...
How can I get round this? Is there a way of converting the email addresses to strings prior to them being passed to javascript? Or would I need to iterate over the array once it has been passed to js, and create a new array in js and convert them to strings then?
Ok, so the array is created by the user selecting the emails addresses from a list using checkboxes, this is then posted to a second page.
Heres the php code to create the array on the first page:
while ($row = mysqli_fetch_array($students_results)) {
echo'<div class="form-group"><div class="checkbox"><label><input type="checkbox" name="parentsemails[]" value=' . $row['parent_email'] . '">' . $row['parent_name'] . ' (Student: '. $row['student_name'] . ')</label></div></div>';
}
This is then posted to a seond page to be passed to the js function. The php to assign the array to a php variable is:
if (isset($_POST["parentsemails"])) {
$pe = $_POST['parentsemails'];
}
The the JS code inside the function:
email_a = new array(<?php echo implode(',', $pe); ?>);
The email addresses appear to be passed to JS correctly, in the error log I can see the individual emails, but with the illegal character highlighted...
Any help appreciated.
Thanks.
You are not enclosing the e-mails in quotes, which causes the syntax error you are getting.
You can add the quotes manually, but you can use the json_encode function instead.
The json_encode encodes a PHP object or array in JSON. As a JSON array is a valid JavaScript array, this will work well in your case.
Just change the JS line to:
email_a = <?php echo json_encode($pe); ?>;
As others have said, it looks like you need to surround the strings in quotes before putting them in the Javascript. Something like this.
<?php
$_a = array();
foreach($pe as $str)
$_a[] = "'${str}'";
?>
email_a = new array(<?php echo implode(',', $_a); ?>);