Do not clear screen data when giving error

0

Hello, I'm a bit lay with scripts yet. I ask for help, if at all possible.

I have the following script :

 $.ajax({
                    type: "POST",
                    url: "/PreVenda/GuardarPreVenda",
                    dataType: 'json',
                    data: JSON.stringify(json),
                    async: false,//this makes the ajax-call blocking
                    contentType: 'application/json;charset=UTF-8',

                    success: function (response) {
                        alert(response);
                        window.location.reload().ajax();
                        valid = response.valid;
                    },
                    error: function (error) {
                        alert(error);

                    }
                });

            });

I use window.location.reload().ajax(); to save when it clears all the fields on the screen, but when an error occurs on the page, it simply clears the fields too, I just want it to clear the fields, when everything is ok and not when give errors.

If someone can help me, thank you.

    
asked by anonymous 01.09.2017 / 17:40

1 answer

2

You are using window.location.reload() just to clear the form fields and this is not absolutely recommended.

Let's say your form is <form id="form"> , then make a selector on the form identifier and execute:

success: function (response) {
    $("#form")[0].reset();
    valid = response.valid;
}

Or, if the form is cleaned, it is linked to the validity of the response:

success: function (response) {
    valid = response.valid;

    if (valid){
        $("#form")[0].reset();
   };
}

Or as pure javascript (suggestion in comment):

success: function (response) {
    valid = response.valid;

    if (valid){
        document.getElementById("form").reset();
   };
}

Remember to swap #form for the identifier of your form that best suits you.

    
01.09.2017 / 17:59