Ali Khalili
Ali Khalili

Reputation: 1684

Contacting server in JS client side form validation

I have an HTML form. I am already doing a client side HTML.

    <form id='myForm' onsubmit='return myFormValidation()'>
       ...
    </form>

Now, in myFormValidation function, after making sure the client side is OK, before really submitting the form, I want to do also a server side form validation. I am using JQuery. So,I changed my function to something like this:

function myFormValidation(){
  //first, client side validation
  ...
  //then, server side validation
  $.post(url_of_server_side, $("#myform").serialize(), function(json) {
    data = JSON.parse(json);
    if(!data.ok)
    {
       $("#msg").text("some error");  
    }
    else
    {
       $("#myForm").submit();//Oops!
    }
    });
    return false;
}

But the "submit" function of form behaves like a recursive function and tries to validate the form again! Should I disable the validation function before calling submit? Or, I guess, there is a better way for my problem (which is slightly or even totally different than this)?

Upvotes: 1

Views: 154

Answers (2)

VadimB
VadimB

Reputation: 5711

If you need server side validation you should extend your "Save" enpoint to support correct response status codes and do not use separate "Validation" url. Use single url with different response types:

  • 200 (Success) - data was saved successfully
  • 400 (Bad request) - input data was incorrect. As response message you can include "validation result" message which you will display to user.

So your code can looks like

$.post(url_of_server_side, $("#myform").serialize())
  .done(function() {
    //show some success confirmation or redirect to main page
  }).fail(function(xhr, status, error) {
    $("#msg").text(error.message);  
  });

Upvotes: 1

Alexios Tsiaparas
Alexios Tsiaparas

Reputation: 910

I would suggest, if all data is OK, the server-side script to perform the action that you want, e.g. saving to database. That way, you will not need a second post of the form in case everything is correct. If something is wrong, then obviously, the checks must take place the second time as well.

Upvotes: 0

Related Questions