lewis4u lewis4u - 1 year ago 78
Ajax Question

Laravel - ajax creates double input

I have made this ajax request to show the validation errors and prevent the page to reload

$(document).on('mousedown', ':submit', function() {
//alert('clicked submit');
var form = $("form");
$.ajax({
type: 'post',
url: '/events',
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
data: form.serialize(),
dataType: 'json',
success: function(data){

},
error: function(data) {
for(errors in data.responseJSON){
swal({text:data.responseJSON[errors]});
}
}

});
});


All is fine with this code! The problem is that after successfull submit i have 2 inputs in DB...how can i prevent this?

Answer Source

Are you sure the form isn't actually submitting and saving the values once by post and once by ajax? Usually if you're capturing a submit event you listen for the forms submit even not the mousedown event of the submit button e.g.

$('form').on('submit', function(e) {

    // Stop the forms default submit action
    e.preventDefault();

    //alert('clicked submit');
    var form = $("form");
    $.ajax({
        type: 'post',
        url: '/events',
        headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
        data: form.serialize(),
        dataType: 'json',
        success: function(data){

        },
        error: function(data) {
            for(errors in data.responseJSON){
                swal({text:data.responseJSON[errors]});
            }
        }

    });
});

Also the e.preventDefault() will prevent the form from submitting itself along with your ajax action. Also you'd best off selecting your form by an ID or class name.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download