简体   繁体   中英

How do I submit form using ajax

I have my form and my ajax laid out but I am not sure how to submit the form using the ajax. I've tried $('#testform').submit() but it didn't call my ajax when I wrapped it with the submit. I might of been doing it wrong. How do I get my form to submit through the ajax and not submit regularly?

<form id="testform" action="https://example.com/api/payments/" method="post">

Name<input type="text" name="name" id="name">
Card Number <input type="text" name="card_number" id="card_number" maxlength="16">
Exp Month <input type="text" name="exp_month" id="exp_month">
Exp Year <input type="text" name="exp_year" id="exp_year">
CVC <input type="text" name="cvc" id="cvc" maxlength="3">
Amount  <input type="text" name="amount" id="amount">

<input type="submit" id="submit">

frm = $('#testform');
frm.submit(function(ev)
{
$.ajax({
    type: frm.attr('method'),
    url: frm.attr('action'),
    dataType: "html",
    //Set the HTTP headers for authentication
    beforeSend: function (xhr) {
        xhr.setRequestHeader('api_key', 'tiyndhinzrkzti5ody0');
        xhr.setRequestHeader('email', 'example@example.com');
    },
    //Serialize the data sent from the form inputs
    data: frm.serialize(),
    success: function(data) {
        $('#return').append(data);
   }
});
ev.preventDefault();       
});

Instead of frm.submit(function(ev) try the following code

$("#testform").on('submit', function(ev) {
    ev.preventDefault();   
    ...
});

After clicking on the submit button you should see the ajax being posted in the console. The "magic" is to attach a handler to the submit event instead of invoking the event itself. Additionally, you had a typo in your previous code ( $('testform') instead of $("#testform") )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM