JQuery Submit not called with remote verification [duplicate] - php

I want to validate if username exists in database using jQuery.validate so here's what I have so far:
jQuery:
$("#signupForm").validate({
rules: {
username: {
required: true,
minlength: 3,
remote: "check-username.php"
}
},
messages: {
username:{
remote: "This username is already taken! Try another."
}
}
});
check-username.php:
<?php
require_once "./source/includes/data.php";
header('Content-type: application/json');
$name = mysql_real_escape_string($_POST['username']);
$check_for_username = mysql_query("SELECT username FROM mmh_user_info WHERE username='$name'");
if (mysql_num_rows($check_for_username) > 0) {
$output = true;
} else {
$output = false;
}
echo json_encode($output);
?>
This code always shows an error that the username is taken even if it's not.
I'm using jQuery Mobile 1.9.1
Thanks in advance.

I've managed to get this to work by changing the PHP technique I was using, here's my PHP:
<?php
require_once "./source/includes/data.php";
header('Content-type: application/json');
$request = $_REQUEST['username'];
$query = mysql_query("SELECT * FROM mmh_user_info WHERE username ='$username'");
$result = mysql_num_rows($query);
if ($result == 0){
$valid = 'true';}
else{
$valid = 'false';
}
echo $valid;
?>
Thanks everyone here for your help :)

I have two resources for to look at.
Official example from the validate plugin:
http://jquery.bassistance.de/validate/demo/milk/
jQuery forum solution:
http://forum.jquery.com/topic/jquery-validation-plugin-remote-validation-problem-locks-up
The possible solution is that the response does not need to be json encoded as far as I can tell. Since json needs key value pairs, suppling just the value won't work. So try to just echo it out as 'true' or 'false' strings.
Second, the validate uses GET for the form submission method, not POST.
NOTE: JUST FOUND POSSIBLE SOLUTION QUESTION
jQuery Remote validation

Related

Data cannot insert to database when no more error is detect

Here is my code
Whether is my if-else statement got problem or insert there got any problem
if(isset($_POST["Add"]))
{
$name = $_POST["username"];
$pass = $_POST["password"];
$fname = $_POST["fname"];
$lname = $_POST["lname"];
$hph = $_POST["home"];
$hp = $_POST["hp"];
$mail = $_POST["email"];
$add = $_POST["address"];
$age = $_POST["age"];
$pos = $_POST["position"];
$dept = $_POST["dept"];
$result i use it to check out my username
$result=mysql_query("select*from employee where Emp_Username='$name'");
if($name==""||$pass==""||$fname==""||$lname==""||$hph==""||$hp==""||$mail==""||$add==""||$age==""||$pos==""||$dept=="")
{
?>
<script type="text/javascript">
alert("Please fill in all the required informations.");
</script>
<?php
}
elseif(empty($errors)===true)
{
if (!preg_match("/^[A-Z][a-zA-Z -]+$/i",$_POST['fname']))
{
$fnameErr= 'Invalid key has been input*';
}
if (!preg_match("/^[A-Z][a-zA-Z -]+$/i",$_POST['lname']) )
{
$lnameErr= 'Invalid key has been input*';
}
if (filter_var($mail, FILTER_VALIDATE_EMAIL) === false)
{
$mailErr = 'A valid email address is required*';
}
if (!preg_match('/^[0-9]{1,}/', $_POST['age']))
{
$ageErr = 'Only can be numeric*';
}
if (!preg_match("/^[a-zA-Z0-9 _.,:\"\']+$/i", $_POST['address']))
{
$addErr = 'Address must be letters and numbers*';
}
if (!preg_match("/^[0-9]{2,2}[-][0-9]{7,7}$/", $_POST['home']))
{
$hphErr= 'Phone must comply with this mask: 04-4XX1234*';
}
if (!preg_match("/^[0-9]{3,3}[-][0-9]{7,7}$/", $_POST['hp']))
{
$hpErr= 'Phone must comply with this mask: 014-XXX1234*';
}
if(strlen($name)<4)
{
$nameErr = 'Your username must between 4 to 12 characters*';
}
if (strlen($pass) < 6)
{
$passErr = 'Your password must be at least 6 characters*';
}
}
elseif(mysql_num_rows($result)==0)
if $result==0 so my data will insert to the employee table, but it can't work
{
mysql_query("insert into employee(Dept_ID, Emp_Address, Emp_Age, Position, Emp_Username, Emp_Password, Emp_Fname, Emp_Lname, ContactNo_Home, ContactNo_HP, Emp_Email)
values('$dept','$add','$age','$pos','$name','$pass','$fname','$lname','$hph','$hp','$mail')");
?>
<script type="text/javascript">
alert('Registered successfully!');
</script>
<?php
}
else
{
?>
<script type="text/javascript">
alert("Username already in use!");
</script>
<?php
}
}
Hopefully someone can help me find out the problem and solve it.
Thank you!
Not knowing your exact schema, or the errors MySQL is responding with, it is hard to say exactly what the problem is here. Debugging (breakpoints, stepping over, etc.) will help you determine if what you expect is happening is actually happening.
As JohnnyJS mentioned, it looks like you never opened a connection to MySQL (although as ComFreek mentioned these mysql_* functions are deprecated).
It is advised that you use a DBAL or ORM to interact with your database. There are many. At least checkout Doctrine.
Debug your code. This can be easily done with xdebug in an editor like PHPStorm. It is possible you are never even executing the insert query.
Execute your queries outside of your application to see if they are working as expected.
You are vulnerable to SQL injection, you need to quote your user provided values.
If you used a framework, you wouldn't even need to interact with $_POST directly. Check out Symfony -- it is an excellent PHP framework
Also, I would not recommend returning script tags with alerts the way you have here. It is much better to update the form with the corresponding errors inline -- which if you used Symfony would be done for you.
Hope this helps. Good luck!

jQuery plugin Validation email check if else CRAZY WIERD

I have successfully implemented the Jquery Validation Plugin http://posabsolute.github.com/jQuery-Validation-Engine/ but i am now trying to get an ajax database email check to work (email exists / email available) and i have written some php script to get this done. Its kinda working but i am getting the most unexpected heretically odd behavior from my IF ELSE statement (seems really crazy to me). observe ### marked comments
PHP code: LOOK AT THE IF ELSE STATEMENT
/* RECEIVE VALUE */
$validateValue = $_REQUEST['fieldValue'];
$validateId = $_REQUEST['fieldId'];
$validateError = "This username is already taken";
$validateSuccess = "This username is available";
/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results = array($row['Email']);
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR ### popup shows "validating, please wait" then "This username is already taken" when email typed is in database - i.e. Working
file_put_contents('output.txt', print_r("1 in array - Email is Taken " . $validateValue, true)); ### this runs!!
}else{
$arrayToJs[1] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success ### popup shows "validating, please wait" when email typed is NOT in the database - i.e. not Working
file_put_contents('output.txt', print_r("2 else - Email is available " . $validateValue, true));
//### THIS RUNS TOO !!!!!!!!!!!!! i.e. echo json_encode($arrayToJs) wont work for both.. If I change (in_array()) to (!in_array()) i get the reverse when email is in database.
//i.e. only the else statements echo json_encode($arrayToJs) runs and the popup msg shows up green "This username is available" crazy right???
//so basically IF ELSE statements run as expected (confirmed by output.txt) but only one echo json_encode($arrayToJs) will work.!!!!
//If i remove the json_encode($arrayToJs) statements and place it once after the IF ELSE statement i get the same problem.
//both $arrayToJs[1] = false; and $arrayToJs[1] = true; can work separately depending on which is first run IF or ELSE but they will not work in the one after another;
}
HERE IS THE REST OF THE CODE-->
1-HTML FORM INPUT CODE:
<tr>
<td> <Label>Business Email</Label>
<br>
<input type="text" name="Email" id="Email" class="validate[required,custom[email],ajax[ajaxUserCallPhp]] text-input">
</td>
</tr>
2-Relevant JQUERY code in jquery.validationEngine.js:
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
3-Relevent code for ajaxUserCallPhp in jquery.validationEngine-en.js:
"ajaxUserCallPhp": {
"url": "validation/php/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "*Validating, please wait"
},
Im sure the problem lies with this echo.
echo json_encode($arrayToJs)
Please help i've spent to long on this and its almost working fully.
To clarify - I basically am trying to code it so that if i type an email in the db it shows red "This username is taken" then if i edit the input box to an email not in the database it changes to green "username is available" at the moment only one json_encode will run in any scenario no matter how i change the if else statement –
Thank you very much in advance.
Ok got it finally after a fiddle. I found that json_encode() returns false when any error or warning is posted. using the php error log file in xampp/php/logs/error_logs file i realised that i was getting an error only when the query result was null making $results = null. this caused an output error preventing json_encode() from echoing true, which is why i only got one response.
To fix it i made sure that the $result array was not empty by using the following code after the query to array part.
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
The whole code is now
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = $row['Email'];
}
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = 0;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
} else {
$arrayToJs[1] = 1; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
}
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})

quoted javascript and JSON to PHP

this javascript:
"jform[username]": {
required: true,
minlength:5,
maxlength:15,
remote: "modules/mod_easiness_register/libs/elements/db_checker.php"
},
has to pass it's value to this PHP script:
if (isset($_REQUEST['jform[username]'])) {
$username = $_REQUEST['jform[username]'];
$username = $mysqli->real_escape_string($username);
$check_for_username = $mysqli->query("SELECT username FROM $users WHERE username='$username'");
if (mysqli_num_rows($check_for_username)) {
echo "false";
} else {
echo "true";
}
}
the ""(quotes) around "jform[username]" are the trouble makers, but I have to use those quotes to make the brackets[] work (and I need those brackets as well). I think JSON can't handle this. Do you know a way around this? I hope you understand the problem. Your help is much appreciated.
I think in your PHP script you should check for $_REQUEST['jform']['username'], and this will solve your problem.

Jquery Validation Remote Check Unique Not Working

I wanted to post this online because I have been searching for days on this JQuery Remote validation issue. I cannot get it to work. I think my PHP code is correct as I have test the URL with a query in the URL and it returns false and true depending on with the recordset count is one or more
This is my Jquery Validate Code:
// validate form and submit
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#myform").validate({
rules: {
ord_ref: {
required: true,
minlength: 12,
remote: "check_ord_ref.php"
},
messages: {
ord_ref: {
remote: "Order Number Does Not Exist"
}
}
}
});
});
This is my PHP code for the remote page "check_ord_ref.php"
$colname_rscheck_ord_ref = "-1";
if (isset($_GET['ord_ref'])) {
$colname_rscheck_ord_ref = (get_magic_quotes_gpc()) ? $_GET['ord_ref'] : addslashes($_GET['ord_ref']);
}
mysql_select_db($database_conn, $conn);
$query_rscheck_ord_ref = sprintf("SELECT ref_ord FROM orders WHERE ref_ord = '%s'", $colname_rscheck_ord_ref);
$rscheck_ord_ref = mysql_query($query_rscheck_ord_ref, $conn) or die(mysql_error());
$row_rscheck_ord_ref = mysql_fetch_assoc($rscheck_ord_ref);
$totalRows_rscheck_ord_ref = mysql_num_rows($rscheck_ord_ref);
if($totalRows_rscheck_ord_ref < 0){
$valid = 'false';
} else {
$valid = 'true';
}
echo $valid;
Please someone can you help solve the puzzle for myself and anyone else having issues
Using JQuery 1.5.2min
Validates OK without remote function
Ok, so I'm no PHP expert, but I do know that jQuery Validate expects the following result from a remote validation method:
The response is evaluated as JSON and must be true for valid elements,
and can be any false, undefined or null for invalid elements
Sending down "true" or "false" (note the quotation marks) is going to result in the value being parsed as the error message instead of being evaluated as a boolean primitive.
Back to the PHP part, I think you should probably use json_encode with a boolean primitive. I'm not quite sure the way to do this in PHP, but I believe it would be something like this:
$colname_rscheck_ord_ref = "-1";
if (isset($_GET['ord_ref'])) {
$colname_rscheck_ord_ref = (get_magic_quotes_gpc()) ? $_GET['ord_ref'] : addslashes($_GET['ord_ref']);
}
mysql_select_db($database_conn, $conn);
$query_rscheck_ord_ref = sprintf("SELECT ref_ord FROM orders WHERE ref_ord = '%s'", $colname_rscheck_ord_ref);
$rscheck_ord_ref = mysql_query($query_rscheck_ord_ref, $conn) or die(mysql_error());
$row_rscheck_ord_ref = mysql_fetch_assoc($rscheck_ord_ref);
$totalRows_rscheck_ord_ref = mysql_num_rows($rscheck_ord_ref);
if($totalRows_rscheck_ord_ref < 0){
$valid = false; // <-- Note the use of a boolean primitive.
} else {
$valid = true;
}
echo json_encode($valid);
This problem seems to be plaguing remote validation scripters and the jQuery documentation on the matter is clearly lacking.
I notice you are using jQuery 1.5.2: from what I understand (and found from experience) you must use the jQuery callback that is sent to the remote script with $_REQUEST with versions after 1.4, AND jQuery is expecting "true" or "false" as a STRING. Here is an example, confirmed working on multiple forms (I'm using jQuery 1.7.1):
if($totalRows_rscheck_ord_ref < 0){
header('Content-type: application/json');
$valid = 'false'; // <---yes, Validate is expecting a string
$result = $_REQUEST['callback'].'('.$check.')';
echo $result;
} else {
header('Content-type: application/json');
$valid = 'true'; // <---yes, Validate is expecting a string
$result = $_REQUEST['callback'].'('.$check.')';
echo $result;
}
I found this answer here (in the answers section), randomly, and have since stopped pulling out my hair. Hope this helps someone.
To add to Andrew Whitaker's response above, I must stress that you are sure that the response is strictly JSON and that there are no other content types being returned. I was having the same issue with my script, and everything appeared to be set properly - including using json_encode(). After some troubleshooting with Firebug's NET tab, I was able to determine that PHP notices were being sent back to the browser converting the data from JSON to text/html. After I turned the errors off, all was well.
//check_validate.php
<?php
// some logic here
echo json_encode(true);
?>

how to get something back from a php file using jQuery?

i am sending some value to a php file like this:
$.post('php/xxx.php', { username: userName } );
and the php file echo'es out a var $test
how can i get it back into the js?
i was thinking to use this:
var get_back = $.get('php/xxx.php', ... );
but i am not sure how...
thanks
edit:
here is my php file:
include("connect.php");
$get_username = $_POST['username'];
$username = '';
$username = mysql_real_escape_string($get_username);
echo $get_username;
$result = mysql_fetch_assoc(mysql_query("SELECT username FROM database WHERE username='$username' LIMIT 1"));
if($result !== FALSE) {
echo $username;
}
i want to get back this echo $username; value
The various ajax functions in jQuery (ajax, post, get) accept callback functions where you can handle the returned data:
//define username outside so that
//it's available outside of the scope
//of the callback function
var username;
$.post('php/xxx.php',
{ username: userName },
function(data){
//per the comment below,
//assuming data will simply
//be the username
username = data;
});

Categories