Noor
Noor

Reputation: 23

How do I prevent form from redirecting after submission?

I have searched the site and I've found various solutions, most of them suggesting using

return false;

Problem is that I'm using this piece of code to submit the form:

$(function() {  
    $("#snd").click(function() {  
        var dendar = "http://" + $("#inpt").val() + ":" + $("#pwd").val() + "secretsite.lol/something.xml";
        $("#formen").attr("action", dendar);
        $("#formen").submit();
        alert(dendar);
        return false;
    });  
});

The alert is just there to let me know that the form has been submitted..

Thanks guys!

Upvotes: 2

Views: 5551

Answers (4)

Thomas Kjørnes
Thomas Kjørnes

Reputation: 1927

You must return false within the submit() call's event handler, not the click handler.

$("#formen").attr("action", dendar); $("#formen").submit(
   function() { 
      return false;
   }
);

As pointed out by others, this will stop the form from submitting at all. What you want to do is collect the form data and submit it using an Ajax-call.

$.post( url, { var1: value1, var2: value2 etc... });

Upvotes: 4

marcgg
marcgg

Reputation: 66436

Using jquery 1.4:

$("#formen").live("submit",function(e) {  
   e.preventDefault();
}

This will prevent the form from actually submitting. Then you're free to do whatever with the data that was supposed to be posted (use ajax, print something on the page...).

Upvotes: 2

Jason Harwig
Jason Harwig

Reputation: 45551

You can't prevent a redirect, but you can submit the form into a (possibly hidden) iframe so you don't leave the current page

Ajax would be better if the post is to the same server as the current page and you aren't posting file data

Upvotes: 4

jcolebrand
jcolebrand

Reputation: 16025

What about just using an AJAX call with POST to a data handler? That sounds like what you want.

Upvotes: 3

Related Questions