Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error handling on form submit

Tags:

javascript

I have a form having some data

<form id="abc" method="POST" action="abc.html">
<input type="hidden" id="a" name="a" />
<input type="hidden" id="b" name="b" value="save"/>
</form>

and in js file i am submitting this form

document.getElementById("abc").submit();

What i want to do is if it throws any exception then an alert popup should open. Can anyone help?

like image 913
Abhinav Parashar Avatar asked Oct 02 '22 19:10

Abhinav Parashar


1 Answers

Both previous answers are wrong. They check that object form exists but don't handle server-side errors.

You could use jQuery Form Plugin:

$('#myForm')
    .ajaxForm({
        url : 'myscript.php', // or whatever
        dataType : 'json',
        success : function (response) {
            alert("The server says: " + response);
        }
    })
;

or simple ajax :

$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(){
        console.log('form submitted.');
      }
    });
    return false;
});

You could find more details in answers to this question - How do I capture response of form.submit

like image 50
RredCat Avatar answered Oct 12 '22 11:10

RredCat