0

I have a jqGrid form for creating new users and what i want is to ensure that (among the other fields submitted by the form) the username does not already exist in the database.
So i created a beforeSubmit action, that is executed when the submit button is pressed but before the form is submitted.
I think the function works, because the code bellow always returns "User exists";

beforeSubmit:function(postdata,formid) { return[false,"User exist"]; }

But when i try ti use the $.get to make an ajax request to the server in order to see if the username already exists, i always get a k is undefined error. This is the code the produces the error

beforeSubmit:function(postdata,formid) {

$.get("project-management?r=Users/usernameExists&tmpl=json&username=" + postdata.username, function(data) {
return[false,"Exists"];
}); }

I know that this is not a real validation but shouldn't produce the same result as the first script?

Thanks a lot

tliokos
  • 3,606
  • 3
  • 28
  • 28

1 Answers1

0

First of all I explain why you code don't work like you expect.

The method $.get works asynchronous. So

  • your function beforeSubmit first start $.get
  • then it returns undefined value bacause the body of the beforeSubmit function will be finished.
  • Then after the asynchronous $.get request will get response from the server the function(data) { callback will be called (it's success callback).
  • Your success callback return the value return[false,"Exists"]; from the callback. The $.get don't analyse any return value from the success callback so the array [false,"Exists"] will be discarded by $.get.

You can use $.ajax with async: false parameter instead of $.get as the workaround, but better is don't implement any beforeSubmit at all. If your server-based code find out that the user changes can't be saved or the input field contains some validation errors the server should just return response having some error HTTP status code. The status code can be 400 or higher in case of validation errors - the Client Error or be 500 or higher in case of some other errors in processing the request on the server - Server Error. The body of the server response can be HTML fragment of the message which jqGrid will display to the user.

You can customize the error message with respect of errorTextFormat callback. See here and here for additional information.

Community
  • 1
  • 1
Oleg
  • 220,925
  • 34
  • 403
  • 798