6

Possible Duplicate:
jQuery AJAX submit form

I have a form on a page A, and instead of me posting to a new page, is there a way that i can do onSubmit ajax request it instead? I want to make the page to be able to load in the result into a div.

I know how to write the script for the call sort of, but i wasn't sure if i had to hand write it or it if was possible to take all the form information and send it without having to code it all into the attributes. i was thinking I could just do some sort of thing like: onClick, post form but return results into a div.

Thoughts? Ideas?

3
  • 2
    This is a pretty standard ajax call. api.jquery.com/jQuery.ajax
    – Bankzilla
    Commented Jun 29, 2012 at 1:10
  • I'm actually wondering if you need AJAX at all. Can't you just actually submit the form to the same page and have the PHP dynamically load the div with the form data? Is there some reason why that can't be done?
    – Palladium
    Commented Jun 29, 2012 at 1:21
  • yea, i didn't want to hard refresh the page, so i didn't want to submit it to myself. Commented Jun 29, 2012 at 2:22

2 Answers 2

7

Try using JQuery's serialize (API ref here)

EDIT: something like this:

 $("input.submit").click( function() {
    $.ajax( {
      type: "POST",
      url: $("form").attr( 'action' ),
      data: $("form").serialize(),
      success: function( response ) {
        //Code to process the response
      }
    });
    return false;
  } );
4
  • so, serialize snags all the data from a form eh? Commented Jun 29, 2012 at 2:25
  • 2
    Yep, and it parses it into a string. Commented Jun 29, 2012 at 2:30
  • Thanks! That is a fantastic thing to know! Commented Jun 29, 2012 at 2:51
  • How does one snatch a data from a specific form maybe by using the id of the form $("#form").serialize(); doesn't seem to work for me.
    – drleifz
    Commented Apr 13, 2015 at 11:41
5
$.ajax({
 url: 'mypage.html',
 success: function(data){
    $('.result').html(data);
 },
 error: function(){
   alert('failure');
 }
});

Then you have a div:

<div class="result"> </div>

This will automatically populate with the result of your ajax post.

http://api.jquery.com/jQuery.post/

Also see TONS of related questions: Jquery checking success of ajax post

1
  • since it doesn't define the data, will it just submit everything in that form? Commented Jun 29, 2012 at 2:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.