So here's my situation: I have a form that validates with PHP. I want to make it so that if the form fails validation, the user is forced to click through a confirmation dialog before they navigate to another page (the form is fairly large and they don't want to accidentally leave it before it's saved). I'm going about this like so:
see updated function below,
Basically use php within the function to either set the body to present the confirmation or do nothing depending on the error status of my form. Nothing happens when the form isn't submitted and I click a link, good. When the form is displaying errors and I click a link the confirmation dialog will appear but canceling it causes it to reappear. If I cancel it a second time the page request will go through even though it's not supposed to. I'm not that familiar with javascript so I'm not sure what's going on. Is there a better way I should be going about this?
Edit: I figured it out, it was a combination of things. The first was a really dumb mistake on my part: I was calling the onlick on both tags AND the tags for each link in my list, hence why the box popped up twice.
the second piece was that even though my function already returns bool, the onclick requires an explicit return declaration. I was doing:
<a onclick="forceConfirm();" href="somepage.html">Blah</a>
When it should have been:
<a onclick="return forceConfirm();" href="somepage.html">Blah</a>
Then just edit the PHP so that forceConfirm always returns true when the form hasn't been submitted, bypassing the confirmation:
function forceConfirm(){
<?php
if($form->errorStatus){
echo 'if(confirm("Are you sure you want to navigate away from this page? All unsaved changes will be lost.")){'."\n".
'return true;'."\n".'}'."\n".
'else{ return false;}';
}
else{ echo 'return true;';}
?>
}
Now I just need to figure out how to use jQuery to apply this to all links without having to put onclick events all over the place....
You can use confirm() like this:
if(confirm("Are you sure you want to proceed?")){
document.location = 'confirmed redirect url...';
}
else{
document.location = 'cancel redirect url...';
}
Then you'd wrap that in the same PHP block as in your example, displaying it if necessary and hiding it if not.
Related
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.
So basically my question is very simple, I have two buttons, I for page forward, one for page backwards, If one of those is pushed, a javascript function is called inside an onClick Event. Javascript then gets the variables of the page and then redirects to the next page, the only problem is, that I need to pass those variables to PHP in order to put them into the Database. So for that I make a load of cookies to pass the variables.
However, I was wondering if something like this would work :
<form>
<a onClick="nexpage();" onSubmit="phpScript.php"> <img src = "previous button.jpg"/> </a>
</form>
The idea behind this is that I want to store the variables in a PHP script, which will put them in a display:none; <div> and then for javascript to get the variables out. This instead of using cookies.
So is it possible to run a PHP script to get the variables and when the script is finished to get them, Javascript kicks in to redirect to the next page...
The reason I don't test this at this moment, is that my code is 100% complete, I don't want any sudden changes that maybe won't work at all. Yes I know back-up this and that, but I thought just asking here, maybe someone will know the answer!
Sincerly,
Harmen Brinkman
You can also use onClick = "this.form.submit(); return false;".
There is no any event like onSubmit for link, instead form do have onSubmit event.
Normal Way as OP asked.
<form action = "phpScript.php" method = "POST">
you can use document.getElementById("my_form").submit();
#Dipesh Parmar – Good point. You could also do:
window.onload=function() {
document.getElementById('my-form').onsubmit=function() {
// do what you want with the form
// AJAX POST CALL TO PHP PAGE
// Should be triggered on form submit
alert('hi');
// You must return false to prevent the default form behavior
return false;
}
});
Inspiration by Capture a form submit in JavaScript
I have a page that contains an HTML form that submits back to itself once the user clicks a link in a list of returned search results. Once they click the link, the page takes the submitted variables, runs a bunch of searches on various external APIs, parses a bunch of data, and adds a bunch of stuff to the database, then redirects to a new page that has been created from that data.
All the searching and parsing can take up to six or seven seconds; I'd like to be able to show the user a "Please Wait" kind of message while all that work is happening behind the scenes.
Trouble is, I can't show and hide a DIV because it will screw up my PHP redirect if I've already generated output before the
header('Location: ' . $newURL);
command. I've searched around for answers but while there are many that are similar, none of them are close enough to my specific situation that I can hack around them.
I'd be grateful if someone could point me in the right direction.
Updated version which now works, courtesy #Izkata from his comments below:
jQuery("a").bind('click', function() {
jQuery('#feedback')[0].innerHTML = 'Searching, please wait...';
})
Turned out what I needed to do was assign bind a the message to the click of a link, not to 'submit', as submit was looking for form data.
The simplest way I can think of doesn't require the server to do anything:
<div id='wait_message' style='display: none;'>
Please wait while search is in progress...
</div>
...
$$('.links').observe('click', function(e) {
$('wait_message').show();
});
(Event is written using Prototype.js; you should use whatever is appropriate (JQuery/mootools/etc))
Using the example page in the comments, this works - it runs in Firebug, so just putting it on your page somewhere should work just fine.:
jQuery('#newMovieSearchForm').bind('submit', function() {
jQuery('#feedback')[0].innerHTML = 'Searching, please wait...';
})
There's probably a jQuery-way to update the text instead of using innerHTML, but I don't know it - we don't use jQuery here.
You are right, you won't be able to output data to the screen and then try to redirect afterwards using PHP. You could accomplish this by echoing JS:
echo 'Please wait...';
// Time-intensive PHP here
echo '<script>window.location = "new-location.php";</script>';
You can do something like this:
First, take care of output buffering, i.e. you want php to display output as it executes - you don't want it to buffer.
That way, you can output some html that will show a "loading.." sort of thing.
And, will wait for the script to end it's execution.
Once, you are done with php, redirect using a meta tag, something like:
echo '<meta http-equiv="refresh" content="5;URL=\'http://example.com/\'">';
I've got a bit of a dilemma with some PHP code. The site I'm working on has a "Back to Previous Page" option and I'd like it to behave much like a browser's back button. As it stands right now, I'm using a $_SESSION variable to track what the current and previous pages are. I've also "refresh-proofed" the variables so that I don't end up with both the previous and current pages being the same.
So here's the issue:
With the current implementation, if I go to one page, say "register.php" and then go to "forgot.php", the previous page will be "register.php" which is fine. However, if I click "Back to Previous Page" I'll end up back at "register.php" with the previous page being "forgot.php" which now leaves me with a 2-page loop with going back.
I tried implementing SplQueue to help me keep track of variables and I tried using the dequeue() function in my links to get the last page to show up as the link. The problem comes in when the dequeue is actually called and causes the element to disappear so that if I refresh, the element is no longer in the queue and the link changes. I fixed this by "refresh-proofing" the function that calls the dequeue for me and it works as I would like it to. The problem is now forward-linking. If I direct myself to another page, I don't want the old links to dequeue information.
Ex:
I'm on register.php and my previous page is "forgot.php". The "Back to Previous Page" link accurately shows that "forgot.php" is the page it will direct to, but now it's no longer in the queue, so if I go to another page, say "profile.php" and then use the back button to go back to "register.php", it will no longer show "forgot.php" as the page that you will go to if you hit "Back to Previous Page" again.
So, I guess my question is really how I can make a link call a PHP function without actually calling that function UNTIL the link has been clicked. I've tried having the link point to a JavaScript function, but the JS functions tend to tell me that my queue is empty, which is completely wrong.
As a side note, the pages are a mix of HTML and PHP. The HTML is supplied to me and I've been adding the PHP in to add functionality to fields and to get data from a database. I have no problem using PHP to echo the HTML links if I have to, and if it can be done in HTML with a small <?php someCode(); ?>, that's fine too.
I thank you for your time to try and help me out.
EDIT:
So to try and clarify a bit, I have a structure that is currently tracking pages that the user has already been to as they visit them. It creates a mini history of the pages. My issue is that I have code like this:
Back To Previous Page
And I don't know what "somelink" is since it will change depending on your history. I know I can do something like:
Back To Previous Page
If I do anything like the above, the function is executed as the page is being displayed, so it makes it difficult to use an array_pop() or a dequeue() but again, the PHP will be executed as soon as the page is displayed. What I'm looking for is a way to display the link and then remove it from the history if and only if the "Back to Previous Page" link is clicked. As of right now, I'm storing an array in $_SESSION as was suggested below and since it's an array, I can show the last element in the array as the link, so the only real problem is to find a way to remove elements from the array when the link is clicked.
EDIT 2:
I've been scouring the internet and decided upon using JavaScript with AJAX to call a PHP file. This allows me to us an onClick on the links I have so that I can control when I array_pop from my $_SESSION['links'] variable.
I don't think my AJAX is actually doing anything sadly, so the code I'm using is below.
<script src="js/jquery-1.4.2.min.js" type="text/javascript">
function dequeue()
{
$.ajax({
type: "POST",
url: "common.php",
data: {action: "rem"},
success: function(output) {
alert(output);
}
});
}
</script>
and the PHP is
switch($_POST['action'])
{
case "rem":
array_pop($_SESSION['links']);
break;
default:
if(isset($_SESSION['current']) && $_SESSION['current'] != $_SERVER['REQUEST_URI'])
{
array_push($_SESSION['links'], $_SESSION['current']);
}
$_SESSION['current'] = $_SERVER['REQUEST_URI'];
break;
}
As far as I can tell, this will allow me to add a link to the history in the session variable unless I'm clicking on the "Back to Previous Page" link since that link will have the "rem" code. I'm also a bit suspicious of the $_SESSION['current'] = $_SERVER['REQUEST_URI']; and where it should be placed.
You can store array in a session and treat the array like a stack (use array_push and array_pop accordingly). When the user hits something but the back button, push the current page to the stack. otherwise, pop it.
I would do it like this if I had to:
$_SESSION["history"] = array();
And within the header of every "rememberable" page:
if(in_array($this_page, $_SESSION["history"])) {
unset($_SESSION["history"][array_search($this_page, $_SESSION["history"])]);
}
array_push($_SESSION["history"], $this_page);
What this does is: "If the page exists in the history, remove it from wherever it is and put it as the last page of the history. If not, just put it as the last page of the history". That way you won't have any loops.
I have two questions about Javascript:
How can I prevent my fields from being cleared when I try to cancel a form submission by returning false in the onsubmit function?
I have a form, which has the onsubmit value "return validate()". If validate() finds an error in the fields, it returns false, which should stop the form submission. It does, but all my fields get cleared, and the browser ignores the Javascript I run before the return statement, like document.write. Example:
function validate() {
//If there's an error:
document.write("Error!");
return false; }
How can I prevent this?
Can I have a form inside a prompt window (a popup)?
I have not only failed to put several inputs in one Javascript prompt(), but also to put a submittable form inside a prompt window. I have a feeling that this is not possible with Javascript, and would like to know how to achieve this.
Thanks.
1) Use alert or elements inner text to display error than document.write. Document write clear the DOM and write the specified content so you will loose the form data.
Use
function validate() {
//If there's an error:
document.getElementById('errorDiv').innerText = 'your error message';
return false; }
2) If you talking about native prompt window, then answer is no. If you talking about JS pop--up then yes, u can put form inside pop up. Pop is just like any browser window where u can show any html page.
onsubmit="return validate()" is fine. There must be another reason your fields are being cleared. What does your validate() function do? Unless your submit button is actually a reset() button - or there's a JavaScript error somewhere and the form is being submitted regardless (check the JavaScript console in the browser).