EACoder EACoder - 5 months ago 38
jQuery Question

form onsubmit ignores action

I am new to JavaScript. I have a form with an action and I need to fill the form inputs using JavaScript on submitting. I use an

onsubmit
function which executes as expected, but the form didn't hit the action in the
action
attribute and no data is sent to the server.

Can anybody help me find what is missing ?

JavaScript/jQuery:

$("#myForm").submit(function (e) {
e.preventDefault();
return fillFormValues();
})

function fillFormValues()
{
$.get( ...,function( data ) {
//fill my inputs values here
return true;
});
return false;
}


HTML:

<form action="..." method="post" target="output_frame" id="myForm">
<input name="first" id="first" type="hidden" value="">
...
<input type="submit" value="next">
</form>

Answer

what you can do is prevent the jQuery event default that would submit the form, do the ajax and once values are set trigger the native submit event that will bypass the jQuery submit listener

$("#myForm").submit(function(e) {
  e.preventDefault();
  fillFormValues(this);
});

function fillFormValues(form) {
  $.get(..., function(data) {
    //fill your inputs values here
    form.submit(); //trigger native submit which is not caught by jQuery
  });
}
Comments