简体   繁体   中英

NO refresh the page when success ajax

I have a ajax section to submit data in laravel. I want if I submit success then don't reload the page and submit the error then reload the page. In the code below, when the error reloads the page correctly, I am having a problem in the success case, the page must not be reloaded, but the result is reloaded. I have added the line e.preventDefault () then true in the success case but wrong in the error case

$(document).ready(function() {   
        $('form').submit(function(e){
            //e.preventDefault();
            var form_data = $(this).serialize();
            $.ajax({
                url:'{{ route('contracts.store') }}',
                method: "POST",
                data: form_data,
                dataType: "json",
                success: function(data) {
                    $("#mgsContract").text("Add successfully");
                    $("#hideForm").css("visibility", "visible"); 
                    $("#hideForm").css("height", "auto"); 
                    $("#result-contract-id").val(data.contract_obj);
                },
                error: function(data) {
                    $("#mgsContract").text("Something wrong");
                }
            })
        });
    });

Add back that e.preventDefault() to prevent the form submission, and in the error case, call location.reload() . (Or if you want to submit the form conventionally in the error case, use e.target.submit(); instead. Since that's calling submit on the DOM element [not a jQuery wrapper], it won't call your submit handler again. [This is one of the differences between programmatically calling submit on a DOM element vs. calling it on a jQuery object.])

when you use ajax, laravel automatically responds in JSON for validation errors. therefore to access the validation errors you can use this.responseJSON.errors in error section of your ajax. there is no need to reload the page to access validation errors.

however in any case if you need to reload or go to specific location you can use window.location

window.location.href = "an address"; // going to specific location

window.location.reload(); //reloading the page

an ajax example is the following, in which a loop for showing all errors inside the form is specified.

               $("#form_id").submit(function (e) {

        e.preventDefault(); // avoid to execute the actual submit of the form.

        var form = $(this);
        var url = form.attr('action');

        $.ajax({
            method: "POST",
            url: url,
            data: form.serialize(), // serializes the form's elements.
            success: function (data) {
                    // code in the case of success
            },

            error: function (err) {
                if (err.status == 422) { // when status code is 422, it's a validation issue
                   // code in the case of error
                    console.log(err.responseJSON); 

                    // you can loop through the errors object and show it to the user
                    console.warn(err.responseJSON.errors);

                    // display errors on each form field
                    $.each(err.responseJSON.errors, function (i, error) {

                        var el = $(document).find('[name="' + i + '"]');
                        el.removeClass('is-valid');
                        el.addClass('is-invalid');
                        var parent = el.parents('.form-group');
                        parent.append("<small  class='error-message text-right text-danger d-block pr-5 ' role='alert'>" + error + "</small >");
                    });
                }
            },


        });


    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM