quersfas
quersfas

Reputation: 47

About AJAX, need to click submit button two times

My ajax code looks like this:

 $("#form").submit(function(event){

        var $form = $(this);
        var serializedData = $form.serialize();
        var $inputs = $form.find("input, select, button, textarea");

        request = $.ajax({
            url: "/blog/ajaxphp/registration_check.php",
            type: "post",
            data: {formData:serializedData},
            datetype: "JSON"
        });
        request.done(function (response, textStatus, jqXHR){
            if(jQuery.parseJSON(response).success==undefined){
                $form.unbind('submit');
                $form.submit();
            }
        });
        request.fail(function (jqXHR, textStatus, errorThrown){
        });
        event.preventDefault();


    });

Problem: I need to click submit button twice otherwise this form is not being submitted. I tried using return false instead of preventdefault and also tried $form.unbind('submit'); but not working.

how to i make submit button to work by 1 click

Upvotes: 1

Views: 368

Answers (1)

Jeremiah Reed
Jeremiah Reed

Reputation: 83

In the request.done event, return true if success is not undefined. You may consider an alternative to unbinding and resubmitting the form when success is undefined, or removing that portion all together and just showing a message that says that the form could not be submitted and should be tried again. It's worth trying just to see if simplifying the process yields the results you want.

I would also remove event.preventDefault(); and just return false inside the request.fail event.

I assume you are doing all of this because you don't want to submit the form before the ajax call is finished, so you might want to try adding async: false to your $.ajax request:

$("#form").submit(function(event){

    var $form = $(this);
    var serializedData = $form.serialize();
    var $inputs = $form.find("input, select, button, textarea");

    request = $.ajax({
        url: "/blog/ajaxphp/registration_check.php",
        type: "post",
        data: {formData:serializedData},
        async: false,
        datetype: "JSON"
    });
    request.done(function (response, textStatus, jqXHR){
        if(jQuery.parseJSON(response).success==undefined){
            $form.unbind('submit');
            $form.submit();
        }
        else
        {
            return true;
        }
    });
    request.fail(function (jqXHR, textStatus, errorThrown){
            return false;
    });
});

Upvotes: 1

Related Questions