views:

118

answers:

9

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" />

Somebody's GOT to know how to do this. Thanks!

+1  A: 

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.

Lucho
+10  A: 

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
I've never coded AJAX. Would it be possible to post an example that directly relates to my code?
Robert Pessagno
Updated example to fit your situation. I assume you are using JQuery.
Bruce Armstrong
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
After changing the variables, do you see the expected post in firebug/ live http headers/charlie/etc? What part doesn't work?
Bruce Armstrong
@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
Thanks for pointing that out, I missed that
Bruce Armstrong
+5  A: 

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
+1  A: 

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
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
Absolutely. I was just covering all the bases. I found that same limitation with the No Content response, too.
staticsan
+1  A: 

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
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
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
Amir Raminfar
I am going to add my code in the answer instead.
Amir Raminfar
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
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
+2  A: 

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

$(function() {
$('.submit').click(function(event) {
    $('#registerform').submit();
    event.preventDefault();
    }); 
});
bozdoz
I tried this, and although the page did not redirect, it failed to send the email.
Robert Pessagno
perhaps event.stopPropagation instead?
bozdoz
nope, that didn't work either
Robert Pessagno
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).
emurano
+2  A: 

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
This worked as you said it would, but it refreshed the page instead of finshing the animation.
Robert Pessagno
+1  A: 

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

PMV
+2  A: 

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
            });
        return false;
    }); 
})
Derek Adair
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
Sorry, did a copy paste job and some of my code snuck in there. -fixed
Derek Adair
woops, missed a comma as well.
Derek Adair