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?

Community
  • 1
  • 1
Fallenreaper
  • 8,518
  • 10
  • 53
  • 107
  • 2
    This is a pretty standard ajax call. http://api.jquery.com/jQuery.ajax/ – Bankzilla Jun 29 '12 at 01: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 Jun 29 '12 at 01:21
  • yea, i didn't want to hard refresh the page, so i didn't want to submit it to myself. – Fallenreaper Jun 29 '12 at 02:22

2 Answers2

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;
  } );
Rob d'Apice
  • 2,366
  • 1
  • 17
  • 29
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

Community
  • 1
  • 1
MultiDev
  • 9,449
  • 22
  • 69
  • 132