JavaScript alert boxes combined with PHP - 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

Related

Set the value of a button to equal the answer of an SQL query

My code has a text input and submit button which on return hides that form and displays a new button, which works. The problem I'm having is setting the value of the button (or innerHTML) to the answer in my query (which will always only be one). I have the following code:
echo '<form><button id="HCP_Btn" name="HCP_Btn" style="display:none"></button></form>';
$HCP_num = $_POST['HCP_num'];
$HCP_Query="SELECT * FROM HomeCareProviders WHERE Number='". $HCP_num."'";
$HCP_result= mysql_query($HCP_Query) or die(mysql_error());
if (mysql_num_rows($HCP_result)==0){
echo 'Sorry there are no Home Care Providers with the number entered.';
}
//HCP_Btn.innerHTML='.$row["name"].';
else {
$row = mysql_fetch_array($HCP_result);
echo '<script type="text/javascript">
HCP_Btn.style.display="";
document.form.HCP_Btn.innerHTML='.$row["name"].';
</script>';
}
You can use this Javascript code
echo '<script type="text/javascript">
document.getElementById("HCP_Btn").style.display="";
document.getElementById("HCP_Btn").innerHTML="'.$row["name"].'";
</script>';
For first change it like this
echo '<script type="text/javascript">
//HCP_Btn.style.display="";
document.form.HCP_btn.innerHTML=\''.$row["name"].'\';
</script>';
for second check if $row["name"] gives you the right value and at last check you javascript console for errors.
Also HCP_Btn.style.display=""; mean nothing like this.
The problem is probably because Your button's id is HCP_Btn but in the JS further You are accessing it like HCP_btn - the problem could be small b. Also You are missing quotes for the innerHTML value.
Change the line
document.form.HCP_btn.innerHTML='.$row["name"].';
to
document.form.HCP_Btn.innerHTML="'.$row["name"].'";
^ ^ ^
make the b uppercase add quotes ----------^
EDIT: Have You ever tried jQuery? It is commonly and widely used JavaScript framework that makes JS programming so much easier (after You know it)... With jQuery, You could just do:
echo '<script type="text/javascript">
$("#HCP_Btn").css({"display":""}).html("'.$row['name'].'");
</script>';
How is the information from your JavaScript call returned to the innerHTML itself? When does it get called and changed? I think you should do that first.
You have an user pressing a button. Then you go to the database using PHP (need a new request response for that), with AJAX or JavaScript you could make it work client side.
I think that you are mixing up server side and client side issues. You should at least need a function call on the onClick event to toggle the display of the button and show the information. That onClick event should call a JavaScript function and that will handle the change.

call javascript function with arguments within php echo statement

I'm trying to call a javascript function within php that will pop up a confirmation button. If the user presses yes, then it will proceed onto the page, otherwise it'll stay on the same page. I wrote it, but I have no idea what's wrong.
php:
echo "Delete<br/><br/>";
javascript (i placed it right before the tag):
<script type="text/javascript">
function deleteMembers(url, id) {
var deleteMemberConfirmation = confirm("Are you sure you want to delete?");
if(deleteMemberConfirmation) {
window.location="http://mvcsf.com/admin/"+url+"?"+id;
}
else {
window.location="http://mvcsf.com/admin/view_members.php";
}
}
</script>
I enabled ERROR_REPORTING(E_ALL); at the top of the page, but it's not returning anything. What did I do wrong?
Edit: I changed the variable names to deleteMemberConfirmation, but still nothing works. I just click the link, but nothing happens.
delete is a reserved keyword in javascript, and not a valid variable name!
And you got the quotes wrong:
"<a href=\"javascript:deleteMembers('del_member.php', '$studentid');\">";
You're using ' as a designator in your HTML AND in your JS. You will have to use it in one place and " in others.
A working version would be something like:
echo "Edit or Delete<br/><br/>";
For your echo, be careful when using single quote ' and double quote ". A single quote will be closed when it meets another single quote unless it is escaped like this \'. The same goes for double quote.
I'm not 100% sure if you can use javascript inside href, but another solution is to use onclick when calling javascript function, and just use javascript:void(0) or # for href attribute.
echo "Delete<br/><br/>";
As for the delete, change the delete word to something else (I.e: del), because delete is a reserved word for javascript.
<script type="text/javascript">
function deleteMembers(url, id) {
var del = confirm("Are you sure you want to delete?");
if(del) {
window.location="http://mvcsf.com/admin/"+url+"?"+id;
}
else {
window.location="http://mvcsf.com/admin/view_members.php";
}
}
</script>

jQuery - click() not working when attached to anchor created in PHP

I have this PHP code which outputs HTML anchor elements on a page:
if(!$isOnOwnPage)
echo '<a id="message-button" class="button">Message</a>';
if($isOnOwnPage)
echo '<a id="add-img-button" class="button">Add Image';
else if(!$isFollowing)
echo '<a id="follow-button" class="button">Follow';
else
echo '<a id="follow-button" class="button">Unfollow';
echo "</a>";
When I load the web page, I get this, as expected:
...
<a id="message-button" class="button">Message</a><a id="follow-button" class="button">Unfollow</a>
...
But when I try to attach a click() function to it, the clicking doesn't work. This is the jQuery code. (It's weird because all of my other JS on the page works flawlessly."
$('.button').click(function() { alert("HEY"); }); // It doesn't work grabbing by #follow-button or #message-button either.
What did I do wrong here? I've spent an hour looking at these snippets of code to no avail.
Try this:
$('.button').live('click',function() { alert("HEY"); });
Put it in your $(document).ready function.
Gonna go out on a limb and guess that you've forgotten to wait for document.ready and that the a.button element doesn't exist when the click event is bound.
Is ajax included somehow? Because then you need to either use the live, or re-apply the function.
It should work regardless if it's PHP generated. In the end it's still HTML that gets output to the client.
I think you should make sure that the JS code gets to the part where you assign clicks to the buttons. Maybe there's not document ready or a correct one. Maybe there's a boolean IF that doesn't get passed.
All in all, if you can see the code in the View Source page, then it's a HTML/JS problem, not a PHP one.
This is an old question, but to all there who want to add listeners to dynamic content, instead of using $('a').(click(function(){}) or $('a').on('click',function(){}), you need to use instead the document as the object you want to attach the listeners, because the tag you are inserting wasn't in the DOM when the listener was assigned.
So instead you should use:
$(document).on('click','a',function(){ ... });

including php in html code within 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; ?>

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 .

Categories