Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a traditional post in ajax

Suppose I have a form :

<form id="myForm" method="POST" action="/something/somewhere">
   <input type="text" name="textField" />
   <input type="submit" name="foo" value="bar" />
</form>

the /something/somewhere action does not return a complete html page, but just a fragment.

I would like to let the submit button do its posting job, but catch the result of this post and inject it somewhere in the DOM.

The jQuery submit happens before the form is actually submitted. An exemple of how it could work is:

$('#myForm').posted(function(result)
{
    $('#someDiv').html(result);
});

Any way to do this?

like image 504
Johnny5 Avatar asked Jan 27 '12 17:01

Johnny5


2 Answers

Description

You can use the jQuery .post() and .serialize() method for that.

.post() Load data from the server using a HTTP POST request.

.serialize() Encode a set of form elements as a string for submission.

.preventDefault() If this method is called, the default action of the event will not be triggered. In your case the normal submit.

Sample

Html

<form id="myForm" method="POST" action="/My/MyActionMethod">
   <input type="text" name="textField" />
   <input type="submit"/>
</form>

<div id="someDiv"></div>

jQuery

$(function() {
  $('#myForm').live('submit', function (e) {
     var form = $(this);
     e.preventDefault();
     $.post(form.attr('action'), form.serialize(), function (result) {
        $('#someDiv').html(result);
     });
  });
});

MVC Controller

public class MyController : Controller
{
    [HttpPost]
    public ActionResult MyActionMethod(FormCollection forms)
    {
        // do something with forms["textField"];
        return Content("<b>Hello World!</b>");
    }
}

If you have trouble getting it to work (thanks IE), try

event.preventDefault ? event.preventDefault() : event.returnValue = false;

More Information

  • jQuery.post()
  • jQuery.serialize()
  • event.preventDefault()
like image 131
dknaack Avatar answered Oct 01 '22 10:10

dknaack


While you can hack a simple example yourself using .post and .serialize, if you want to do anything more than trivial, I'd suggest looking into this plugin, which is (from what github and the project page says) actively community-maintained by the jQuery folks.

like image 30
Gijs Avatar answered Oct 01 '22 09:10

Gijs