I am trying to use jQuery, AJAX, PHP, and MySQL to check if an email entered into a form already exists in a database.
This is my current jQuery code :
$.post('check-email.php', {'suEmail' : $suEmail}, function(data) {
if(data=='exists') {
validForm = false;
$suRememberMeCheckbox.css('top', '70px');
$suRememberMeText.css('top', '68px');
$signUpSubmit.css('top', '102px');
$tosppText.css('top', '115px');
$suBox.css('height', '405px');
$suBox.css('top', '36%');
$errorText.text('The email has been taken.');
return false;
};
});
And this is my PHP code:
<?php include("dbconnect.php") ?>
<?php
$sql = "SELECT email FROM users WHERE email = " .$_POST['suEmail'];
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($row) > 0) {
echo "exists";
}
?>
When I go through with the sign up form, when I use an email already in the database, the error text never changes to what I specified, but instead to some other error cases I have coded. Why is this not working! Thanks so much!
Use This Code: Working Perfectly:
<?php
include("dbconnect.php");
$sql = "SELECT email FROM users WHERE email = '" .$_POST['suEmail']."' ";
$select = mysqli_query($connection, $sql);
$row = mysqli_fetch_assoc($select);
if (mysqli_num_rows($select) > 0) {
echo "exists";
}
?>
If its not changing that means you might have a error with your query. Check developer options on your browser under network. There you can see all ajax calls being made. Click on look at the response. Check to see if there was an error with your query.
Also you have to validate the form submission.
Something like.
if($_SERVER['REQUEST_METHOD'] = 'POST')
{
//maybe send a token over with the form to prevent form spoofing
if($_POST['token'] === $_SESSION['token'])
{
// all your code goes in here
// you provably want to check that is a real email also
// check email input against regular expression
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
//if valid email to variable and escape data
$e = sanitizeString($_POST['email']);
}else
{
/// if not a real email to errors array
$reg_errors['email'] = 'Please enter a valid email address!';
}
}
}
You have to use prepare statements in your queries.
Related
This is the code where this used to verify the token by getting it from url and matching it with databse. and when matches it updates a db field and gives a alert that account is verified according to code. It works good. but when url token is wrong and it doesnt updates databse field but still gives same alert that account is verified. but it should use that else fumction. But still it uses that if function. What is the reason behind this error?
session_start();
include 'partials/_dbconnect.php';
if(isset($_GET['token'])){
$token = $_GET['token'];
$updatequery ="UPDATE `users` SET `status` = 'active' WHERE `users`.`token` = '$token' " ;
$query = mysqli_query($conn, $updatequery);
if($query){
echo '<script>alert("Your account is verified successfully. Please login now. !")</script>';
echo '<script> window.location.href = "/login.php"</script>';
}
else{
echo '<script>alert("This link is not valid. Acoount verification failed !")</script>';
echo '<script> window.location.href = "/index.php"</script>';
}
}
?>``
`
$query will return as true as long as the query executed successfully. You aren't matching the token at all. You're updating it. If the token doesn't match, the database doesn't update, but the query itself still returns true, that 0 rows were updated.
What you need to do is check if the token exists in the database first. If it does exist, then update it. Something like this:
if(isset($_GET['token'])){
$token = $_GET['token'];
$checkquery ="SELECT `token` FROM `users` WHERE `users`.`token` = '$token' " ;
$result = mysqli_query($conn, $checkquery);
if(mysqli_num_rows($result) >0){
$updatequery ="UPDATE `users` SET `status` = 'active' WHERE `users`.`token` = '$token' " ;
$query = mysqli_query($conn, $updatequery);
echo '<script>alert("Your account is verified successfully. Please login now. !")</script>';
echo '<script> window.location.href = "/login.php"</script>';
}
else{
echo '<script>alert("This link is not valid. Acoount verification failed !")</script>';
echo '<script> window.location.href = "/index.php"</script>';
}
}
This is my ajax code:
$(document).ready (function() {
$("#send").click (function() {
var username = $(this).val();
alert (username);
$.ajax({
url : "sendpost.php",
type: 'POST',
async: false,
data: {username},
success: function(datat){}
})
});
});
This is my php code
include ('connection_socio.php');
if(isset($_POST['body']))
{
$body=mysqli_real_escape_string($db, $_POST['body']);
$date_added="123";
$added_by="123";
$username = mysqli_real_escape_string($db, $_POST['username']);
$check = "SELECT * FROM users";
$result_profile = mysqli_query($db, $check);
//check whether the no of rows in users table is more than 0
//get username from database
$getusername = mysqli_fetch_assoc($result_profile);
$user_posted_to = $username;
echo $user_posted_to;
$query_post = "INSERT INTO posts VALUES ('', '$user_poste_to',)";
mysqli_query($db, $query_post);
echo "POSTED SUUCESSFULLY";
}
This is my profile.php code:
if (isset($_GET['u']))
{
$username = mysqli_real_escape_string($db, $_GET['u']);
//checks and remove symbols like # , ' etc
if(ctype_alnum($username))
{
//check user existance
$check = "SELECT * FROM users WHERE username='$username'";
$result_profile = mysqli_query($db, $check);
//check whether the no of rows in users table is more than 0
if(mysqli_num_rows($result_profile) == 1)
{
//get username from database
$getusername = mysqli_fetch_assoc($result_profile);
$username = $getusername['username'];
}
else
{
echo "User dont exist";
exit();
}
}
}
what I want is to fetch variable $username from profile.php page and assign it to $user_posted_to variable in senpost.php page and insert into database using javascript if any expert can help will really appreciate it i have tried this.attr() but thats not working also this.value is also not working I'm unable to fetch username from that page can anyone help me with this the username variable i want to fetch is the username of the user profile which I want to assign to $user_poste_to
I believe, the best way to access the value of $username is to store it to a cookie, once you are in senpost.php, all you need to do is to get the cookie you stored and assign it to $user_posted_to variable. the correct way to get the value of a textbox/form element in by using this $(input[type="text"]).val()
Update your AJax call.
data: {username:username},
here first username will be the index and 2nd username will be the variable which you got using $(this).val()
Please bear with me; trying my best to learn more Ajax. I am trying to Validate whether the Name of Event field in my form already exists in my table, but only if both were created by the same User. For example, if User 1 already has an event called Event1, the validation would check if there was a duplicate event name ONLY under User1.
I have the following snippet in a PHP/HTML form:
<div>Event Name: </div>
<input type="text" name="eventname" id="eventname" onblur="checkeventname()" onkeyup="restrict('eventname')" size="50" maxlength="75" />
<span id="eventnamestatus"></span>
This is my checkeventname function:
function checkeventname(){
var nameofevent = _("eventname").value;
if(nameofevent != ""){
_("eventnamestatus").innerHTML = 'checking ...';
var ajax = ajaxObj("POST", "eventcreationpage.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
_("eventnamestatus").innerHTML = ajax.responseText;
}
}
ajax.send("usernamecheck="+nameofevent);
}
}
And here is the Ajax I put at the top of the page, which I am having trouble with:
<?php
// Ajax calls this NAME CHECK code to execute
if(isset($_POST["eventnamecheck"])){
include_once("php_includes/db_conx.php");
$eventname = preg_replace('#[^a-z0-9]#i', '', $_POST['eventname']);
$sql = "SELECT id FROM users WHERE eventname='$eventname' && eventcreator='$eventcreator' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$eventname_check = mysqli_num_rows($query);
if ($eventname_check < 1) {
echo '<strong style="color:#009900;">' . $eventname . ' is not a duplicate name</strong>';
exit();
} else {
echo '<strong style="color:#F00;">' . $eventname . ' is an event name already under your name</strong>';
exit();
}
}
?>
The webpage itself has the user variable carried over (eventcreationpage.php$eventcreator=User1) I am trying to send over the $eventcreator variable, which would be the User in this case, but I'm not quite sure how to do so.
Set
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
to show that this request will send form data. Next, on your server, you may use $_POST["userid"] to get the userid if you specified it via
ajax.send("userid=" + userid);
To send both userid and eventid, you may use
ajax.send("userid=" + userid + "&eventid=" + eventid);
If you get the userid only from PHP, you could render it into script. That would look like this:
ajax.send("userid=<?php echo $eventcreator; ?>&eventid=" + eventid);
which injects the user's name into the string. Make sure it is properly escaped though, if you allow special characters for user names though.
I have here a register HTML form with some elements. I need to validate the elements on server side and client side and I will explain why. For example, in HTML form I have:
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
User name:<input type="text" name="user_name"/><br/>
Email:<input type="text" name="user_email"/><br/>
Password:<input type="text" name="user_password"/><br/>
</form>
I use PHP to check if the email and user already exists in the database. And I can use PHP to identify if the input fields are empty too.
if (isset($_POST['submit']))
{
$user_name = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
$exists = "";
$sql = "SELECT user_name from users WHERE user_name = '{$user_name}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if ($num == 1)
{
$exists .= "u";
}
$sql = "SELECT user_email from users WHERE user_email = '{$user_email}' LIMIT 1";
$stmt = $connection->prepare($sql);
$stmt->execute();
$num = $stmt->rowCount();
if ($num == 1)
{
$exists .= "e";
}
if (empty($user_name) || empty($user_email) || empty($user_password))
{
echo "<script>alert('Please fill all input fields to register!');</script>";
}
else if($exists == "u")
{
echo "<script>alert('This user is already registered in our system.');</script>";
}
else if($exists == "e")
{
echo "<script>alert('This email is already registered in our system.');</script>";
}
else if($exists == "ue")
{
echo "<script>alert('This user and this email are already registered in our system.');</script>";
}
else
{
//Here insert the values in database
}
}
Looks perfect, except for one thing: when I click submit the page is refreshed and all the input fields values are cleaned. This is bad because the user will have to enter all informations again because something was wrong. I know that the reason for this is because I am validating the form after sending it with PHP. To overcome this problem I need to validate the fields before sending the form, logically using JavaScript in the client side. But how about the check in the database? I will need to use PHP for that. If I did not have to check the database I could use JavaScript only. I would have to mix the validations with JavaScript and PHP, I think for that I should use AJAX, but do not know how.
Personally I would do the check at the client level (javascript) not in php but hey if you insists try this
if ($_POST["password_user"] != $_POST["confirm_password"])
echo "<script>alert('The entered passwords doesn't match. Try again.');
document.getElementByID('inputPassword').value = $_POST['password_user'];
document.getElementByID('inputConfirmPassword').value = $_POST['confirm_password'];
</script>";
Also update your HTML input to have ids
Password:<font color="red">*</font>
<input id="inputPassword" type="password" name="password_user"/><br/>
Confirm password:<font color="red">*</font>
<input id="inputConfirmPassword" type="password" name="confirm_password"/><br/>
Edit:
Added good AJAX tutorial:
without JQuery
with JQuery (I personally find this easier to use)
Edit2:
Sample code for PHP (server side) that returns a JSON to be fed back to the client (javascript)
<?php
$canLogin = false;
$responseArray = array();
// your logic here
// ....
if ($canLogin)
{
$responseArray["status"] = "Success";
} else
{
//Use the appropriate HTTP header (default 200), this is sometimes missed by developers
http_response_code(404);
$responseArray["status"] = "Error";
}
return json_encode($responseArray);
?>
Background: I am doing ajax calls to a PHP script which returns data to fill a form based on some file key a user inputs. This form is used so users may edit an incorrectly inputted file key from their original submission.
Problem: If a user wanted to edit a file key, they input it into a text box, hit a button for an ajax pull, the form fills, they can then correct their mistakes and submit. However, if they try to edit the new file key again, the form will not fill and I am getting no results returned from the query. This is the php script I have been using to pull the data from the server.
A sample file key might be: 10000010000-0D-MAN.
This is a good response: 10000010000-0D-MAN,N/A,amibaguest,dfgfdgfd,Electrical
This is the response I get on a newly edited file key: Nothing returned. Id: 20000010000-0D-MAN.
Really baffled at the moment. If more information is needed, please let me know.
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("database", $dbhandle)
or die("Could not select database");
$id = $_GET['param'];
if(isset($_GET['param'])) {
$sql = sprintf("SELECT a.File_key, a.Name, a.Uploader, a.File_descriptor, b.keyword1 FROM files as a, keyword as b WHERE a.File_key='%s' AND a.File_key=b.File_key", mysql_real_escape_string($id));
$result = mysql_query($sql);
if($result === FALSE) {
echo mysql_error();
}
if(mysql_num_rows($result)==1) {
while($myrow = mysql_fetch_array($result)) {
$file_key = $myrow["File_key"];
$name = $myrow["Name"];
$uploader = $myrow["Uploader"];
$file_desc = $myrow["File_descriptor"];
$keyword = $myrow["keyword1"];
$text_out .= $file_key.",".$name.",".$uploader.",".$file_desc.",".$keyword;
}// end while
} else {
$text_out = " Nothing returned. Id: ".$id;
}// end else
}// endif
echo $text_out;