33

I have an HTML form that submits an email with PHP, and when it submits, it redirects to that PHP page. Is there a way to prevent this redirect from happening? I built an animation with jQuery that I want to occur instead of redirecting. I tried return false;, but it wouldn't work. Here's my function:

$(function() { $('.submit').click(function() { $('#registerform').submit(); return false; }); }); 

Here's the opening form tag:

<form id="registerform" action="submit.php" method="post"> 

And the submit button:

<input type="submit" value="SUBMIT" class="submit" /> 
2
  • 2
    Thanks for the tip. I'm kind of new to Stack Overflow; still getting used to the way t things work. But I rarely get answers that I can say are the one's I "accept." I'll go back through them, though. Any guidance on this particular question? Commented Oct 27, 2010 at 23:40
  • I'd go for Bruce Armstrong's or Derek Adair's answer. Commented Nov 14, 2011 at 9:14

16 Answers 16

42

You should post it with ajax, this will stop it from changing the page, and you will still get the information back.

$(function() { $('form').submit(function() { $.ajax({ type: 'POST', url: 'submit.php', data: { username: $(this).name.value, password: $(this).password.value } }); return false; }); }) 

See Post documentation for JQuery

Sign up to request clarification or add additional context in comments.

10 Comments

I've never coded AJAX. Would it be possible to post an example that directly relates to my code?
Updated example to fit your situation. I assume you are using JQuery.
Yes, I am using jQuery. I tried out your code, and it didn't seem to work. Does the location of the script matter? Do I keep type="submit" on the submit button?
After changing the variables, do you see the expected post in firebug/ live http headers/charlie/etc? What part doesn't work?
@Robert Pessagno - You'll need to override the submit method of your form e.g., instead of $('.submit').click() use $('form').submit(). The submit event docs for JQuery are here: api.jquery.com/submit
|
18

Instead of return false, you could try event.preventDefault(); like this:

$(function() { $('#registerform').submit(function(event) { event.preventDefault(); $(this).submit(); }); }); 

5 Comments

I tried this, and although the page did not redirect, it failed to send the email.
perhaps event.stopPropagation instead?
preventDefault() will just stop the browser from submitting the form. The asker does want to invoke the form handling code in the PHP page (so that it sends the e-mail).
When processdata is true it redirect anyways!
This caused an infinite loop for me. It's preventing submission, then calling submit again...?
8
$('#registerform').submit(function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'submit.php', data: $(this).serialize(), beforeSend: //do something complete: //do something success: //do something for example if the request response is success play your animation... }); }) 

Comments

6

Using Ajax

Using the jQuery Ajax request method you can post the email data to a script (submit.php). Using the success callback option to animate elements after the script is executed.

note - I would suggest utilizing the ajax Response Object to make sure the script executed successfully.

$(function() { $('.submit').click(function() { $.ajax({ type: 'POST', url: 'submit.php', data: 'password=p4ssw0rt', error: function() { alert("Request Failed"); }, success: function(response) { //EXECUTE ANIMATION HERE } // this was missing }); return false; }); }) 

5 Comments

I'm getting a JavaScript error on the line 7: "missing } after property list" and I can't seem to figure out how to fix it
Sorry, did a copy paste job and some of my code snuck in there. -fixed
woops, missed a comma as well.
@DerekAdair : won’t pass Same Origin Policy. I don’t control the target domain. That’s why I used form instead of Ajax.
the problem with ajax is that if i change button type='submit' to type='button' i lose all of the native browser restrictions on my input elements... do u know a way to use AJAX while maintaining browser restrictions on input elements?
5

If you want the information in the form to be processed by the PHP page, then you HAVE to make a call to that PHP page. To avoid a redirection or refresh in this process, submit the form info via AJAX. Perhaps use jQuery dialog to display the results, or your custom animation.

Comments

4

If you can run javascript, which seems like you can, create a new iframe, and post to that iframe instead. You can do <form target="iframe-id" ...> That way all the redirects happen in the iframe and you still have control of the page.

The other solution is to also do a post via ajax. But that's a little more tricky if the page needs to error check or something.

Here is an example:

$("<iframe id='test' />").appendTo(document.body); $("form").attr("target", "test"); 

5 Comments

I like the iframe solution; I've seen it done before, and it worked well. But I don't know what JavaScript to write to make it work.
I think you can do something like $("<iframe id='test' ...../>").appendTo(document.body); then do $("form").attr('target', 'test'); You have to make sure the two ids match
I have no problem putting an iframe into my page. I don't need JS to do that. But the form still wants to redirect to the PHP page when it is submitted.
Sure, but you can have the PHP page load into the iframe instead. You don't even need any JavaScript for it, really. Just put an iframe next to your submit button, the same height, and use TARGET= on your form to load the results page into it. (Initially, the iframe's src should load a blank page.) The result page should just be a simple one-line message like "Successfully submitted."
thats my issue right now. i need to figure out how to allow native browser restrictions on input elements, but use AJAX instead
4

With out knowing exactly what your trying to accomplish here its hard to say but if your spending the time to solve this problem with javascript an AJAX request is going to be your best bet. However if you'd like to do it completely in PHP put this at the end of your script, and you should be set.

if(isset($_SERVER['HTTP_REFERER'])){ header("Location: " . $_SERVER['HTTP_REFERER']); } else { echo "An Error"; } 

This will still cause the page to change, twice, but the user will end on the page initiating the request. This is not even close to the right way to do this, and I highly recommend using an AJAX request, but it will get the job done.

1 Comment

This worked as you said it would, but it refreshed the page instead of finshing the animation.
3

You can use as below

e.preventDefault() 

If this method is called, the default action of the event will not be triggered.

Also if I may suggest read this: .prop() vs .attr()

I hope it will help you,

code example:

$('a').click(function(event){ event.preventDefault(); //do what you want } 

Comments

1

The design of HTTP means that making a POST with data will return a page. The original designers probably intended for that to be a "result" page of your POST.

It is normal for a PHP application to POST back to the same page as it can not only process the POST request, but it can generate an updated page based on the original GET but with the new information from the POST. However, there's nothing stopping your server code from providing completely different output. Alternatively, you could POST to an entirely different page.

If you don't want the output, one method that I've seen before AJAX took off was for the server to return a HTTP response code of (I think) 250. This is called "No Content" and this should make the browser ignore the data.

Of course, the third method is to make an AJAX call with your submitted data, instead.

2 Comments

I have used the no content response back in the day. The main issue was that it was impossible to give any feedback to the user. If you want any indication that the request was successful, then AJAX is the way to go. This is no criticism of your answer, just my vote for option 3 within it :)
Absolutely. I was just covering all the bases. I found that same limitation with the No Content response, too.
1

The simple answer is to shoot your call off to an external scrip via AJAX request. Then handle the response how you like.

2 Comments

I found a jQuery plugin that uses AJAX to submit a form via PHP script. Worked perfectly for what I needed: jquery.malsup.com/form
@Parris Varney : won’t pass Same Origin Policy. I don’t control the target domain. That’s why I used form instead of Ajax.
1

Just like Bruce Armstrong suggested in his answer. However I'd use FormData:

$(function() { $('form').submit(function() { var formData = new FormData($(this)[0]); $.ajax({ type: 'POST', url: 'submit.php', data: formData, processData: false, contentType: false, }); return false; }); }) 

2 Comments

So how is your answer different from Bruce's?
This does not prevent redirect
1

You must put the return inside submit() call.

 $('.submit').click(function() { $('#registerform').submit(function () { sendContactForm(); return false; }); //Here you can do anything after submit } 

Comments

1

Since it is bypassing CORS and CSP, this is to keep in the toolbox. Here is a variation.

This will POST a base64 encoded object at localhost:8080, and will clean up the DOM after usage.

const theOBJECT = {message: 'Hello world!', target: 'local'} document.body.innerHTML += '<iframe id="postframe" name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe><form id="dynForm" target="hiddenFrame" action="http://localhost:8080/" method="post"><input type="hidden" name="somedata" value="'+btoa(JSON.stringify(theOBJECT))+'"></form>'; document.getElementById("dynForm").submit(); dynForm.outerHTML = "" postframe.outerHTML = ""

From the network debugger tab, we can observe a successful POST to a http:// unencrypted server from a tls/https page.

enter image description here

Comments

0

Probably you will have to do just an Ajax request to your page. And doing return false there is doing not what you think it is doing.

Comments

0

You can simply make your action result as NoContentResult on controller

public NoContentResult UploadFile([FromForm] VwModel model) { return new NoContentResult(); } 

Comments

0

I found this page 10 years (!) after the original post, and needed the answer as vanilla js instead of AJAX. I figured it out with the help of @gargAman's answer.

Use an appropriate selector to assign your button to a variable, e.g.

document.getElementById('myButton')

then

myButton.addEventListener('click', function(e) { e.preventDefault(); // do cool stuff }); 

I should note that my html looks like this (specifically, I am not using type="Submit" in my button and action="" in my form:

 <form method="POST" action="" id="myForm"> <!-- form fields --> <button id="myButton" class="btn-submit">Submit</button> </form> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.