I'm working on a webpage in which, when the user checks a checkbox, calling a PHP function to query the table if the user exists. If so, it then displays the button to go to next page.
So far I've tried this. I am sure that my php is working fine I checked my result variable returns 0 when user exists, but for some reason it is not executing the if statement.
$(document).ready(function() {
$('#submit').hide();
$('#mobiletask').change(function(){
if($('#mobiletask').attr('checked'))
{
check_availability();
// $( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
});
});
//function to check username availability
function check_availability(){
//get the username
// var username = $('#username').val();
var username = '<?php echo $_GET['id']; ?>';
$.post("check_username.php", { username: username }, function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}
else if(result == 0) {
//show that the username is NOT available
$('#submit').show();
}
});
}
checkusername.php
$username = mysql_real_escape_string($_POST['username']);
//mysql query to select field username if it's equal to the username that we check '
$result = mysql_query('select studentId from smartphone_scores where studentId = "'. $username .'"');
//if number of rows fields is bigger them 0 that means it's NOT available '
if(mysql_num_rows($result)>0){
//and we send 0 to the ajax request
echo 0;
}else{
//else if it's not bigger then 0, then it's available '
//and we send 1 to the ajax request
echo 1;
}
Based on the response you are getting:
<html><body>1</body></html>
What you have to do is to work on your PHP file and make sure to remove any HTML in it.
Try this:
$.post("check_username.php", { username: username }, function(result){
//if the result is 1
if(result == '1'){
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}
else if(result == '0') {
//show that the username is NOT available
$('#submit').show();
}
});
$(document).ready(function()
{
$('#submit').hide();
$('#mobiletask').on('change',function() {
if($('#mobiletask').attr('checked'))
{
check_availability();
//$( "#notifyresult" ).html( "<p>Awesome, we'll send you an email!</p>" );
}
});
function check_availability()
{
//get the username
// var username = $('#username').val();
var username = '<?php echo $_GET['id']; ?>';
$.ajax({
url: 'check_username.php',
type: 'POST',
async: false,
data: {'name':'username','value':username},
success: function(result)
{
alert(result);
//if the result is 1
if(result == '1')
{
//show that the username is available
$("#errormessage").html('<p>PLease complete the task before proceeding</p>');
}else if(result == '0')
{
//show that the username is NOT available
$('#submit').show();
}
}, error: function(error)
{
alert(error);
}
});
}
});
** Remove the alerts when done with testing the code. **
Related
I have a problem with this my script.
$("#login").click(function(event) {
event.preventDefault();
var email = $("#email").val();
var pass = $("#password").val();
$.ajax({
url : "login.php",
method: "POST",
data: {userLogin:1, userEmail:email, userPassword:pass},
success : function(data){
if(data == "1"){
alert(data);
}
}
})
I want it to alert a value that I am getting from an echo in another php file
<?php
if(isset($_POST['userLogin'])){
$email = mysqli_real_escape_string($con, $_POST['userEmail']);
$password = md5($_POST['userPassword']);
$sql_login = "SELECT * from database where email = '$email' AND password = '$password'";
$query_login = mysqli_query($con, $sql_login);
$count_login = mysqli_num_rows($query_login);
if($count_login == 1){
$row_login = mysqli_fetch_assoc($query_login);
$_SESSION['uid'] = $row_login['user_id'];
$_SESSION['name'] = $row_login['first_name'];
echo "1";
}
}
?>
If I didn't put the alert(data) in an if condition, it displays the value I echo, but I need the condition to enable the right user logged in.
What can IF can also ELSE.
In your ajax add the else conditions to see if it helps uncover the issue:
if (data == "1") {
alert('youre in');
} else {
alert('try again');
}
And in your php, also account for the else condition (and do strict checking on that count of rows with ===):
if ($count_login === 1) {
// code ...
echo '1';
} else {
echo 'Sorry, the login is incorrect';
}
It works fine for me, if i always echo "1", the alert(data) show 1, in an if condition and out, pls, echo something else if isset($_POST['userLogin']) or $count_login == 1 are false, or put an
error : function(data) {
$('body').append("<div>"+data.responseText+"</div>")
}
in your ajax, to debug the prob. Because in your .php file, when you echo nothing, it returns a data in error, not in success, maybe that's your prob.
hi i am working on an authentification page , so my code is the following
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
e.preventDefault();
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
alert(result);
}
}});
});
});
i get the form , the login and password and i pass them to my php script .
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
if($msg == 0)
{
echo"false1";
}
else if($row[1] == crypt($password,$row[1]))
{
echo"true";
}
else
{
echo"false2";
}
?>
everything is goood , when i give the good email and password i get true otherwise i get false, that's not the problem , the problem is i am trying to redirect the user to another page called espace.php if the result is true so i've tried this .
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
if(result == 'true')
{
form.submit(true);
}
else form.submit(false);
}});
});
});
now even if the login and password are not correct the form is submitted , how could i manage to do that i mean , if the informations are correct i go to another page , otherwise i stay in the same page.
use json to get result from authanication page
<?php
//data connection file
//require "config.php";
require "connexion.php";
extract($_REQUEST);
$pass=crypt($password);
$sql = "select * from Compte where email='$email'";
$rsd = mysql_query($sql);
$msg = mysql_num_rows($rsd); //returns 0 if not already exist
$row = mysql_fetch_row($rsd);
$result = array();
if($msg == 0)
{
$result['error'] = "Fail";
}
else if($row[1] == crypt($password,$row[1]))
{
$result['success'] = "success";
}
else
{
$result['error'] = "try again";
}
echo json_encode($result); die;
?>
And in the ajax,, check what is the response.
$(document).ready(function(){
var form = $("#connexion");
var login =$("#logins");
var password=$("#passe");
$("#go").click(function(e){
$.ajax({type: "POST",
url: "check_con.php",
data: { email:login.val() , password:password.val() },
success:function(result){
var response = JSON.parse(result);
if(response.error){
//here provide a error msg to user.
alert(response.error);
}
if(response.success){
form.submit();
}
}});
});
});
I have been stuck with this problem for days already. I used Ajax group of web development techniques to call the php file from the server. It appears that the success method was not called. Here is my code:
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
//$("#submitButton",form).attr("disabled","disabled");
var e = $("#email", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
//var str = form.serialize();
//alert(str);
$.ajax({
type: 'POST',
url: 'http://prefoparty.com/login.php',
crossDomain: true,
data: {email: e, password :p},
dataType: 'json',
async: false,
success: function (response){
alert ("response");
if (response.success) {
alert("you're logged in");
window.localStorage["email"] = e;
window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location.replace(main.html);
}
else {
alert("Your login failed");
//window.location("main.html");
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter email and password");
}
return false;
}
In php, I used a typical MySQL call and as I run this file from Google Chrome browser. It returned the JSON correctly. Here is my php:
<?php
require_once('includes/configinc.php');
$link = mysql_connect(DB_HOSTNAME, DB_USERNAME,DB_PASSWORD) or die("Could not connect to host.");
mysql_select_db(DB_DATABASE, $link) or die("Could not find database.");
$uname = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM User_Profile WHERE Email = '$uname' AND Password = 'md5($password)'";
$result=mysql_query($sql);
$num_row = mysql_num_rows($sql);
$row=mysql_fetch_array($result);
if (is_object($result) && $result->num_rows == 1) {
$response['success'] = true;
}
else
{
$response['success'] = false;
}
echo json_encode($response);
//echo 'OK';
?>
Please check my code and point out where I did wrong.
Thank you all in advance :)
Adding
header("access-control-allow-origin: *")
to the Top of your PHP page will solve your problem of accessing cross domain request
I am trying to get a form to check if a surname already exists in the database.
It seems like it is working, it checks the database and returns values, eg the number, as a string, of times the surname exists, or 'none' if they did not enter a surname.
The problem I am having is when I try to display the results.
JavaScript:
sName = $('#sName'), sInfo = $("#sInfo");
sName.blur(function() {
$.ajax({
type: "POST",
data: "sName="+$(this).attr("value"),
url: "check.php",
beforeSend: function(){
sInfo.html("<font color='blue'>Checking Surname...</font>");
},
success: function(data){
if(data == "none")
{
sInfo.html("<font color='red'>No Surname Entered</font>");
}
else if(data != "0")
{
sInfo.html("<font color='red'>Surname Exists</font>");
}
else
{
sInfo.html("<font color='green'>Surname Not Found</font>");
}
}
});
});
check.php:
//database connection stuff
extract($_REQUEST);
if(!empty($sName))
{
$sql = "SELECT sName FROM student WHERE sName='$sName'";
$rsd = mysqli_query($DBConnect, $sql) or die('Error: '.mysqli_error($DBConnect));
$msg = mysqli_num_rows($rsd);
mysqli_free_result($rsd);
mysqli_close($DBConnect);
}
else
{
$msg = "none";
}
echo $msg;
No matter what the value of data is (eg "1", "2", "0", "none") the sInfo div always displays "Surname Exists".
When I change it to display
else if(data != "0")
{
sInfo.html("<font color='red'>Surname Exists..."+data+"</font>");
}
The result is Surname Exists...0 or Surname Exists...none when it should instead display No Surname Entered or Surname Not Found...
What am I doing wrong?
thanks.
Change the line
data: "sName="+$(this).attr("value"),
to
data: {"sName":$(this).attr("value")},
jquery will format it correctly in the post body
Summary: This is a basic, stand alone web form. Just html form, with a JQuery included for the functions.
I have a form that checks email and username for uniqueness and validity (of email). I'm using a JQuery onChange event to call each function, which is an Ajax call to a php file.
The JQuery for the username check is as follows:
$("#username").change(function() {
var username = $("#username").val();
var msgbox_username = $("#username_status");
var dataString = "username="+ username;
$("#username_status").html('<img src="images/loader.gif">Checking Availability.');
if (username != "" && username.length >= 6){
$.ajax({
Type: "POST",
url: "functions/check_username.php",
data: dataString,
success: function(msg_username) {
$("#username_status").ajaxComplete(function (event, request) {
if (msg_username == 'Username Ok') {
$("#username").removeClass("red").addClass("green");
msgbox_username.html('<font color="Green">Available</font>');
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html(msg_username);
}
});
}
});
return false;
} else {
$("#username").removeClass("green").addClass("red");
msgbox_username.html('<font color="Red">Username of 6 or more characters is required</font>');
}
});
The check_username.php file is as follows:
<?php
$username = $_GET["username"];
include_once("../includes/connect.php");
$query = "SELECT username
FROM sss_users
WHERE username = '$username'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0 && strlen($username) >= 6) {
echo '<font color="#cc0000"><strong>' . $username . '</strong> is already in use. </font>';
} else {
echo 'Username Ok';
}
?>
Continuing with the pattern, the email JQuery:
$("#email").change(function() {
var email = $("#email").val();
var msgbox_email = $("#email_status");
var dataString = "email="+ email;
$("#email_status").html('<img src="images/loader.gif">Checking Availability.');
var atpos = email.indexOf("#");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length){
$("#email").removeClass("green").addClass("red");
msgbox_email.html('<font color="Red">Valid Email Required</font>');
} else {
$.ajax({
Type: "POST",
url: "functions/check_email.php",
data: dataString,
success: function(msg_email) {
$("#email_status").ajaxComplete(function (event, request) {
if (msg_email == 'Email Ok') {
$("#email").removeClass("red").addClass("green");
msgbox_email.html('<font color="Green">Available</font>');
} else {
$("#email").removeClass("green").addClass("red");
msgbox_email.html(msg_email);
}
});
}
});
return false;
}
});
And the email PHP:
<?php
$email = $_GET["email"];
include_once("../includes/connect.php");
$query = "SELECT email
FROM sss_users
WHERE email = '$email'";
$result = mssql_query($query);
if(mssql_num_rows($result) > 0) {
echo '<font color="#cc0000"><strong>' . $email . '</strong> is already in use. </font>';
} else {
echo 'Email Ok';
}
?>
They each work seperately, but if I put an invalid username in the box and then put a valid email, somehow the check_username.php file is called and no matter what is in the box (valid or not) it thinks it's a valid username.
An example is:
All functions are called on the OnChange Event
1) type in the username asdfasdf (which is available)
2) Delete the username asdfasdf from the text box (this works correctly, displaying a username must have at least 6 characters)
3) type in any valid email
Result: the valid email works correctly, but the username field (which is blank) recalls what was there before (asdfasdf) and says it is a valid username (even though the field is still blank.)
Hope this makes sense. Any suggestions?
SOLUTION
As noted below, the .ajaxComplete() was calling all functions with that tag. Therefore, when I made the following changes it worked:
$("#username_status").ajaxComplete(function (event, request) { ... code here ... });
changed to:
$("#username_status").ajaxComplete(function (event, request, settings) { ... code and new if statement ... });
And then I wrapped
if(settings.url == 'functions/check_username.php') {}
around the validation code. This process was done for both the username and email validation.
http://api.jquery.com/ajaxComplete/
Whenever an Ajax request completes, jQuery triggers the ajaxComplete
event. Any and all handlers that have been registered with the
.ajaxComplete() method are executed at this time.
Maybe both handlers are being fired.