How do I pass 2 PHP variables in a javascript function? - php

How do I pass 2 PHP variables in a javascript function?
This one is working
echo '<button onClick = "count('.$increment.')">'.$counter.' </button>';
but when i do this
echo '<button onClick = "count('.$increment.','.$pass.')">'.$counter.' </button>';
it does not work, what is the problem?
By the way these are the variables:
$increment=5;
$pass="sdfgd";

Try this dude......
<button onClick = "count('<?php echo $increment ?>','<?php echo $pass ?>')"><?php echo $counter ?></button>

echo '<button onClick = "count('.$increment.',\''.$pass.'\')">'.$counter.' </button>';

If $pass contains exactly "sdfgd" and with exactly I mean double quotes includes, this isn't a valid statement anymore, because your parser will find double quotes "too early" and them will close the onClick event attribute
After variable expansion:
echo '<button onClick = "count('5','"sdfgd"')">'.$counter.' </button>';
-------------------------------------^
Take a look to the arrow
Edit
However, if you use a tool like firebug (if you run firefox), you can debug your code easily

The generated HTML code should look like this:
<button onClick = "count(5,sdfgd)">5 </button>
The variable sdfgd is most likely undefined, therefore undefined gets passed to your function.
If you want to pass a string you have to use quotes, so that the generated HTML looks like this:
<button onClick = "count(5,'sdfgd')">5 </button>

Related

ajax jquery passing string as a parameter in onclick event jquery

echo "<button onClick='follow(".$name.");'></button>";
I need to pass a string as a parameter in follow(user) function onClick event jquery. But it's getting called as a value.
I tried kind of everything, but in php it looks a bit of a big deal for me. Is there any other way around to get the expected result as a string from a php variable.
You echo a php variable in javascript without adding quotes thus ending with a javascript variable name instead of a string.
Just add escaped quotes like this:
echo "<button onClick='follow(\"".$name."\");'></button>";
Quotes are off and if you're passing a string you need quotes wrapping the string in the function call.
There is various ways to do it, for standard " in html properties:
echo '<button onClick="follow(\''.$name.'\')"></button>';
echo "<button onClick=\"follow('".$name."')\"></button>";
echo "<button onClick=\"follow('$name')\"></button>";
for single quotes
echo '<button onClick=\'follow("'.$name.'")\'></button>';
echo "<button onClick='follow(\"".$name."\")'></button>";
echo "<button onClick='follow(\"$name\")'></button>";
But that's presuming your users are nice, a crafty user may create a username with \n in it, then from POSTing to storing and retrieving it would most likely be rendered as a new line:
<?php
$name = "Foo\nBar";
echo '<button onClick="follow(\''.$name.'\')"></button>';
Rendering the following which would cause the page to break:
<button onClick="follow('Foo
Bar')"></button>
Or worse a username like:
$name = "Foo')\"></button>\n<button onClick=\"window.location.href = ('http://example.com";
Which would render a stored XSS:
<button onClick="follow('Foo')"></button>
<button onClick="window.location.href = ('http://example.com')"></button>
So a better solution then to directly pass it in, would be to escape it, using htmlentities and json_encode so \n is not rendered by the html.
echo '<button onClick=\'follow('.json_encode(htmlentities($name, ENT_QUOTES, 'UTF-8')).')\'></button>';
Which would render to:
<button onClick='follow("Foo')"><\/button>\n<button onClick="window.location.href = ('http:\/\/example.com")'></button>
Though you should be validating usernames on create before allowing such an attack.

Using a hyperlink to submit a form instead of a button through an intermedite function is not working

I want to submit a form through an 'edit(param1,param2)' function which in turn is being called in either of the two ways..
echo '<input type="button" value="DELETE" onclick="edit(\''.$key.'\',\''.$b.'\')"/>';
or
echo '<a href="list_cadmin.php" onclick="edit(\''.$key.'\',\''.$b.'\')"><span class="bluetext">DEACTIVATE</span>';
the function edit() is something like this:
function edit(a,b) {
var answer = confirm("Do You Really want to Deactivate ?")
if (answer){
alert(a)
document.getElementById('cid').value= a;
document.getElementById('key').value= b;
document.getElementById('fname').method='get';
document.getElementById('fname').action='samepage.php';
document.getElementById('fname').submit();
}
}
where $key and $b are number and string values respectively.
so, according to the above both should go to 'samepage.php?cid=BLAHBLAH&key=1234' on onClick. But only the input=button is working. Hyperlink is reloading without the GET parameters. How do i get the hyperlink to work?
You need to prevent the href from executing by returning false from the onclick:
echo '<a href="list_cadmin.php" onclick="edit(\''.$key.'\',\''.$b.'\'); return false;"><span class="bluetext">DEACTIVATE</span>';
Try to use
echo '<span class="bluetext">DEACTIVATE</span>';
<?php
echo <<<EOD
<a href="javascript:void(0);" onclick="edit('{$key}','{$b}')">
<span class="bluetext">DEACTIVATE</span></a>
EOD;

Echo Javascript Variable in Php to another page

I have code which passes php variable to another page on my site:
echo'<a class="btn btn-danger" style="margin-left:10px;width:120px;float:left;" href="fullsizemarket.php?imageid=',$imageid,'&action=removed">Remove from Cart</a>';
I am able to retrieve the php variable $imageid by the following:
$imageid = htmlentities($_GET['imageid']);
I want to also pass in this code the value of a javascript variable. The variable is set in an earlier part of the code as follows:
var rowcount
I don't know how to pass var rowcount in the same echo code as I pass $imageid. What is the code to do this?
How bout following:
echo
"<a class='btn btn-danger'
style='margin-left:10px;width:120px;float:left;'
href='fullsizemarket.php?imageid=$imageid&action=removed&rowcount='
onclick = \" this.setAttribute('href', this.getAttribute('href')+rowcount) \"
>Remove from Cart</a>";

Parameters in Javascript using jquery

I'm trying to pass a parameter from php into my javascript function inside html. Is this at all possible? This is what I've got so far, but it seems to crash once it hits the condition:
$str="<input type='submit' value='-' onclick='Call(".$row['field1'].");'/>";
I hope that I won't have to find a work around for this.
Thanks.
EDIT:
This is the function that I'm trying to call
function Call(stuff)
{
alert(stuff);
$.get('reports.php',
{'param':'section', 'text':stuff},
function(returned_data)
{
alert(returned_data);
});
//alert('end');
}
And this is the function that I'm populating a table with.
function PopTable()
{
alert('end');
document.getElementById('table').innerHTML = 'Loading...';
$.get('reports.php',
{'param':'getstuff'},
function(returned_data)
{
document.getElementById('table').innerHTML = returned_data; // Clear the select
});
alert('end');
}
This is the php that I'm sending back population the table:
$str.= '<tr>';
$str.='<td bgcolor="#ffffff">' . $row['stuff'] .'</td>';
$str.='<td><input type='submit' value='-' onclick="Call('$row['stuff']');"/></td>';
$str.='</tr>'; //accumulate table
I can't seem to get a return value for Call(), and the alert doesn't even pop up
Try:
$str='<input type="submit" value="-" onclick="Call(\''.$row['field1'].'\');"/>';
I would bet you need quotes around the value if it is a string value
For example if $row['field1'] = 'test'; then:
Your version: <input type='submit' value='-' onclick='Call(test);'/> which would fail because test is not a valid variable
My Version <input type="submit" value="-" onclick="Call('test');"/> which would work becase 'test' is a string
What you're trying to do is possible, whereas it is not possible to pass a parameter from JavaScript into a PHP function.
When you say it crashes once it hits the condition, do you mean when you click on the input on the page? In that case, it's an error in your JavaScript syntax. I would try using Firebug with Firefox to track down the issue.
My first guess is there are no quotation marks inside the Call() method. So you're doing this:
Call(something)
and it should be like this:
Call('something')
This is possible, but I would be very careful about mixing PHP echos and javascript inline with strings because you need to escape javascript datatypes properly
In your example, $row['field1'] is probably from a database, so it's a string, so you need to surround the value with quotes in your javascript call. But that's not all, because what if there's a quote in your string, or a special character like a newline which needs to be escaped in javascript? And then what about html escaping?
A better approach is to import your javascript values in one place using json_encode(), then use your variables from there.
E.g.:
<?php
$jsonrow = json_encode($row);
?>
<script type="text/javascript">
var jsrow = <?=htmlspecialchars($jsonrow);?>;
</script>
<?php // some time later... ?>
<input type="submit" value="-" onclick="Call(jsrow.field1);" />

php javascript confirm box for delete

The below code is in PHP
echo "<input type='submit' name='delete' value='$t2[0]' class='delete_button' onclick='return confirm('Please Confirm Delete');'>"
I am trying to create a delete button, when a user clicks on delete button , it should ask confirmation. but in this case, its not working.
is there any best way to delete with confirmation in php with/ or javascript
and no ajax
Your quotes are breaking themselves here;
onclick='return confirm('Please Confirm Delete');'>
Instead use;
onclick="return confirm('Please Confirm Delete');">
Well, in javascript you can do it as:
<input type='submit' name='delete' value='$t2[0]' class='delete_button' onclick='return askme();'>
//javascript function
function askme() {
if(confirm("Are you sure you want to delete this..?")) {
//delete someting
}
}
The quotes are going wrong, use this instead:
echo "<input type='submit' name='delete' value='$t2[0]' class='delete_button' onclick='return confirm(\"Please Confirm Delete\");'>"
You are going out of your attribute by opening the single quote again inside your confirm.
You cannot "call php code into jquery". The only thing you can do is to set up a request (AJAX) to a server side PHP script which will take over the respective parameters you transferred to the script and produce an output (using echo or print) which will automatically be available in the request's callback.
With jQuery it's as easy as that
$.post('url/to/script.php', {parameter1: 'whatever', param2: 'something'}, function(response) {
// the output of the PHP script is available in the variable "response"
alert(response);
});
The PHP script can take over the parameters, take any action with it and create output
$param1 = $_POST["parameter1"];
$param2 = $_POST["param2"];
// do whatever you want with $param1 and $param2
// create some output using echo/print
echo "This will be transferred back to the calling Javascript";
You can try this, quite easy and it works.
<td> <a onClick="return confirm('DELETE: Are You sure ??');" href="member_delete?id=<?php echo $row['memID'];?>" >delete <i class="fa fa-trash-o" aria-hidden="true"></i></a></td> [DEMO][1]
I assume, its in a table list of members.

Categories