including php in html code within php - php

<?php
if(isset($left))
{
echo "<button name = rightname onclick= \" disp();\">". "$left"."</button>";
}
?>
here disp is a php function. but i am not able to use it. can anybody say me how to overcome this problem...

The only way to run a PHP function in response to a user clicking on something in their browser, is to send an HTTP request to the server.
The simplest way to achieve this would be:
<?php echo htmlspecialchars($left); ?>
You then need to write disp.php such that it includes the function you want to run, and calls it. Then you need to return an appropriate response to the browser (e.g. a page to display or a redirect (via Location) header.
You could also look at using XMLHttpRequest (probably via a third party library such as YUI or jQuery) to make the HTTP request using JavaScript without the user leaving the page (Ajax). Given the amount of knowledge you appear to have based on your question, you might need an introduction to JavaScript first.

Simply try like this
<?php
if(isset($left))
{
?>
<button name ="rightname" onclick= "<?php disp();?>"><?php echo $left;?></button>
<?php
}
?>

onclick only works for javascript functions not PHP functions, that won't work.
See BoltClock's comment under your question.
One of the ways to run php in combination with javascript is using an ajax post (http://api.jquery.com/jQuery.post/). Eg:
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
And when concatenating variables with string you don't need to put the variable between double quotes, or just put the variable in the string without closing the double quotes.
echo "<button name='rightname' >". $left."</button>";
Or (will only work when using double quotes)
echo "<button name='rightname' >$left</button>";

if you don't use Aston's answer, you can correct your code as follow:
<?php
if(isset($left))
{
echo '<button name ="rightname" onclick= "' . disp() . '">'. $left .'</button>';
}
?>
I wanted to point that you can use single quotes to make it easier to handle double-quotes inside.

Before bothering with AJAX, would you mind me asking what the disp() function does? If it's something that doesn't heavily rely on server interaction (file operations, db connections), we may be able to help you port it to JS and remove the need for AJAX.

I would write this:
<?php if(isset($left)) : ?>
<button name="rightname" onclick="<?php disp(); ?>"><?php echo $left ?></button>
<?php endif; ?>

Related

What is the proper way to execute JS?

Is it possible to use JS/JQuery from an external file? If so, what is the best practice?
What is the best practice to call a JQuery function inside a PHP or HTML page?
Here is file.php
echo "<table..";
echo "some code...";
echo "</table>":
<script type="javascript">
$('table').hide().fadeIn(700);
</script>
or:
echo '<script type="javascript">';
echo '$('#foo').toggle("slow");';
echo '</script>';
So, besides a best practice. is any of this possible? I can't seem to make it work from external file or directly.
also from external.js
$(document).ready(function(){ $('table').css({ // code here ... }); });
You can certainly echo jquery (or any html code) directly from PHP
echo '<script type="javascript">
$(\'#foo\').toggle("slow");
</script>';
Your issue in that one was the un-escaped quotes around #foo
I'm not really sure what you meant in the first part of your question, but since you have php I would use this option rather than trying to add jquery into an html file from another javascript file (if that's what you were trying to do)
Both internal and external javascript/jquery code should work.
Make sure you jquery script tag was include in you header/body
If external, make sure to include the external.js script tag after the jquery script tag
Make sure the document was ready first ( $(document).ready() ), and check again the selector either they are exist or not.
For more clean code, no need to echo every single line html code. Just close the php ( ?> ) and write the html as usual.
Please provide as much information as you can so that we know exactly what's the problem was.

how to pass a php values to javascript?

here is the code??
posting code:
$.post('get.php',{selected:"aaaa"},function(return){alert(return);});
when i check the values of "selected" value using
<?php
$r=$_POST['selected'];
echo $r;
?>
is displays the value "aaaa" correctly..
this code works fine...
<?php
$r=$_POST['selected'];
?>
var answer="<?php echo "welcome" ?>";
when we echo the value"welcome" it is stored in the variable answer.and i could print that...
but when i put like this....
<?php
$r=$_POST['selected'];
?>
var answer="<?php echo $r ?>";
an empty value is stored in answer... and nothing gets displayed....
whether specifying $r inside " " is not right... how to specify that......
Assuming that the php code you are showing, is located in get.php, there is no use of using javascript in that same file. If you want to get the returned value in a javascript variable in your page, you need to use the first php snippet and use the return value in your .post function:
javascript in original page:
$.post('get.php',{selected:"aaaa"},function(data){
var answer = data;
});
get.php
<?php
$r=$_POST['selected'];
echo $r;
?>
$_POST['selected'] is probably empty to start with. Make sure you're sending a nonempty value for selected, and that you're using POST. (The easiest way is to look in your browser's developer tools for the initial request).
Note that directly outputting user input into the page introduces a Cross-Site Scripting Vulnerability: The input "; alert("evil"); can show that. Assuming you're using UTF-8 all around, you can write:
var answer = <?php echo json_encode($_POST['selected']); ?>
Also, there are often better ways to transfer data from php to JavaScript, including XHR requests/JSON or data-* attributes.

Embed javascript in PHP echo

echo "<td> + manuf + </td>";
Is this above ever going to work??
I'm pulling results from a mysql db to edit the contents but need the jQuery functionality to edit it, hence the embedded javascript variable...
EDIT:
Sorry for the lack of context, its related to another question i've asked on here Mysql edit users orders they have placed
this is the end goal. To edit the order i place, i need to pull the results into an environment similar to how the user placed the order. So my thinking was to include the jQuery functionality to add items to a cart etc, then they could press submit and in the same way i used .Ajax to post the data to an insert php script i would post the values to an update php script! Is this backwards thinking, any advice welcomed!
I suggest you take a look at the follwing.
json_encode
Ajax
JSONP
Now your simplest solution under you circumstances is to do go for the json_encode method. Let me show you an example:
$json_data = array(
'manuf' => $some_munaf_data
);
echo "<script type=\"text/javascript\">";
echo "var Data = " . json_encode(json_data);
echo "</script>";
This will produce an object called Data, and would look like so:
<script type="text/javascript">
var Data = {
munaf : "You value of $some_munaf_data"
}
</script>
Then when you need the data just use Data.munaf and it will hold the value from the PHP Side.
Try just emitting the MySQL content with PHP:
echo "<td id='manuf'>".$manuf."</td>"
Then get the contents with jQuery like this:
var manuf = $('#manuf').text();
Would you not echo out the jQuery within a Javascript code island? You need the client-based code (jQuery) to be able to execute after the server-side code (PHP).
echo '<td><script language = "JavaScript" type = "text/JavaScript">document.write("");</script></td>';
Is this above ever going to work??
Nope. You'd need to output valid JavaScript for the browser to interpret:
echo "<script>document.write('<td>'+manuf+'</td>')</script>";
But that is a dreadful construct, and I can't really see why you would need this, seeing as the td's contents are likely to be static at first.
Consume you have the table echoed with php:
<table id="sometab">
<tr>
<td>
</td>
<tr>
</table>
The jquery for printing resuls in any td is :nth-child(2) takes 2 table td object :
<script type="text/javascript">
$(function(){
$("#sometab tr td:nth-child(2)").html("bla");
})
</script>
Is "manuf" a JS variable or part of a PHP output e.g. part of generated ?
Basically this can easily be done by:
mysql thru PHP(*I can't put table tag..sorry.):
while($row = mysql_fetch_object($result)) {
echo 'tr';
echo 'td a href="#" class="myres"'.$row->manuf.'/a /td';
echo '/tr';
}
then on your JS just attach a "click" handler
$(function() {
$(".myres").click(function() {
//my update handler...
});
});
i think you cant embed the jquery variable in the php like this .
you just give the class name here from here when edit will be click you will get the variable as in submit click in other questions .

PHP, javascript, single quote problems with IE when passing variable from ajax post to javascript function

I have been trying to get this to work for a while, and I suspect there's an easy solution that I just can't find. My head feels like jelly and I would really appreciate any help.
My main page.php makes a .post() to backend.php and fetches a list of cities which it echoes in the form of:
<li onclick="script('$data');">$data</li>
The list is fetched and put onto the page via .html().
My problem occurs when $data has a single quote in it. backend.php passes the variable just fine to page.php but when i run html() it throws a javascript error (in IE, not FF obviously);
')' is expected
IE parses the single quote and messes up the script()-call. I've been trying to rebuild the echoed string in different ways, escaping the 's on the php side and/or on the javascript side - but in vain. Do I have to review the script in total?
page.php
$.post("backend.php", {q: ""+str+""}, function(data) {
if(data.length >0) {
$('#results').html(data);
}
backend.php
while ($row = $q->fetch()) {
$city = $row['City'];
// $city = addslashes($row['City']);
// $city = str_replace("'","'",$row['City']);
echo "<li onclick=\"script('$city');\">".$city."</li>";
}
You need two encodings: One for the JavaScript context and one for the HTML context:
json_encode is for encoding the data for JavaScript and
htmlspecialchars for the HTML part.
So try this:
echo '<li onclick="script(' . htmlspecialchars(json_encode($row['City'])) . ')">' . htmlspecialchars($row['City']) . '</li>';
You could call script() and then reference this.innerhtml.
<li onclick="script();">$data</li>
And then in your javascript:
function script() {
data = this.innerHTML;
// do stuff
}
what about backslash escaping it?:
$city = str_replace("'","\'",$row['City']);
To make your life easier, I would dispense with using onclick if you can and include scripts in the <head> of the page and register click handlers based on id/class. And even better, use jQuery to do that, but you're probably aware of jQuery already if you've been around S.O. enough.
Single/Double/Triple escaping all the time just isn't worth it.
My contribution to proceedings, uses your existing function with minimal change.
<li onclick="script(this.innerHTML);">$data</li>

JavaScript alert boxes combined with PHP

echo "<td><a href='delete.php?id=$row[id]&&category=$a' onclick='return confirm(\'are you sure you wish to delete this record\');'>delete</a></td>";
Above is the code I am trying to use. Every time it does nothing and I cannot see how I can use 'proper' JavaScript methods. What is the reason?
It is also a bad idea to use GET methods to change state - take a look at the guidelines on when to use GET and when to use POST ( http://www.w3.org/2001/tag/doc/whenToUseGet.html#checklist )
I think $row[id] is not evaluating correctly in your echo statement. Try this:
echo "<td><a href='delete.php?id={$row[id]}&&category=$a'...
Note the squiggly brackets.
But THIS is much easier to read:
?><td>delete</td><?
As an aside, add a function to your js for handling the confirmation:
function confirm_delete() {
return confirm('Are you sure you want to delete this record?');
}
Then your onclick method can just be return confirm_delete().
Just a suggestion, are you using a framework?
I use MooTools then simply include this script in the HTML
confirm_delete.js
window.addEvent('domready', function(){
$$('a.confirm_delete').each(function(item, index){
item.addEvent('click', function(){
var confirm_result = confirm('Sure you want to delete');
if(confirm_result){
this.setProperty('href', this.getProperty('href') + '&confirm');
return true;
}else{
return false;
}
});
});
});
All it does is find any "a" tags with class="confirm_delete" and attaches the same code as your script but i find it easier to use. It also adds a confirmation variable to the address so that if JavaScript is turned off you can still send them to a screen with a confirmation prompt.
You should try to separate your JavaScript from your HTML as much as possible. Output the vanilla HTML initially and then add the event to the link afterwards.
printf('<td><a id="deleteLink" href="delete.php?id=%d&category=%s">Delete</a></td>', $row["id"], $a);
And then some JavaScript code somewhere on the page:
document.getElementById('deleteLink').onclick = function() {
return confirm("Are you sure you wish to delete?");
};
From your example however, it looks like you've probably got a table with multiple rows, each with its own delete link. That makes using this style even more attractive, since you won't be outputting the confirm(...) text over and over.
If this is the case, you obviously can't use an id on the link, so it's probably better to use a class. <a class="deleteLink" ...
If you were using a JavaScript library, such as jQuery, this is very easy:
$('.deleteLink').click(function() {
return confirm("...");
});
echo "<td><a href='delete.php?id=$row[id]&&category=$a' onclick='return confirm("are you sure you wish to delete this record");'>delete</a></td>";
Use Firefox's HTML syntax highlighting to your advantage. :-)
Another solution:
echo '<td><a href="delete.php?id=' . $row[id] . '&category=' . $a . '" onclick="return confirm(\'are you sure you wish to delete this record?\');'>delete</a></td>';
I changed the double quotes to single quotes and vise versa. I then concatinated the variables so there is no evaluation needed by PHP.
Also, I'm not sure if the return on the onclick will actually stop the link from being "clicked" when the user clicks no.
And if you insist on using the echo-thing:
echo "<td><a href='delete.php?id=$row[id]&&category=$a' onclick='return confirm(\\'are you sure you wish to delete this record\\');'>delete</a></td>";
-- because the escaping is treated from the php-interpretator !-)
Here is what I use for the same type of thing.
I do not echo/print it, I will put the html between ?> html
?> <td>Upd / Del</td> <?php

Categories