3

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);
    }
Half_Duplex
  • 5,102
  • 5
  • 42
  • 58
  • If the form is being submitted normally, you can't handle the error with javascript. – Kevin B Jan 15 '14 at 20:28
  • _"I'm trying not to use ajax"_ No, I don't think you can handle any type of errors since you are submitting the form to another page – Adam Azad Jan 15 '14 at 20:29
  • Unless, you submit the form to an iframe. Then, you can listen for the iframe load event and inspect it's contents to see if it is the error page or something else. – Kevin B Jan 15 '14 at 20:30
  • @Kevin B - What if I were to submit it myself using the jQuery submit() within my submit handler? – Half_Duplex Jan 15 '14 at 20:53
  • 2
    @Half_Duplex still nothing you can do, as the 500 error would be on another document entirely. – Kevin B Jan 15 '14 at 20:54
  • @KevinB Looks like I'll have to ajax and atry to serialize this form. – Half_Duplex Jan 15 '14 at 21:01
  • 1
    Note that if you're posting files, you won't be able to use jquery's serialize method. – Kevin B Jan 15 '14 at 21:09
  • @Kevin B - used the FormData object and that takes care of the file input as well as the rest of the form. – Half_Duplex Jan 17 '14 at 16:57

3 Answers3

2

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.

Community
  • 1
  • 1
Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
  • Thanks, but my goal was to replace ajax for this form with a creative alternative. I'm aware of how the config and server side work, I wrote the back end to return the 500. I don't want a redirect on any response, success or failure. I know I can suspend/divert form submission with jQuery, seems there should be a way to avoid the page refresh on the 500. – Half_Duplex Jan 15 '14 at 20:50
1

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);
        }
    }
});
});
Afzaal Ahmad Zeeshan
  • 15,669
  • 12
  • 55
  • 103
mohammed momn
  • 3,230
  • 1
  • 20
  • 16
  • I do not want to use ajax for this particular form, and also I'm already using ajaxSetup for the ajax that's happening everywhere else on the page. – Half_Duplex Jan 15 '14 at 20:48
0

After more reading, I found this was possible using a FormData object. This even takes care of the multiselect. Here's the code:

<form id="theForm">
    <input name="text" type="text">
    <select name="fileType">
    ...
    </select>
    <input name="file" type="file">
</form>

The jQuery

$("#theForm").submit(function(e){
    e.preventDefault();
    var theForm = new FormData($(this)[0]);
    $.ajax({
        url: '.../rest/save',
        type: 'POST',
        data: theForm,
        cache, false,
        contentType: false,
        processData: false
    });
    return false;
});

Jersey resource

@POST
@Path("/save")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void save(   
    @FormDataParam("text") String text,
    ....
    @FormDataParam("file") InputStream inputStream,
    @FormDataParam("file") FormDataContentDisposition fileDetail){
        log.info(fileDetail.getFileName());
        // exceptions return 500
        throw new ServerException(500);
    }
Half_Duplex
  • 5,102
  • 5
  • 42
  • 58