jQuery validator additional method not working as expected - javascript

I am using this jQuery validation plugin, http://jqueryvalidation.org/ And I am creating an addition method, as shown here.
jQuery.validator.addMethod('exists', function(value, element) {
$.ajax({
data: {username: value},
type: 'POST',
url: 'action/check/',
dataType: 'json',
success: function(data) {
if (data==true) {
console.log(data);
return true;
}
if (data==false) {
console.log(data);
return false;
}
}
})
}, 'This username is already in use');
My console is getting the proper data back from the check script and in my console I can see true and false etc. But what I do not understand is the validation flag seems to flag the input regardless of what the input is.
rules: {
password_confirm: {
equalTo: 'input[name=password]'
},
username: {
exists: true
}
}
I already have username chris in my database, so when I type chris into the username input I should get a flag for being a duplicate user, but regardless of what type I get the validation flag.
What am I missing

Your validation won't work because it is asynchronous(ajax request).
You can use the existing remote rule to do that, make sure your request is returning true/false as its result
rules: {
password_confirm: {
equalTo: 'input[name=password]'
},
username: {
remote: {
url: 'action/check/',
type: 'POST'
}
}
}

jQuery.validator.addMethod('exists', function(value, element) {
var result = false;
$.ajax({
data: {username: value},
type: 'POST',
url: 'action/check/',
dataType: 'json',
success: function(data) {
result = data; // make sure data returns bool value
}
});
return result;
}, 'This username is already in use');

Related

jQuery ajax parameters not being passed to php as expected

I have the following javaScript code:
const getReport = {
jobID: $('#jobID').val(),
startDate: $('#summaryStart').val(),
endDate: $('#summaryEnd').val(),
tableType: 'Summary',
};
$.ajax({
url: "php/reports.php",
contentType: "application/json",
type: "post",
dataType: "application/json",
data: function (d) {
return JSON.stringify(getReport);
},
success: function (response) {
if (response["tableColumns"].substring(0, 4) === "<h4>") { //if html returned here no detail query
} else {
$('#summaryTable').DataTable({
select: {
sytle: 'single',
items: 'row'
},
data: response["tableData"], columns: response["tableData"],
dataSrc: ""
});
}
}
});
And in my php code I have the following (to test values coming accross):
$rawJson = file_get_contents("php://input");
echo $rawJson;
return;
$parms = json_decode($rawJson, true);
$jobId = $parms["jobID"];
The code as stated above the XLR value from Chrome's developer tools is blank. If I run with this code instead:
$rawJson = file_get_contents("php://input");
// echo $rawJson;
//return;
$parms = json_decode($rawJson, true);
$jobId = $parms["jobID"];
I get:
Warning: Trying to access array offset on value of type null at the statement: $jobId = $parms["jobID"];
Note: when I get the warning message, javascript executes my success: routine, but the response appears to be null or blank.
I do a similar thing with fetch in another part of the app and it works. I could probably switch to that method, but would like to know why my jQuery call does not work.
The data option can't be a function. So this:
data: function (d) {
return JSON.stringify(getReport);
},
should be:
data: JSON.stringify(getReport),
The data parameter of $.ajax does not take a function it takes a PlainObject or String or Array. Also dataType for JSON is json not the json content type application/json.
const getReport = {
jobID: $('#jobID').val(),
startDate: $('#summaryStart').val(),
endDate: $('#summaryEnd').val(),
tableType: 'Summary'};
$.ajax({
url: "php/reports.php",
contentType: "application/json",
type: "post",
dataType: "json",
data: JSON.stringify(getReport),
success: function (response) {
if (response["tableColumns"].substring(0, 4) === "<h4>") { //if html returned here no detail query
} else {
$('#summaryTable').DataTable({
select: {
sytle: 'single',
items: 'row'
},
data: response["tableData"], columns: response["tableData"],
dataSrc: ""
});
}
}
});

How to prevent ajax from auto quoting boolean and numbers

So what happens is that jQuery will turn something like false and 1 into "false" and "1", which kind of breaks my server code. I can kind of overcome this by using JSON.stringify but then I need to JSON.parse on the server end. Is there anyway for jQuery to not quote booleans, numbers and anything else that normally doesn't need escaping?
let test = {
truthy: false
}
let test2 = {
truthy: false
}
$.ajax({
url: "https://reqres.in/api/users",
type: "POST",
data: {
another: test
},
success: function(response){
console.log(response);
}
});
$.ajax({
url: "https://reqres.in/api/users",
type: "POST",
data: {
another: JSON.stringify(test2)
},
success: function(response){
console.log(response);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JQuery Validation not posting data to backend

I have something weird going on that I am trying to work out. I have a simple submitHandle that passes one bit of data to my PHP file
submitHandler: function (form) {
$.ajax({
type: "POST",
url: "form-process.php",
data: {
'customer': $("input[name='customer']:checked").val()
}
}).done(function (response) {
console.log(response)
}).fail(function (jqXHR, textStatus) {
console.log(textStatus)
});
return false;
}
If I output $("input[name='customer']:checked").val() I get the expected value of yes or no. Now in my PHP file, I am simply doing
echo json_encode($_POST["customer"]);
This seems to produce the error
Undefined index: customer
If I just check $_POST it returns an empty array.
Am I missing something here? Is there a reason this data isn't making it to the backend?
Try this method :
$.ajax({
method: "POST",
url: "form-process.php",
data: { customer: $("input[name='customer']:checked").val() }
}).done(function(response) {
console.log( "Data Saved: " + response);
}).error(function(error){
console.log(error)
});
You should use $("input[name='customer']:checked") ? true : false because if the input is not checked $("input[name='customer']:checked") will return null and then you will have null.val() which is not correct
data: {
customer: $("input[name='customer']:checked") ? true : false
}

Very elementary jquery + ajax

On the click of a button, I want to capture a form's data and send it to a php page using ajax, json. Now, the alert "hello hello" comes on the click of a button ONLY WHEN I HAVE COMMENTED OUT MY AJAX PORTION.
When i include the ajax portion by un-commenting it, not only do i not get any errors but also my "hello hello" alert doesnt show up.
I find this odd. Why does it happen so?
Here is my ajax:
<script>
$(document).ready(function () {
$("#btn").click( function() {
alert('hello hello');
/* Coomenting starts here
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
}
datatype: "json",
success: function (status)
{
if (status.success == false)
{
alert("Failure!");
}
else
{
alert("Success!");
}
}
});
*/
//commenting ends here.
//basically i just commented out the ajax portion
});
});
</script>
You are missing a comma after "data":
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
}, // Missing comma!
datatype: "json",
success: function (status)
{
if (status.success == false)
{
alert("Failure!");
}
else
{
alert("Success!");
}
}
});
As #dystroy pointed out, since your code can't compile, this malformed block will potentially prevent other code (such as a simple alert) from firing.
Check comma syntax after data parameter:
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
},
You are missing a comma after the data part:
<script>
$(document).ready(function () {
$("#btn").click( function() {
alert('hello hello');
/* Coomenting starts here
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
},
datatype: "json",
success: function (status)
{
if (status.success == false)
{
alert("Failure!");
}
else
{
alert("Success!");
}
}
});
*/
//commenting ends here.
//basically i just commented out the ajax portion
});
});
</script>

jQuery Validate Triggering message from success

I'm trying to figure out once the callback to the remote function is made for either the username or email address, that if the data returned is equal to "n" it should trigger the message to be displayed.
JS:
$(document).ready(function() {
var validator = $("form").validate({
rules: {
username: {
minlength: 6,
maxlength: 12,
remote: {
type: 'post',
url: 'register/is_username_available',
data: {
'username': function() {
return $('#username').val();
}
},
dataType: 'json',
success: function(data) {
alert(data);
if (data == 'y') {
alert('available');
}
else {
alert('no available');
}
}
}
},
email_address: {
email: true,
remote: {
type: 'post',
url: 'register/is_email_available',
data: {
'email_address': function() {
return $("#email_address").val();
}
},
dataType: 'json',
success: function(data) {
alert(data);
if (data == 'y') {
alert('available');
}
else {
alert('no available');
}
}
}
}
},
messages: {
username: {
remote: 'The username is already in use'
},
email_address: {
remote: 'There is already an account set up that uses that email address!'
}
}
});
});​
Your "dataType" is incorrect.. right now your telling it to get and use JSON, you on the other hand are outputting or expecting a string or "text"/"html" rather than "json"
change your dataType to html or text, and see how that does ya.
if you wanted to keep it at json.. your output from the php side would have to be
{"response":"y"}
and your javascript in the sucess would have to be like
if(data.response == "y")

Categories