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.
Related
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
I have a problem with the understanding of variable scopes.
I've got a huge .php file with many $_POST validations (I know that isn't not good practise). Anyways I want a little html-part above all the code which outputs an error message. This message I want to change in every $_POST validation function.
Example:
if($ERR) {
echo '<div class="error-message">'.$ERR.'</div>';
}
Now my functions are following in the same file.
if(isset($_POST['test']) {
$ERR = 'Error!';
}
if(isset($_POST['test2'] {
$ERR = 'Error 2!';
}
But that doesn't work. I think there's a huge missunderstanding and i'm ashamed.
Can you help me?
I didnt catch your question but maybe this is your answer:
<body>
<p id="error_message">
<?php if(isset($ERR)){echo $ERR;} ?>
</p>
</body>
and I suggest you to learn how to work with sessions.
and you should know that $_Post will be empty on each refresh or F5
You can do put the errors in array make them dynamic.
<?php
$error = array();
if (!isset($_POST["test"]) || empty($_POST["test"])) {
$error['test'] = "test Field is required";
} else if (!isset($_POST["test1"]) || empty($_POST["test1"])) {
$error['test1'] = "test Field is required";
}else{
//do something else
}
?>
You can also use switch statement instead of elseif which is neater.
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!
I've been to almost every forum possible with this question (including this one). I almost got the answer to my question. The problem is no one seems to figure out my problem because everything looks right, and everything looks right to me too. Can someone please help me? Here are my codes.
Flash Code:
var lvSend:LoadVars = new LoadVars();
var lvReceive:LoadVars = new LoadVars();
register_button.onRelease = function(){
var valid:Boolean = validateForm();
if (valid) {
//gather information and put in loadvars object
lvSend.username = username1.text;
lvSend.password = password1.text;
lvSend.email = email1.text;
lvSend.sendAndLoad("register.php", lvReceive, "POST");
gotoAndStop(1);
}
};
lvReceive.onLoad = function(success:Boolean) {
if (success) {
username1.text = "";
password1.text = "";
email1.text = "";
}
}
function validateForm():Boolean {
if (username1.text == "" || password1.text == "" || email1.text == "") {
return false;
}
return true;
}
Php Code:
http://i.stack.imgur.com/RXPWb.png
(Sorry its in link form)
Please favorite this or something until I get an answer because I've been everywhere and no one could help me. :/ BTW I have been getting a few blank entries into my database but I don't know why. Also, the lvReceive function doesn't seem to work, but when I add the username1.text = ""; into the register_button function it seems to clear the text fields. Please help me. I left the database info on the php file cause I thought maybe the database I entered could be the problem, but I did use this php code with an html file and it worked fine. I will accept any answers. Thanks in advance! :D
lvSend.sendAndLoad("register.php", lvReceive, "POST");
You put the information in lvSend and not in lvReceive.
Perhaps you should put the information in lvReceive:
lvReceive.username = username1.text;
lvReceive.password = password1.text;
lvReceive.email = email1.text;
lvSend.sendAndLoad("register.php", lvReceive, "POST");
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);
?>