Reputation: 325
<form target="_blank" method="POST" action="somePage.php" id="myForm">
<input type="hidden" name="someName" value="toBeAssignedLater"/>
<button type="submit">Proceed</button>
</form>
At the beginning, the value of someName
is not determined yet, I want to execute an Ajax to get and assign the value to it before the form is actually submitted.
I tried:
$("#myForm").submit(function (e) {
var $this = $(this);
someAjaxFunction(function (data) {
$this.find('input[name="someName"]').val(data.value);
});
});
But the form would have already submitted before the Ajax is finished, how can I ensure the form would be submitted after the Ajax is finished.
I want to keep the form submit
event initiated by the user instead of code, such as $("#myForm").trigger('submit');
, since I don't want the new window tab to be blocked by browsers.
Upvotes: 1
Views: 61
Reputation: 32354
Why don't you ajax the value at page load and than submit the data?
$(function(){
someAjaxFunction(function (data) {
$('input[name="someName"]').val(data.value);
});
$("#myForm button").on('click',function(){
$(this).submit();
});
});
or place the ajax call on click event and submit whan the values is updated:
$(function(){
$("#myForm button").on('click',function(e){
e.preventDefault();
$.ajax({
url:url, //other params
success:function(data){
//thing to do before submit
$('input[name="someName"]').val(data.value);
$(this).submit();
}
});
});
});
Upvotes: 2
Reputation: 15893
$("#myForm").submit(function (e) {
var $this = $(this);
someAjaxFunction(function (data) {
$this.find('input[name="someName"]').val(data.value);
// submit form without triggering jquery handler
$this[0].submit();
});
// cancel the current submission
return false;
});
Upvotes: 2