I want to check if the username is already taken, here is my script, which outputs "undefined". Can anyone help me, please? :)
This is in my jQuery - $("#registerusername").val() is the value of an input.
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data.exists);
if(data.exists){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
}, 'JSON');
This is in my checkregister.php
header('content-type: text/json');
if(!isset($_POST['username']))
exit;
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
echo json_encode(array('exists' => $query->rowCount() > 0));
First, You might want to strengthen your php against sql injection by 'sanitizing' the input.
Next why return JSON from the php? It would be much simpler to just return either true or false.
$db = new PDO('mysql:host=localhost;dbname=testdatabase','root','pw000');
$query = $db->prepare("SELECT * FROM users WHERE username = '" . $_POST['username'] . "'");
$query->execute();
if( $query->rowCount() > 0 ){
echo 'true';
}
else{
echo 'false';
}
Then in your javascript:
$.post('checkregister.php',{username: $("#registerusername").val()}, function(data){
window.alert(data);
if(data == 'true'){
window.alert("Name already found");
}else{
window.alert("Name NOT found");
}
});
edit---
You could also just return a boolean variable from php rather than a string, but either will work
Simple Example..
Jquery
var username = $.trim($('#username').val());
if(username != '') {
$.ajax({
url : 'localhost/phpScript.php',
data : {username : username},
dataType : 'JSON',
type : 'POST',
cache : false,
success : function(result) {
if(result == '1') { alert('Username Found.'); }
else if(result == '0') { alert('Username Not Found!'); }
},
error : function(err) {
console.log(err);
}
});
}
PHP/MySQL (Make sure that you escape value for user input, Before giving it to MySql)
if(isset($_POST['username'])) {
$username = $_POST['username'];
$sql = "SELECT username FROM users WHERE username = '".$username."' LIMIT 1";
$query = mysql_query($sql);
if(mysql_num_rows($query) == '1') {
echo '1';
} else {
echo '0';
}
}
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.
This question already has answers here:
Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
(13 answers)
Closed 7 years ago.
I want to do this simple log in task using php web service. I am just trying to authenticate username and password on the basis of text result I am echoing in my php.
PHP:
<?php
// Include confi.php
include_once('confi.php');
$found = false;
$email = isset($_POST['email']) ? mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ? mysql_real_escape_string($_POST['password']) : "";
if(!empty($email) && !empty($password)){
$login=mysql_num_rows(mysql_query("select *
from `login`
where `email`='$email'
and `password`='$password'"));
$result =array();
if($login!=0)
{
echo "success";
}
else
{
echo "failed";
}
}
#mysql_close($conn);
/* Output header */
header('Content-type: text/plain');
?>
If the username and password match; it displays success.
Jquery
<script>
$(function () {
$("#logon").click(function () {
var email = $("#username").val();
var password = $("#pass").val();
var dataString = "email=" + email + "&password=" + password;
if ($.trim(email).length > 0 & $.trim(password).length > 0) {
$.ajax({
type: "POST",
url: "http://*****/login.php",
data:dataString,
crossDomain: true,
cache: false,
beforeSend: function () { $("#logon").html('Connecting...'); },
success: function (data) {
if (data == "success") {
alert(result+"You are in");
localStorage.login = "true";
localStorage.email = email;
window.location.href = "test.html";
}
else if (data == "failed") {
alert("Login error");
$("#logon").html('Login');
}
}
});
}
});
});
</script>
you are missing the json function you have to encode what ever you want to send to back to request
<?php
/*output the header here*/
header("Content-Type: application/json");
// Include confi.php
include_once('confi.php');
$response['Status'];// declare a variable to store msg
$found = false;
$email = isset($_POST['email']) ?
mysql_real_escape_string($_POST['email']) : "";
$password = isset($_POST['password']) ?
mysql_real_escape_string($_POST['password']) : "";
if(!empty($email) && !empty($password)){
$login=mysql_num_rows(mysql_query("select *
from `login`
where `email`='$email'
and `password`='$password'"));
$result =array();
if($login!=0)
{
$response['Status']=""success";
}
else
{
$response['Status']="failed";
}
}
#mysql_close($conn);
here make the change
$result= json_encode($message);
echo $result;
?>
in you jquery data to ajax function add
dataType:"json",
success: function (data) {
if (data.Status == "success") { //here check the condition
alert(result+"You are in");
localStorage.login = "true";
localStorage.email = email;
window.location.href = "test.html";
}
else if (data.Status== "failed") { //here check the condition
alert("Login error");
$("#logon").html('Login');
}
}
I have writtin this code to check the email availability.
var email = $('#email_reg').val();
if(email && email.length > 0)
{
if(!isValidEmailAddress(email))
{
isValid = false;
$('#msg_email').html('Email is invalid').show();
}
else
{jQuery.ajax({
type: 'POST',
url: 'check_username.php',
data: 'email='+ email ,
cache: false,
success: function(response){
if(response == 1){
$('#msg_email').html('Email already Exists').show();
isValid=false;
}
else {
$('#msg_email').html('').hide();
}
}
});
}
}
else
{
isValid = false;
$('#msg_email').html('Please enter email').show();
}
The php Code is
<?php
require_once('Connections/connection.php');
$username= mysql_real_escape_string($_REQUEST["email"]);
if (!$con)
{
echo 0;
}
else {
mysql_select_db($database_connection, $connection);
$result = mysql_query("SELECT * FROM vendor_logiin WHERE username='" . $username . "'");
$num = mysql_num_rows($result);
echo $num; //it will always return 1 or 0 since we do not allow multiple users with the same user name.
}
mysql_close();
?>
Now all the others work well like when left it empty and give a wrong email format.But the problem is when i give an email Id that already exists. It didnot give error.
I have no idea what is going wrong.
Since you didn't specify dataType the response is probably treated as text or html and in that case it might be wise to do the comparison as a string:
if (response == "1") {...}
instead of a number. Or use parseInt(response, 10) == 1 if you compare it as a number.
url : http://localhost/test-mobile/log.php?username=&password=pass
$.ajax({
url:url,
type:'POST',
data:{message:message},
dataType:'json',
json:'members',
success:successData,
error:function(){
alert("error")
}
});
function successData(data){
var response=data.message;
alert(response);
}
json response is {"members":{"httpCode":"400","message":"Username missing"}}
PHP code is given below:
<?php
require_once("class/clsdatabase.php"); //Connect to SQL
$username = $_GET['username'];
$password = $_GET['password'];
//Check Username
if($username == '') {
$user = 'Username missing';
$success = true;
$status = array("httpCode"=>"400", "message"=>$user);
//return $status;
}
//Check Password
if($password == '') {
$pass = 'Password missing';
$success = true;
}
//Create SELECT query
$qry = "select * from user_register where emp_code='$username' AND emp_password='$password' AND active='1';";
$result = mysql_query($qry);
$te = mysql_num_rows($result);
if($te == 0 && $username != '' && $password != '') {
$both = 'Invalid username or password';
$success = true;
}
//If there are input validations, redirect back to the registration form
if($te != 0 && $username != '' && $password != '') {
$row = mysql_fetch_assoc($result);
$name = $row['emp_code'];
$success = true;
$status = array("httpCode"=>"400", "message"=>$name);
//return $status;
}
//echo $_GET['callback']. '(' . json_encode($status) . ');';
echo '{"members":'.json_encode($status).'}';
?>
alert a json response
I would split the pages up into two. One file called ajax.php and another called index.php.
Your index.php will look something like.
<html>
<head>
<script type="text/javascript">
postData={ajax:"testing",id:'123'};
$.post('ajax.php', postData , function (data) {
alert(data);
});
</script>
</head>
<body>
</body>
</html>
And your ajax.php file will look something like
<?php
// its important that this file only outputs json or javascript
// content and nothing else.
if(isset($_REQUEST['ajax'])){
$ajaxRequest = $_REQUEST['ajax'];
if($ajaxRequest == 'testing'){
// do some php stuff here -- if you look at the above example we sent an id variable
$sql = "SELECT FROM table WHERE id = {$_REQUEST['id']}";
$results = query($sql);
echo json_encode($results);
exit; // exit the script here so that only the ajax stuff is output
}
}
The jQuery .ajax function automatically decodes the JSON object if the dataType:'json' parameter is set (which it is in his query). So the 'data' variable passed to the success() function will already be a javascript object.
To access the 'message' value, you would use "data.members.message" since the 'members' object contains the 'message' value.
function logsig() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = '&username=' + username + '&password=' + password;
if(username=='' || password=='') {
$('#success').fadeOut(400).hide();
$('#error').fadeOut(400).show();
} else {
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?=base_url()?>index.php/home/logsig",
data: dataString,
json: {session_state: true},
success: function(data) {
if(data.session_state == true) {
window.location = "<?=base_url()?>";
} else if(data.session_state == false) {
$("#login_failure").fadeIn(400);
}
}
});
}
}
How can I pass multiple json encoded values to my form above. What I'm doing is if user logs in, 'session_state' is passed, and if user has a 'pending' account, 'pending' is passed. Both json values have an expression to be executed.
public function logsig() {
header('Content-type:application/json');
$postedEmail = $this->input->post('username');
$password = $this->input->post('password');
$hashedPass = $this->encrypt->sha1($password);
$query = $this->db->query("SELECT * FROM users WHERE username = '{$postedEmail}' AND password = '{$password}'");
if ($query->num_rows() > 0) { // if user is already registered and is logging in, execute the following sql/php commands.
$row = $query->row();
if ($row->status == "pending") {
echo json_encode(array('pending' => true));
} else {
echo json_encode(array('pending' => false));
}
//$this->session->set_userdata('userid', $idgen);
//$this->session->set_userdata('email', $postedEmail);
$this->session->set_userdata('logged', "1"); // 1 means user is logged in.
echo json_encode(array('session_state' => true));
} else {
echo json_encode(array('session_state' => false)); // false sends to jquery that member isn't registered
}
}
You should collect all your data and at the end output it as the single JSON string. For example:
$output= array();
if ($query->num_rows() > 0) {
$row = $query->row();
// Status flag
$output['pending'] = $row->status == "pending";
$this->session->set_userdata('logged', "1"); // 1 means user is logged in.
// Session state
$output['session_state'] = true;
}
else {
$output['session_state'] = false;
}
header('Content-type: application/json');
die(json_encode($output));
Or in this case even better (optimized true-branch):
$row = $query->row();
$this->session->set_userdata('logged', "1"); // 1 means user is logged in.
// Session state
$output = array(
'pending' = $row->status == "pending",
'session_state' = false
);