Passing a PHP variable to a java-script function - php

im trying to pass a value to a java-script function. but when i click the link i get a
Uncaught SyntaxError: Unexpected identifier
here is the code
<?php
include_once("php_includes/check_login_status.php");
$routeHTML = '';
$sql = "SELECT user,title FROM route";
$query = mysqli_query($db_conx, $sql);
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$title = $row["title"];
$user = $row["user"];
$routeHTML .= '<p>Planned By '.$user.'</p>'.$title.'<br />';
}
?>
i echo the $routeHTML in a div tag

you forgot to add quotes for the javascript:
$routeHTML .= '<p>Planned By '.$user.'</p>'.$title.'<br />';

You'll have to surround your string with a '' quotes like this...
$routeHTML .= '<p>Planned By '.$user.'</p>'.$title.'<br />';

The Parameter to your JS function is undefined (since the parsed HTML is missing quotes - JS assumes title is an undefined variable).

You forgot to escape the quotes, do like this:
fetchdata(\''.$title.'\')
Otherwise php will not render the ' properly and you get an error.

You can pass a php variable to a javascript function in this way:
<input type="button" value="Send" onClick="js_function('<?php echo $var; ?>')">

It's generally not recommended to make inline Js (as an attribute of the tag).
So, i encourage you to separate javascript from html code, like this :
Html:
$routeHtml = '<p>Planned By '.$user.'</p>'.$title.'<br />';
Js (with jQuery, but also work for vanillaJs):
$(document).ready(function(){
$(".MyLink").click(function(e){
fetchData($(this).data("title"))
});
});
Note the data-title attribute, the data-* attributes are intended to store custom data, so it's a great way to exchange informations between php and Javascript inside templates.
More info about data-* attributes : http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/all-you-need-to-know-about-the-html5-data-attribute/

Related

php javascript json parse escape characters

I currently have a webpage that need to use javascript to parse variables from php.
I do things like this:
data.notices = JSON.parse('<?php echo json_encode($notices) ?>');
However, when there is single or double quotes in the $notices variable, javascript console return errors.
How can I get the variables correctly?
This code doesn`t return error
<?
$notices = array('sad'=>'asd as" asd', 'asd"sdf '=>'asdasd" \' asd ads');
?>
<script>
data = new Object();
data.notices = JSON.parse('<?php echo addslashes(json_encode($notices)) ?>');
</script>
$a='b' will be converted to "b"(note the quotation mark) by json_encode
just write JSON.parse(<?php echo json_encode($notices) ?>);(remove ') will be ok.
I found that it is the problem caused by the fact that I did not escape the characters before inserting to database.
You are one extra operation. If you want message as javascript variable you can directly get like
data.notices = <?php echo json_encode($notices) ?>;
// and access like this
// data.notices[0] or data.notices['alert']

using javascript quotes in php code

i'm having some trouble using javasript in php code, I'm confused in using double quotes and single quotes.
echo 'Delete';
or how to do the above code in php ?.
Thanks
use this code
echo 'Delete';
you have to escape the quotes.
http://viper-7.com/F6uI0L
You need to escape the quotes with htmlspecialchars (for HTML):
echo '<a href="..." onclick="return confirm('
.htmlspecialchars('"Are you sure"') . '">Delete</a>';
(alternatively you could just write ")
...but don't do that. Use JS event registration:
document.getElementById('a-id').addEventListener('click', function (e) {
if (!confirm("Are you sure...")) {
e.preventDefault();
}
});
Do that in JS file. It requires that the <a> have an ID (you could also do it with a host of other selectors, but ID is the simplest).
Change like following
echo "Delete";
Why don't you put the HTML outside of PHP tags? For example you could do:
...
?>
Delete
<?php
...
Another way to echo HTML is:
echo <<<HTML
Delete
HTML
Error in confirm("Are you sure you want to delete?")"> you need to escape double quote.
You need to call the javascript function using php echo
echo 'href_link';
...but you have to use JS function
<html><head><script type="text/javascript">
function fun()
{
if(confirm('are you sure')) return TRUE;
else return FALSE;
}
</script>
</head>
<body></body>
</html>

Pass PHP array to Javascript via onClick using JSON

I am using PHP and MySQL to loop through products and generating HTML code that consists of an img tag with an onClick event that calls a Javascript function. I want to pass PHP variables via the onClick event to a Javascript function. I'm using jQuery and thought it would be a good idea to use PHP's json_encode() function and jQuery's jquery-json plugin.
My PHP code looks like this:
$onclick = json_encode(array(
'productid' => $productsRow['ProductID'],
'description' => $productsRow['Description']
));
echo "<a href=\"javascript:;\" onClick=\"changepic('" . htmlentities($onclick) . "')\">";
echo "<img src=\"products/$thumbnailfilename\" width=\"100\" height=\"100\">";
echo "</a>";
As you can see my Javascript function is called changepic(). I've left out a bit of code that is irrelevant to this question (i.e. the database access code and deciding where the thumbnail image is).
My Javascript code is:
function changepic(productarray) {
var productid = $.evalJSON(productarray).productid;
var productdesc = $.evalJSON(productarray).description;
alert(productid);
}
I'm not really doing anything yet with the PHP variables that I'm passing to the Javascript array, I'm just trying to get it to work first! My ultimate aim is to use jQuery to insert the product description into a <div>
A sample product detail might look like this:
ProductID: 30c7508008ac7597619ad9b90a97b40f
Description: <p>Wide and Narrow Bands<br>
Set with Top-Quality Diamonds</p><p>
As you can see the description contains HTML code, as well as a newline after the <br> tag.
The HTML that is generated looks like this:
<img src="products/tn-30c7508008ac7597619ad9b90a97b40f.jpg" width="100" height="100">
When I run this I get a Javascript error:
Event thread: click
Uncaught exception: SyntaxError: JSON.parse: Unescaped control char in string: "<p>Wid
Error thrown at line 18, column 2 in changepic(productarray) in http://isis/carats/view-collection.php?collectionid=32d0c7b8774f7f82a2d7c7d053286cfc:
var productid = $.evalJSON(productarray).productid;
called from line 1, column 0 in <anonymous function>(event) in http://isis/carats/view-collection.php?collectionid=32d0c7b8774f7f82a2d7c7d053286cfc:
changepic('{"productid":"30c7508008ac7597619ad9b90a97b40f","description":"<p>Wide and Narrow Bands<br>\r\nSet with Top-Quality Diamonds<\/p>"}')
From what I can see I've done something wrong with encoding the JSON string. I've done some Googling and found some people that say no encoding is necessary (I tried that and the product description was taken as HTML and showed up in the page), others say to use addslashes() and some say htmlentities().
Do I need to do something in the Javascript function to decode it before I try to use it with evalJSON()?
I usually just do this,
var foo = <?php echo json_encode($foo); ?>;
and I don't really see how this can result in any sort of an "injection" attack as long as json_encode is doing its job.
I don't understand why you are getting into so much mess.. here is the solution and it works
$onclick = json_encode(array(
'productid' => $productsRow['ProductID'],
'description' => $productsRow['Description']
));
echo "<a id='test' href='' var='$onclick'>";
echo "<img src=\"products/$thumbnailfilename\" width=\"100\" height=\"100\">";
echo "</a>";
Here is your jquery:
$(function(){
$("#test").click(function(){
var img = jQuery.parseJSON(($(this).attr("var")));
alert(img.description);
});
});
Now since you have the json object you can create div tag and put the variables inside or put the content on already existing div tag. I am sure you know what to do here.
Dins
I think I was over-complicating things, I didn't really need to use JSON at all.
I got this working by changing my PHP code to this:
$productid = $productsRow['ProductID']
$description = rawurlencode($productsRow['Description']);
echo "<a href=\"javascript:;\" onClick=\"changepic('$productid','$description')\">";
Then my Javascript looks like this:
function changepic(productid, description) {
description = decodeURIComponent(description);
alert(description);
}
This works fine so now I can continue and actually do something useful in the Javascript function.

Passing variable through function Javascript / PHP

i want to pass a variable through to a php on an onClick event, it doesn't seem to be passing it through to the page properly though.
Here's my html
<a href="data.php" onClick="video(We Have a Pope)" hidefocus="">
and the relevant javascript function
function video(result) {
$('#information').load('data.php?result=' + result);
document
}
My php page looks like this
<?php
$result = $_GET['result'];
echo $result;
?>
Nothing is being outputted though :S
onClick="video(We Have a Pope)" should be onClick="video('We Have a Pope')"
You need quotation marks when you pass string as parameter, like this:
<a href="data.php" onClick="video('We Have a Pope')" hidefocus="">
<a href="data.php" onClick="javascript:video('We Have a Pope');" hidefocus="">
onClick="video('We Have a Pope');"
or
onClick="video(\"We Have a Pope\");"

Jquery to parse HTML in a string

I tried searching the related posts, and having a hard time figuring out how to fix my query - I'm pretty close, any help is much appreciated (new to Jquery).
I program in PHP, and trying to pull either the HREF value from a tag, or the text. Either will work.
I basically have my HTML code in a string, might contain multiple tags, and would like to load the text of the tags into either a PHP array or variable (right now just trying to ALERT the results, I can dump it later).
My PHP Code:
<?php
$info = '<li><strong>I want this text</strong>';
echo '<script type="text/javascript">';
echo '$("document").ready( function () {';
echo 'alert($("a", $("' . $info . '")).html());';
echo '});';
echo '</script>';
?>
The above doesn't alert anything. Putting in
echo 'alert("yes")';
does work, so I'm guessing there's something basic wrong with my syntax, but 4 hours later still unable to find it! :)
Thanks in advance.
You aren't Javascript-escaping the quotes in your string.
Your code creates Javascript that looks like
$("<li>...<a href="http..."...")
The quotes in the attribute end the Javascript string, creating a syntax error.
You need to call json_encode.
SLaks has the rest of your problem. But also, it's not:
$("document").ready();
It's:
$(document).ready();
The former is a selector for a tag named <document>.
This should work the way you want it to:
<?php
$info = '<li><strong>I want this text</strong></li>';
?>
<script type="text/javascript">
$(document).ready( function () {
alert($("a", $("<?php echo $info; ?>")).html());
});
</script>
You are not closing your li Tag
$info = '<li><strong>I want this text</strong>';
should be
$info = '<li><strong>I want this text</strong></li>';
You should escape info. It's breaking because you've got double quotes inside of double quotes:
$info = addslashes($info);
or
$info = json_encode($info);
or just
$info = str_replace('"', '\\"');
Try to save the HTML is a JS variable first, then use it. Also, heredocs are your friend.
<?php
$info = '<li><strong>I want this text</strong></li>';
echo <<<END
<script type="text/javascript">
$(function(){
var HTML = '$info';
alert($('a', $(HTML)).html());
});
</script>
END;
?>
echo '<script type="text/javascript">
$(document).ready( function () {
var info = \''.$info.'\';
$("a").html(info);
alert(info);
});
</script>';

Categories