简体   繁体   中英

Submit a form with Ajax

I'm making a user script for a site, and my goal is to submit a form on a page that I haven't opened. If I remove all unneeded bits from the page with the form that I want to submit, this is what is left (censoring the links):

<form action="http://foo.com/supply/" method="POST" name="supplyContractForm">
<input type="hidden" name="supplyContractData[selected][]" value="2244068">
<input type="type" name="supplyContractData[party_quantity][2244068]" value="123">  
<input type="text" value="0" name="supplyContractData[quality_constraint_min][2244068]">
<input type="submit" name="applyChanges">
</form>

It's all about the third line: with the 'value="123"'. I want to change that value to "222". What do I do: I change the input value from "123" to "222", I press the submit button, and the form submits: the page reloads, and the value shown is "222". Exactly as I want.

Now, this was all manual, and I want it scripted.

This works:

$("input:submit").click();

However, this doesn't work:

$("form").submit();

And this doesn't work either:

$.post($("form").attr("action"), $("form").serialize())

How can I post this form using Ajax, in a way I can change the value from http://foo.com/main/ ?

Note: I can only do things client-side, I'm just making a user script, and I can't see the server-side code.

This would do the trick

Html, notice the addedd class for cleaner js:

<form action="http://foo.com/supply/" method="POST" name="supplyContractForm">
    <input type="hidden" name="supplyContractData[selected][]" value="2244068">
    <input class="changer" type="type" name="supplyContractData[party_quantity][2244068]" value="123">  
    <input type="text" value="0" name="supplyContractData[quality_constraint_min][2244068]">
    <input type="submit" name="applyChanges">
</form>

Js:

$('form input.changer').val('222');
$('input:submit').click();

The reason why $('form').submit() might not work would be because $('form') matches multiple element, ie do you have multiple forms in your html? if so make the selector more unique, via either adding ids or classes so your selected becomes:

$('#formid').submit();

Ajax

This doesn't use ajax though, for that you would need:

var form = $('form');
$.ajax({
    url: form.attr('action'),
    type: form.attr('method'),
    data: form.serialize(),
    success: function(){
        alert('Form posted via ajax!');
    }
});

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