call javascript function with arguments within php echo statement - php

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>

Related

PHP: Confirm Box before deleting

I want to add a button on my website, where a User can delete his Account. Unfortunately I don't know how to realize it...
my Code so far:
Javascript:
<script language = "JavaScript" >
function delete(id) {
if (confirm("Do your really want to delete your account?"))
{
header("refresh:1;url=intern.php?act=account");
}
else
{
}
}
</script>
my .html file:(there are no tags like html title head... it begins with ?php..)
<td></form><input type='submit' name='deleteuser' value='Delete Account' onClick='return delete()'/></form></td>
Also i have an if clause in the .html file:
if(isset($_POST['deleteuser'])) {
if(delete() == true){
delete_user;
}
else{
header("refresh:1;url=intern.php?act=account");
}
}
The Button is there and when I click on it, it asks me if I'm sure to delete my account, but afterwards I got an error: "Fatal Error:Call to undefined function delete() "
I have a stored procedure named: sp_deleteAccount. In my config.php I declared it as:
$SQL_delete_user = "CALL sp_deleteAccount('";
Now I don't know how to bind that stored procedure in the code so that the Account will be deleted after pressing "Yes I want to delete my Account".
Hope I didn't miss anything and someone can help me
JOP
In this portion you're calling a php redirect(i think?) in javascript without php open tag so that's not going to work. Instead you can use a javascript reditrect if the 'if' statement returns true(yes) then redirect to a url with a get variable of delete or something, see below.
edit -- you'll probably want the id as well so i made adjustments. PLus in the onclick in the form you'll need to pass the id, unless it's stored in a session variable or something, in which case you don't need to pass it into the url. your sql should end with "WHERE id=" then just tack the id onto the query. This is just a simple example to get you started, always be cautious of sql injection, but i'll leave preventing it up to you.
<script language = "JavaScript" >
function deleteUser(id) {
if (confirm("Do your really want to delete your account?"))
{
window.location.href= 'intern.php?delete=true&id='+id;
}
else
{
window.location.href = 'intern.php?act=account';
}
}
</script>
next in intern.php check for the get variable
if(isset($_GET['delete'])) {
$mysqli = new mysqli(connection variables here);
$mysqli->query($SQL_delete_user.(int)$_GET['id']);
}
give that a try, rearrange the code as you like but that should get it done.
as for the error, you can't use the keyword delete for a function name. One last thing, for this to work make the input type "button"
I am not sure there might be a way to achieve it using the approach you are trying , but I am not aware of it. For this I would typically use an ajax call to an url, on the click event of the OK button in the jquery-ui Dialog. And then process the logic and on success create another dialog for confirmation.
I searched and struggled with this issue until I did a little lateral thinking.
I used JavaScript to show a hidden div containing the Yes/No options.
Then an onClick around the Yes option which loaded the php script into a hidden iFrame.
The onClick around the No option simply hid the div and did nothing else.
A bonus is being able to style the div any way I wanted, show and hide it with an effect and place it exactly where it looked best.

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.

How to retrieve value from form_dropdown() in Codeigniter

I am using codeigniter.I have simple form_dropdown(). I want to execute an onchange() function for my drop down.
I will get the string which was selected through JavaScript.
This is my code but its not working
$js ="onChange=message()";
echo "<script type=\"text/javascript\" > function message(){ var no=document.getElementById('name').value;
alert(sr);
}
</script>";
echo form_dropdown('name',$data,'large',$js);
form_dropdown doesn't automatically add an id to the element, so getElementById won't work as written.
also, for understanding's sake, the guide doesn't do a good job of explaining the fourth parameter. Calling it $js is misleading, as it well add anything you give it to the attributes list.
Change the one line of code to this (note the quotes around the onChange function as well):
$js = 'id = "name" onChange="message();"';
make sure you're viewing your source code after it's output to verify it is outputting valid html as well.
Also, on Chrome, F12 will bring up your developer tools, and hitting the esc key will toggle showing your JavaScript console, which will hopefully give you meaningful errors if everything doesn't go as planned.
Edit:
It also looks like you're setting the value of a variable called no, but alerting a variable called sr, which doesn't seem to be defined.
you can also simply pass ref from function call that would easy instead of getting value from document.getElementById(), it will work when you will add id in select dropdowm
try this code
<?php
echo "<script type=\"text/javascript\" >
function message(element){
var no=element.value;
alert(no);
}
</script>";
echo form_dropdown('name',$data,'large', 'onChange="message(this);"');
?>

popup window not work in php echo

it can appear a simple question but i have searched untill writing here but no answer. i have a php code and i what to start a pop up window after echo :
echo "<A HREF='map2.php' onClick='return popup(this,'notes')'>WHATEVER</A>";
in the head section i have :
<SCRIPT TYPE="text/javascript">
<!--
function popup(mylink, windowname)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
window.open(href, windowname, 'width=400,height=235,scrollbars=yes');
return false;
}
at the end is the ending script tag but i dont succide in adding it.
anyway.the pop up doesn work. the link opens in the same page.
i also tried :
About
and it doesnt work. it opens in the same page. The funny thing is that all these 2 solutions worked in html page, but when used between php , after "echo" , it doesnt work anymore.
In the first line you posted (the php echo), it seems to me you have a problem with ' in side '
Try the following:
echo "WHATEVER";
The issue here your quoting.
When outputting HTML I recommend using single quotes with echo as it allows you to use the proper double quotes for the HTML tags.
echo 'Whatever';
The problem with your original code was that you had quotes within quotes that were breaking the syntax. Read the link I posted to see how to handle quotes properly with PHP.

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