Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting an HTML form to PHP using JQuery AJAX

Tags:

html

jquery

forms

I was wondering if there was a succinct way to submit a form to my backend with JQuery AJAX (async). What I mean, more specifically, is:

HTML Form:

<form method="post" action="/Intranet/Resources/Forms/WorkOrder.php">
    <input type="text" name="notes[]" />
    <input type="text" name="notes[]" />
    ...
    <!-- a whole bunch more input fields here -->
</form>

This form is pretty awkward to separate into a bunch of variables with JQuery. I don't want the user to be redirected away from the page - I want the form to submit asynchronously. It's actually a save button...

Would it be better to screw it and just use JSON?

like image 779
Daniel Kats Avatar asked Feb 23 '26 21:02

Daniel Kats


2 Answers

$(function(){
    $("form").submit(function(){
        $.ajax({
            url:"save.php",
            type:"post",
            data:$(this).serialize(),
            success: alert('saved');
        });
    });
});
like image 195
genesis Avatar answered Feb 25 '26 11:02

genesis


You can use $('form').serialize() to serialize a form. The result (for your form) would be:

notes=val1&notes=val2

http://api.jquery.com/serialize/

like image 31
Adam Hopkinson Avatar answered Feb 25 '26 11:02

Adam Hopkinson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!