Submit a form using JQuery Ajax

error77
error77 used Ask the Experts™
on
Hi all,

I have a form and I'm submitting it the traditional way.

I need to do this without the page going away or refreshed. Ajax.

Can anyone give me simple instructions on how to do this please?

I prefer the JQuery way if possible.

Thanks

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
here is a simple one

http://net.tutsplus.com/tutorials/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/

but what is the server side language u use?

Author

Commented:
I use PHP.

I've seen that tutorial before but I asked here because I wanted it broken down to the bones.


Don't use form submit.

Change your submit button to just a button.

<input type="button" value="Submit" onclick="form_submit();" />

Your jQuery:

function form_submit();
                    var fullname = $("input[name='fullname']").val();
                    var email = $("input[name='email']").val();
      $.ajax({
            cache: false,
            url: 'http://yoursite.com/process.php',
            type: "POST",
            data: ({
                                            // List your post variables and their values
                                             fullname : fullname,
                email : email  // etc.
                                        }),
            dataType: "json",
            success: function(data){
                                              // what you want done after successful transmission
                                        }
         });
}

Your process.php file:

$fullname = $_POST['fullname'];
$email = $_POST['email'];
// your processing code

$response = json_encode( array(
     'success' => $success
));
      
header( "Content-Type: application/json" );    
echo $response;
exit;
Actually, your response could contain anything that you want:

$response = json_encode( array(
     'success' => true,
    'status' => "Let's party"
));
And then access them through the success function:

      $.ajax({
            cache: false,
            url: 'http://yoursite.com/process.php',
            type: "POST",
            data: ({
                                            // List your post variables and their values
                                             fullname : fullname,
                email : email  // etc.
                                        }),
            dataType: "json",
            success: function(data){
                  if(data.success)
                     alert(data.status); // Displays "Let's Party"
                                              // what you want done after successful transmission
                                        }
         });

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial