Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle 500 error on form submit with JS or jQuery?

I'm using a standard form/action to post to a restful web service, I'm trying not to use ajax due to the size and makeup of the form. Is there a way to attach error handling to the form submission? See my current code below.

<form   id="theForm" 
        action="rest/url" 
        method="post" 
        enctype="multipart/form-data">
</form>

$("#theForm").submit(function(e){           
    // Can anything be done to handle 500s here?            
});

Here's the rest service.

@POST
@Path("/save")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void save(   
    @FormDataParam("iD") Integer iD,
    ....
    @FormDataParam("file") InputStream inputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail
    {
        // void to avoid redirect

        // exceptions return 500
        throw new ServerException(500);
    }
like image 809
Half_Duplex Avatar asked Jan 21 '26 05:01

Half_Duplex


2 Answers

Try this:

<form method="post" id="form>

</form>

Ajax code:

$('#form').submit(function () {
  $.ajax({
    url: 'your_url.html',
    data: 'some_data=somevalue',
    success: function (response) {
      // it was a success!
    }
    error: function () {
      // it was an error!
    }
  });
});

Please note you cannot handle the normal submission process! Only ajax requests can be checked by HTTP response. Simple form submit cannot be handled!

You can execute the above code on a submit button click!

Don't wanna use Ajax?

If you don't want to use ajax, then you need to use a server-side code. And check for the HTTP Resonse from the server! If it is 500, then redirect the user to another page! But remember, you cannot use jQuery to check the HttpResponseCode for the default submission process!

It is better if you start learning about web.config. That is the file where you manage the error and other customization of how server responds to the error and other conditions.

like image 68
Afzaal Ahmad Zeeshan Avatar answered Jan 23 '26 17:01

Afzaal Ahmad Zeeshan


You can handle each type of Ajax error like that

$(function() {
$.ajaxSetup({
    error: function(jqXHR, exception) {
        if (jqXHR.status === 0) {
            alert('Not connect.\n Verify Network.');
        } else if (jqXHR.status == 404) {
            alert('Requested page not found. [404]');
        } else if (jqXHR.status == 500) {
            alert('Internal Server Error [500].');
        } else if (exception === 'parsererror') {
            alert('Requested JSON parse failed.');
        } else if (exception === 'timeout') {
            alert('Time out error.');
        } else if (exception === 'abort') {
            alert('Ajax request aborted.');
        } else {
            alert('Uncaught Error.\n' + jqXHR.responseText);
        }
    }
});
});
like image 22
mohammed momn Avatar answered Jan 23 '26 19:01

mohammed momn