I read all the documentation of the Parsley Js web site. But i not get enough understand how to set custom validation depend on AJAX response.
I need to validate a username and check if it is already exist in the database if it is yes and show the error when hit the submit button.
I look around here and try to find any question regarding to this i could not fine that only i got how ajax code should place to validate that forms. I need to know how the PHP file look likes. That why i post that question
I am using parsley js new version. Here is my code look like
<form class="forms-sample" id="form">
<div class="form-group">
<label for="exampleInputUsername1">Username</label>
<input type="text" class="form-control" id="exampleInputUsername1"
name="username" placeholder="Username" required data-parsley-username>
</div>
<button type="submit" class="btn btn-success mr-2">Submit</button>
<button class="btn btn-light">Cancel</button>
</form>
and i am using Bootstrap 4 for CSS. My Parsley js script like this
<script>
window.ParsleyValidator
.addValidator('username', function (value, requirement) {
var response = false;
$.ajax({
url: "username.php",
data: {username: value},
dataType: 'json',
type: 'post',
async: false,
success: function(data) {
response = true;
},
error: function() {
response = false;
}
});
return response;
}, 32)
.addMessage('en', 'username', 'The username already exists.');
$("#form").parsley({
errorClass: 'is-invalid',
successClass: 'is-valid',
errorsWrapper: '<span class="invalid-feedback"></span>',
errorTemplate: '<span></span>',
trigger: 'change'
});
</script>
I cannot imaging how i create PHP file to write query and what i want to echo from that PHP.
Could you please tell me anything need to be change here and can you guide me to build that PHP file to complete this task. And i need to know this JS will work or not. Thank you.
After i added a php file. that is something like this
<?php
include("include/connection.php");
?>
<?php
if(isset($_POST['username'])){
$username = $_POST['username'];
$query = "SELECT * FROM user WHERE userName = '%$username'";
$q = mysqli_query($conn, $query);
if(mysqli_num_rows($q) > 0) {
echo json_encode("error");
}else {
echo json_encode("success");
}
}
?>
but i got default error message for every time that was "The username already exists." Can anybody know what is the error in here?