0

I am trying to create a custom method calling AJAX but it seems it is not working. The server is giving me back values 1 if the username already exists and 0 if it doesnt. The method is always showing me the error message even if the username is available.

$.validator.addMethod("checkUserName", function(value, element) {
  var isAvailable;
  $.ajax({
    type: "GET",
    url: "http://hostname.com/checkUsername",
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    cache: false,
    data: {
      new_username: function() {
        return $("#username").val();
      }
    },
    success: function(data) {
      if (data != 0) {
        isAvailable = false;
      } else {
        isAvailable = true;
      }
    }
  });
  return isAvailable;
}, "Username already exists!");
Sparky
  • 98,165
  • 25
  • 199
  • 285
James
  • 1
  • Why reinvent the wheel? Simply use the `remote` method to check the server for a username in use. – Sparky Oct 02 '15 at 18:09
  • Still not working, always giving me the error message – James Oct 02 '15 at 18:22
  • Follow the code in the linked answer. Since I cannot see how you're implementing `remote`, I would have no idea how/where you're messing it up. Is the server script PHP? Then you need to `echo` `"true"`, `"false"` or a string using `json_encode()`. Only `echo "true"` or `echo json_encode("true")` will pass validation. – Sparky Oct 02 '15 at 18:35
  • That worked perfectly, thank you. :) – James Oct 02 '15 at 18:48

0 Answers0