1

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.

Community
  • 1
  • 1
Sebi
  • 4,262
  • 13
  • 60
  • 116
  • Move your submit handler `$(formId).submit(function(e) { ... })` out of the `find_schedule()` function. – Jasen Oct 13 '15 at 18:46
  • The uid is still not being sent. – Sebi Oct 13 '15 at 18:50
  • 1
    You're getting two posts because you're not preventing the first default submission. `onsubmit=` _is too late for your purpose_. Moving the submit handler outside of `onsubmit` means you'll need to reorganize your code a bit to make the AJAX call work. – Jasen Oct 13 '15 at 18:53
  • I've moved the handler outside the function. However, the uid field is still not set. – Sebi Oct 13 '15 at 19:08
  • You call a method onsubmit of a form than and you bind submit in there? – epascarello Oct 13 '15 at 19:15
  • The question is _Preventing jQuery AJAX call from sending form data twice_ that's a different problem from passing data (`uid`) successfully. For the `uid` you'll need to watch the request and check that the data is properly formatted as json. – Jasen Oct 13 '15 at 19:16
  • The first javascript code works but the form data is being sent twice. I' trying to avoid the default submit of jquery using preventDefault() and and stopImmediatePropagation() – Sebi Oct 13 '15 at 19:17
  • @Jasen but the first example works with the exception that form fields are sent twice; the uid is added as a json object is created from the form fields and its value. – Sebi Oct 13 '15 at 19:19
  • It appears as though you're pulling uid from localStorage; are you sure it's there? – Heretic Monkey Oct 13 '15 at 19:43
  • Yes, I've added it as hidden field to the form(the form is created dynamically using javascript). Strangely, the ajax request is not visible anymore in firebug, even though the server received and sent a response to it. – Sebi Oct 13 '15 at 19:55
  • You can always use a flag to mark if its sent or not... – pojomx Oct 13 '15 at 19:59
  • May you please show me how to do that. I'm not very familiar with debugging jquery ajax calls. – Sebi Oct 13 '15 at 20:46
  • With FF dev tools you can select the Network tab, make your AJAX request, then click that line in the tab to view details about the request. You want to examine the Request Headers and Request Body. Make sure it's what you expect and all of your data is there to help narrow down where the problem might exist. – Jasen Oct 13 '15 at 21:13
  • @Jasen I did. Apparently nothing in$("#calendarform_id").submit(function(e){ ... } gets executed. I have no idea why. – Sebi Oct 13 '15 at 21:37

0 Answers0