I am using the validation plugin and Laravel 4.2.
I try to check the username via ajax, but I can't get it work.
The username can always be taken, doesn't matter if exists or not.
My second issue is if I am using the validation rule remote, I can't submit the form.
Does anybody know what I am doing wrong? Because in the chrome log all is fine, the request is sent and I can see the debug messages.
Php
<?php
use App\Models\User;
class ValidationController extends BaseController {
public function getCheckUsername()
{
if(Request::ajax()) {
$user = User::where('username', Input::get('username'))->get();
if($user->count()) {
return Response::json(array('msg' => 'true'));
}
return Response::json(array('msg' => 'false'));
}
}
}
JS
$(document).ready(function()
{
$("form").validate({
rules: {
username: {
required: true,
rangelength:[3,255],
remote: {
url:"http://"+location.host+"/validation/checkusername",
type: "get",
success: function(msg){
if(msg.msg == 'true') {
console.log('exists');
return true;
}
console.log('doesnt exists');
return false;
}
},
},
messages: {
username: {
required: "Please Enter Username!",
remote: "Username already in use!"
}
}
});
});
I also tried to create an own rule via $.validator.addMethod(), but this doens't work either.
It doesn't look like you are sending the data. Try this. Note the post request. Also I believe the dataFilter method should return 'true'.
Update I just also realized the logic in your php is sending back true if the user exists, therefore the logic in the javascript should be like so:
remote: {
url: "http://"+location.host+"/validation/checkusername",
type: "post",
data: {
username: function () {
return $("input[name='username']").val();
}
},
dataFilter: function (data) {
var json = JSON.parse(data);
if (json.msg == "true") {
return "\"" + "That username is taken" + "\"";
} else {
return 'true';
}
}
}
Related
I'm using the jQuery Validator plugin to try to check whether an email address getting entered into the form is unique after an ajax call which passes the email to a script which checks to see if the email is already in the database. I'm using a callback function to try to get the results of the ajax query but the function always returns undefined. I'm not sure what I'm doing wrong. Here is the code:
jQuery.validator.addMethod("unique", function () {
function foo(callback) {
$.ajax({
type: 'POST',
async: true,
url: '/form_processor',
data: 'action=email_validate&email=' + $("#email").val(),
success: callback
});
}
var return_value = foo(function (result) {
if (result !== 'g') {
return false;
} else {
return true;
}
});
alert(return_value);
}, "Email address taken. Choose another.");
If you are using jquery validator, in built method is their to validate, So your validate code will like,
$(document).ready(function(){
$( "#myform" ).validate({
rules: {
email: {
required: true,
email: true,
remote: {
url: "form_processor",
type: "post",
data: {
email: function() {
return $( "#email" ).val();
}
}
}
}
},
messages:
{
email:
{
required: "Please enter your email address.",
remote: "Email already taken"
}
}
});
})
In server side you have to return (print) true or false code will be (if you are using php)
<?php
$email = $_POST['email'];
$query = "SELECT ID FROM users WHERE user_email = "$email" LIMIT 1;";
$results = $mysqli->query($query);
if($results->num_rows == 0)
{
echo "true"; //good to register
}
else
{
echo "false"; //already registered
}
}
else
{
echo "false"; //invalid post var
}
?>
I am running an ajax request, then once I get the result back I choose if it should be continued or if the form should not submit. I am checking if the email exists.
Issue is I moved the return false out of the success: as it was not working there and now in a seperate function it is not working either. I get the alert("FALSE"); but the form still submits which is no good as I want an error pop up to happen.
$.ajax({
type: "POST",
url: "/ajax/checkdata.php",
data: "email="+email,
success: function(data){
var returned = true;
if (data == "Email Exists") {
returned = false;
} else {
}
emailModal(returned);
}
})
function emailModal(result){
if (result) {
alert("TRUE");
} else {
alert("FALSE");
return false;
}
}
You'd have to always prevent the form from submitting, and then in the check for the email figure out wether to show an error or submit the form using the native submit handler
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/ajax/checkdata.php",
data: {email : email},
context: this
}).done(function(data) {
if (data == "Email Exists") {
alert(data);
} else {
this.submit();
}
});
});
this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?
I tried build custom validator for jsgrid that check the item.Name is really exist from DB or not before inserting or Editing to avoid any duplicated row.
the problem I read three times the Documents of jsgrid but I didn't get any idea how to fix the problem.
this work https://github.com/tabalinas/jsgrid-php helped me too much and I transformed to be useful for my work and to mysqli.
the idea:
I made function check DB if the value exist or not, if exist it return true else false in a php class
public function checkName($name){
try{
if(!empty($name)){
$co_conn = $this->CON_conn->open_connect();
$getsame = mysqli_query($co_conn,"select Name from category where Name = '$name'");
if($getsame){
$numit = mysqli_num_rows($getsame);
if($numit > 0) return true;
else return false;
}
else return true;
$this->CON_conn->close_connect($co_conn);
}
else return true;
}
catch(Exception $er){
return true;
}
}
and I called this function in an external file "CheckValue.php"
<?php require_once '////the director of the class';
$chnow = new NameOfMyClass();
$result = true;
switch($_SERVER["REQUEST_METHOD"]) {
case "CHGO":
parse_str(file_get_contents("php://input"), $_CHGO);
//to ensure if it work i tested it.
$result = $chnow->checkName($_CHGO["Name"]);
break;
default:
$result = true;
break;
}
header('Content-type: application/json');
echo json_encode($result);
?>
in basic.html
$(function() {
$.ajax({
type: "GET",
url: "../bin/update.php"
}).done(function(response) {
response.unshift({ ID: "0", Name: "" });
$("#jsGrid").jsGrid({
height: "50%",
width: "70%",
selecting: false,
filtering: false,
editing: false,
sorting: false,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(filter) {
return $.ajax({type:"GET", url: "../bin/update.php",data:filter});
},
updateItem: function(item) {
return $.ajax({type:"PUT",url: "../bin/update.php",data: item});
},
insertItem: function(item) {
/*$.ajax({type: "CHGO",url: "..bin/Checkvalue.php",data:item.Name, dataType: "json",
success: function(data){
JSON.parse(data);
consol.log(data);
//alert(data);
//I used many ways to find why its not work, then I commented it
}
});
//return $.ajax({type: "POST",url: "../bin/update.php",data: item});
//return data;
//else sweetAlert("error", "this value is exist!", "error");
//here I thought merge sweetalert js will give a good look of work not the normal message.
*/
}
},
fields: [
{ name: "ID", type: "number",width: 50, editing:false, inserting:false },
{ name: "Name", type: "text", width: 50, validate: ["required",{
message: "this value is exist",
validator: function(value,item){
if(value != "")
{
$.ajax({
type: "CHGO",
url: "..bin/Checkvalue.php",
data: item.Name,
success: function(data){
if(data == true)
//I assume here return the true/false to activate the error message but nothing work..sorry
}
});
}
}
} ]
},
{ type: "control", modeSwitchButton: false, deleteButton: false }
]
});
});
$(".config-panel input[type=checkbox]").on("click", function() {
var $cb = $(this);
$("#jsGrid").jsGrid("option", $cb.attr("id"), $cb.is(":checked"));
});
});
please help, I 'm try for 2 days to fix the problem.
thanks for the developers for writing the validate js file
I used jsgrid-1.4.1
The reason is that validate supports only synchronous validation, and validation from our example requires ajax call, so it's asynchronous.
You have two options:
Load data to the client beforehand and validate inserting item on the client (so validation will be synchronous)
Validate insertion in insertItem method. Checkout the following issue to know more details https://github.com/tabalinas/jsgrid/issues/190
This is using jQuery 1.6.1 and Validate 1.8.1.
I have been banging my head against a wall because of this problem, and now I'm trying the other approach to try and solve this problem. I need to query the database for existing usernames so that someone signing up doesn't register the same one again.
HTML:
<form class="cmxform" action="register.php" method="post" name="signup" id="signup">
<ul>
<li>
<label for="username">Username: <em>*</em></label>
<input type="text" id="username" name="Username" size="20" class="required" placeholder="Username" />
</li>
</ul>
</form>
This time, I'm trying to use the remote function for the validate script:
$("#signup").validate( {
var username = $("#username").val();
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
},
},
submitHandler: function(form) {
form.submit();
}
});
The code in question that doesn't work is var username = = $("#uname").val();. Firebug gives the error missing : after property id.
I'm including the mentioned variable above inside validate() because I only want the value of the input after I've typed something into it, not upon loading of the page.
The other problem I've been running into is making the remote error message ONLY show up when a username already exists in the database. Unfortunately, it shows up whether dbquery.php comes back as true or false. If I try an existing username, it returns false, then I rewrite a new username that returns true, the message doesn't go away. Similarly, when I write a username and it returns true, I still get the remote error message.
What am I doing wrong?
As you can read How can I force jQuery Validate to check for duplicate username in database?
The solution is to use the remote property:
Example with remote:
$("#signup").validate( {
rules: {
username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "get",
data: {
action: function () {
return "checkusername";
},
username: function() {
var username = $("#username").val();
return username;
}
}
}
}
},
messages: {
username: {
required: "Enter a username"
}
},
submitHandler: function(form) {
form.submit();
}
});
To set a custom error message your PHP file must return the message instead of false, so echo "Sorry, this user name is not available" in your PHP file.
var username = $("#uname").val();
instead of
var username = = $("#uname").val();
You can't have = =, it's a syntax error.
Also, make sure you properly 'escape' $("#username").val().
If someone enters: myname&action=dosomethingelse I'd give it a fair change it will dosomethingelse.
New answer:
$("#signup").validate( {
var username = $("#username").val(); // -- this is wrong
rules: {
Username: {
required: true,
...
});
You can fix this the easy way by just not declaring the variable at all since you're only using it is one place, but that's no fun :D
The solution is a closure:
$("#signup").validate( (function () {
var username = $("#username").val();
return {
rules: {
Username: {
required: true,
minlength: 5,
remote: {
url: "dbquery.php",
type: "GET",
async: false,
data: "action=checkusername&username="+username,
success: function (output) {
return output;
}
}
}
},
messages: {
Username: {
required: "Enter a username",
remote: jQuery.format("Sorry, {0} is not available")
}
},
submitHandler: function(form) {
form.submit();
}
};
}()));
(I haven't tested it, there may be a typo or syntax error).
If you have no idea what this does or why, don't worry about it :D