32

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" />
Robert Pessagno
  • 519
  • 2
  • 7
  • 19
  • 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? – Robert Pessagno Oct 27 '10 at 23:40
  • I'd go for Bruce Armstrong's or Derek Adair's answer. – Urs Reupke Nov 14 '11 at 09:14

16 Answers16

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

Bruce Armstrong
  • 1,562
  • 10
  • 11
  • 2
    I've never coded AJAX. Would it be possible to post an example that directly relates to my code? – Robert Pessagno Oct 28 '10 at 00:02
  • 1
    Updated example to fit your situation. I assume you are using JQuery. – Bruce Armstrong Oct 28 '10 at 00:40
  • 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? – Robert Pessagno Oct 28 '10 at 16:32
  • After changing the variables, do you see the expected post in firebug/ live http headers/charlie/etc? What part doesn't work? – Bruce Armstrong Oct 28 '10 at 16:38
  • @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: http://api.jquery.com/submit/ – rojoca Oct 28 '10 at 20:40
  • If you haven't seen it already, I found a jQuery plugin that uses AJAX to submit a form via PHP script. Worked perfectly for what I needed: http://jquery.malsup.com/form/ – Robert Pessagno Nov 03 '10 at 17:57
  • @BruceArmstrong : won’t pass Same Origin Policy. I don’t control the target domain. That’s why I used form instead of Ajax. – user2284570 Sep 11 '15 at 20:49
  • @BruceArmstrong,if need upload some files, is any way? – sendreams May 17 '16 at 18:35
  • Why do I need to do $(this)[0].name.value ? (notice the index) – Murphybro2 May 30 '18 at 10:15
  • 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? – oldboy Jul 28 '19 at 23:56
18

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

$(function() {
$('#registerform').submit(function(event) {
    event.preventDefault();
    $(this).submit();
    }); 
});
bozdoz
  • 12,550
  • 7
  • 67
  • 96
7
$('#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...
   });

})
Matricore
  • 575
  • 7
  • 12
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;
    }); 
})
bubencode
  • 77
  • 10
Derek Adair
  • 21,846
  • 31
  • 97
  • 134
  • 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 – Robert Pessagno Oct 28 '10 at 20:51
  • Sorry, did a copy paste job and some of my code snuck in there. -fixed – Derek Adair Oct 28 '10 at 21:18
  • woops, missed a comma as well. – Derek Adair Oct 28 '10 at 21:30
  • @DerekAdair : won’t pass Same Origin Policy. I don’t control the target domain. That’s why I used form instead of Ajax. – user2284570 Sep 11 '15 at 20:50
  • 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? – oldboy Jul 28 '19 at 23:55
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.

mwotton
  • 2,170
  • 18
  • 36
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");
Amir Raminfar
  • 33,777
  • 7
  • 93
  • 123
  • 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. – Robert Pessagno Oct 28 '10 at 00:09
  • I think you can do something like $("").appendTo(document.body); then do $("form").attr('target', 'test'); You have to make sure the two ids match – Amir Raminfar Oct 28 '10 at 00:13
  • 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. – Robert Pessagno Oct 28 '10 at 00:32
  • 1
    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." – kindall Oct 28 '10 at 23:03
  • thats my issue right now. i need to figure out how to allow native browser restrictions on `input` elements, but use AJAX instead – oldboy Jul 28 '19 at 23:52
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.

Steven Zurek
  • 535
  • 5
  • 18
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
  } 
gargAman
  • 111
  • 1
  • 5
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;
    }); 
})
Community
  • 1
  • 1
flix
  • 1,821
  • 18
  • 23
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.

staticsan
  • 29,935
  • 4
  • 60
  • 73
  • 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 :) – mwotton Oct 27 '10 at 23:59
  • Absolutely. I was just covering all the bases. I found that same limitation with the No Content response, too. – staticsan Oct 28 '10 at 00:02
1

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

Parris Varney
  • 11,320
  • 12
  • 47
  • 76
  • I found a jQuery plugin that uses AJAX to submit a form via PHP script. Worked perfectly for what I needed: http://jquery.malsup.com/form/ – Robert Pessagno Nov 03 '10 at 17:58
  • @Parris Varney : won’t pass Same Origin Policy. I don’t control the target domain. That’s why I used form instead of Ajax. – user2284570 Sep 11 '15 at 20:52
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
}
Juan
  • 15
  • 5
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

NVRM
  • 11,480
  • 1
  • 88
  • 87
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.

Lachezar
  • 6,523
  • 3
  • 33
  • 34
0

You can simply make your action result as NoContentResult on controller

public NoContentResult UploadFile([FromForm] VwModel model)
    {
       return new NoContentResult();
    } 
Serenity
  • 35,289
  • 20
  • 120
  • 115
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>
ron_g
  • 1,474
  • 2
  • 21
  • 39