I'm having some trouble in preventing jquery's ajax call from submitting form data twice.
The form has two fields:
<form id="calendarform_id" method="post" onsubmit="find_schedule()" action="/find_data">
<input id="date1" type="text" required="" name="d_date1">
<input id="date2" type="text" required="" name="d_date2">
</form>
The javascript that makes the ajax call is:
function get_form_data_uid($form){
var form_data_array = $form.serializeArray();
var form_array = {};
$.map(form_data_array, function(n, i){
form_array[n['name']] = n['value'];
});
form_array['uid'] = localStorage.getItem('uid');
return form_array;
}
function find_schedule()
{
var uri, method, formId, $form, form_data;
uri = location.protocol + '//' + location.host + "/find_schedule";
method = "POST";
formId = "#calendarform_id";
$form = $(formId);
form_data = get_form_data_uid($form);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
async: false,
cache: false,
dataType: 'json',
data: form_data
};
$(formId).submit(function(e){
e.preventDefault();
e.stopImmediatePropagation();
// Make the request
$.ajax(request).done(function(data) { // Handle the response
alert(data.message);
}).fail(function(jqXHR) { // Handle failure
console.log("ajax error upon looking up schedule " + jqXHR.status);
}
);
return false;
});
}
Looking at the requests made to the server I see that there is no uid field. I have also tried placing the code retrieving the form data and the user id (uid) as well as the request variable inside the submit handler, but the uid is still not submitted.
Why?
Edit:
I've removed the onsubmit field from the form and moved the submit handler outside the function:
Updated javacript code:
$("#calendarform_id").submit(function(e){
var uri, method, formId, $form, form_data;
uri = location.protocol + '//' + location.host + "/find_schedule";
method = "POST";
formId = "#calendarform_id";
$form = $(formId);
form_data = get_form_data_uid($form);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
async: false,
cache: false,
dataType: 'json',
data: form_data
};
// Prevent implicit submit
e.preventDefault();
e.stopImmediatePropagation();
// Make the request
$.ajax(request).done(function(data) { // Handle the response
alert(data.message);
}).fail(function(jqXHR) { // Handle failure
console.log("ajax error upon looking up schedule " + jqXHR.status);
}
);
return false;
});
Edit #1:
I've added the uid as a hidden field to the form:
<form id="calendarform_id" method="post" action="/find_data">
<input id="date1" type="text" required="" name="d_date1">
<input id="date2" type="text" required="" name="d_date2">
<input id="user_id" type="hidden" name="uid" value="<token_from_local_storage>">
</form>
For some reason apparently I cannot debug code that is within the .submit handler; a simple alert isn't shown either.