code from action.php
if(isset($_POST["username"]))
{
$query = "
SELECT * FROM Admin
WHERE Username = '".$_POST["username"]."'
AND Password = '".$_POST["password"]."'
";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$_SESSION['username'] = $_POST['username'];
echo 'Yes';
}
else
{
echo 'No';
}
}
if(isset($_POST["action"]))
{
unset($_SESSION["username"]);
}
code from index.php
$(document).ready(function(){
$('#login_button').click(function(){
var username = $('#username').val();
var password = $('#password').val();
if(username != '' && password != '')
{
$.ajax({
url:"action.php",
method:"POST",
data: {username:username, password:password},
success:function(data)
{
//alert(data);
if(data == 'No')
{
alert("Wrong Data");
}
else
{
$('#loginModal').hide();
location.reload();
}
}
});
}
In the above index.php code always else part is executed. so I believe the data is not received from action.php code But $_SESSION['username'] = $_POST['username']; part of the code in action.php code is executed.
so my question is why 'Yes' or 'No' is not sent as it is expected.
any kind of help will be greatly appreciated;
use 'datas' in the alert.. You misspelled them
Related
When the AJAX is called I always get these errors:
net::ERR_EMPTY_RESPONSE or net::ERR_CONNECTION_RESET
I also tryed different browsers (Chrome and Edge) but it is only working on localhost.
Thanks for all your help and support.
My PHP code (register.php):
require_once 'mysql_conn.php';
// username and password sent from form
$myUsername = mysqli_real_escape_string($db,$_POST['username']);
$myPassword = mysqli_real_escape_string($db,$_POST['password']);
$myRepPassword = mysqli_real_escape_string($db,$_POST['rep_password']);
if($myPassword == $myRepPassword && strlen($myUsername) >= 3 && strlen($myPassword) >= 8)
{
$userCheck = "SELECT id FROM users WHERE username = '$myUsername'";
$result = mysqli_query($db,$userCheck);
$count = mysqli_num_rows($result);
if($count > 0)
{
echo "This user already exists";
}
else
{
$sql = "INSERT INTO users (username, password) VALUES ('$myUsername', '$myPassword')";
if ($db->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
$db->close();
}
}
else
{
echo "Please check the values you inserted";
}
and the AJAX call:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'register.php',
data: {username:username, password:password, rep_password:rep_password},
success: function (data) {
errorHandling(data);
}
});
});
});
I don't know how, but I solved it by deleting and re-creating the register.php file
I have a an ajax post method that if success will alert "account successfully created". my problem is when it's not created it should alert account already exists, But what the problem it still alert the same.
script code:
$(document).ready(function(){
$("#btn-register").click(function(){
var regaccount = $("#regaccount").val();
var regpass = $("#regpass").val();
if((regaccount == "") || (regpass == "")){
alert("Information required!");
}else {
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"®pass="+regpass,
success: function(data){
alert("account successfully created!");
},
error:function(){
alert("account already exists");
}
});
}
$("#regaccount").val('');
$("#regpass").val('');
return false;
});
});
register.php
<?php
include 'function.php';
session_start();
ob_start();
$userid = rand(100000, 999999);
$regaccount = $_POST['regaccount'];
$regpass = $_POST['regpass'];
$regaccount = stripslashes($regaccount);
$regpass = stripcslashes($regpass);
$salt = "dctech2015ABcRXd";
$regpass = md5($regpass) . $salt;
$regpass = sha1($regpass);
$con = new Functions();
$con = $con->db;
$stmt = $con->query("SELECT * FROM users WHERE username = '$regaccount'");
$count = $stmt->rowCount();
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
}else{
echo '<script>alert("account name already exists");</script>';
}
ob_end_flush();
?>
You need to do following changes to make this work:
1) In your PHP code, do not write any alert.
2) Whether user exists in database or newly inserted, AJAX request will fetch only data. We have to handle the logic.
3) AJAX error method will be called only when AJAX request is failed (either request not sent or response status is not 200 OK).
4) In your case, error method will never be called if user already exists or even user is inserted as data is being correctly transferred from JavaScript to PHP.
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
echo 'success';
}
else{
echo 'exists';
}
AND
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"®pass="+regpass,
success: function(data){
if (data == 'success') {
alert("account successfully created!");
}
else if (data == 'exists') {
alert("account already exists");
}
},
error:function(){
alert("Unknown problem occured.");
}
});
Here you are trying to prompt message into AJAX error section which is wrong. You need to handle both into success section.
The very simple example is, return $count and check that value if greater then 0 means record is exist.
Changes in register.php code:
if($count != 1){
$con = new Functions();
$con = $con->db;
$status="Offline";
$stmt = $con->prepare("INSERT INTO users(user_id, username, password, status)VALUES(:userid, :account, :password, :status)");
$stmt->bindValue(':userid', $userid);
$stmt->bindValue(':account', $regaccount);
$stmt->bindValue(':password', $regpass);
$stmt->bindValue(':status', $status);
$stmt->execute();
}
echo $count;
I remove else part which is not require. And use $count for AJAX response.
And make correspond change into AJAX part also:
$.ajax({
type: "POST",
url: "register.php",
data: "regaccount="+regaccount+"®pass="+regpass,
success: function(data){
//If record exist...
if(data > 0){
alert("account name already exists");
}
else {
alert("account successfully created!");
}
},
error:function(){
alert("There is some error, Please try after some time OR contact site admin.");
}
});
Hope this is very easy to understand and help to other user also.
Hello i have an ajax form submit and i want to return json data. For some reason it doesnt work as it should. When data.error is return it should give me the message Email is incorect. Same for the other responses. What did i do wrong? My php has json header and also datatype is json.
$(function() {
$("form#login").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "log.php",
data: $('form#login').serialize(),
dataType:"json",
success: function(data){
if(data.error == "yes")
{
$("#msg").html('Email is incorect.')
}
else if (data.mandatory == "yes")
{
$("#msg").html('please complete email and pass')
}
else if (data.tip =='user')
{
alert('it works'+ data.id);
}
},
error: function(){
alert("failure");
}
});
});
});
my php
<?php
header('Content-Type: application/json');
session_start();
include ('core/dbconfig.php');
$password=$_POST['password'];
$usernume=$_POST['email'];
$hash = hash('sha512', $password);
if ($password=='' or $usernume=='')
{
$arr[] = array('mandatory' => 'yes');
echo json_encode($arr);
}
else
{
$stmt = $dbh->prepare("SELECT * FROM Users where Email=:username and Password= :hashed");
$stmt->bindParam(':username', $usernume);
$stmt->bindParam(':hashed', $hash);
$stmt->execute();
if ($row = $stmt->fetch())
{
$_SESSION['id_user']=$row['ID_User'];
$arr[] = array(
'tip' => 'user',
'id' => '3'
);
echo json_encode($arr);
}
else
{
$arr[] = array('error' => 'yes',);
echo json_encode($arr);
}
}
?>
turn all your php instances of $arr[] = to $arr =
if(data.error != undefined) ///i think this is the right way
{
$("#msg").html('Email is incorect.')
}else if(data.length == 0){
alert("No users available");
}else {
/*
you will have to do an iteration here of your
"data" parent object through your child objects
*/
for(var x in data){
if (data[x].mandatory == "yes")
{
$("#msg").html('please complete email and pass')
}
else if (data[x].tip =='user')
{
alert('it works'+ data[x].id);
}
} //close for
} //close else
im not so sure how this works, but where does my success(data) value come from?
must I return a value in url: php/login.php?
$.ajax({
url: 'php/login.php', //must i return a value in login.php?
data: {username:username,password:password},
type: "POST",
dataType: 'json',
success: function(data)
{
if(data == true){
console.log("sdfsdfs " + data);
login.submit();
}
else{
console.log("NO DATA PRESENT");
}
}
//else do an alert("please lgo in again");
});
in php/login.php i query the DB to see if such a user exists and if password match
part of my login.php
<?php
echo $username = $_POST['username']; //not echo-ing
echo $password = $_POST['password'];
if ($_POST['login']) //check if the submit button is pressed
{
$remember = $_POST['remember'];
if ($username&&$password) //check if the field username and password have values
{
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$connect=mysqli_connect($dbhost,$dbuser,$dbpass) or die("Unable to Connect");
mysqli_select_db($connect,"clients") or die("Could not open the db");
$sql = "SELECT * FROM clients.users WHERE username='$username'";
$login = mysqli_query($connect, $sql);
if (mysqli_num_rows($login))
{
while ($row = mysqli_fetch_assoc($login))
{
$db_password = $row['password'];
if ($password==$db_password)
{
$loginok = TRUE;
echo json_encode( true );
} else {
echo json_encode( false );
echo "Please re-enter username and password, they did not match";
header("Location: ../login.php");
}
?>
When you want to return some data using ajax, you need to echo data in your script that will be called by ajax. If the request is successful, it will return everything you echoed in your script into your parameter you specified in success function.
success: function(data)
{
// code...
}
so "data" will contain result from your script, then you can do whatever you want.
EDIT:
Well, i would solve it like this
$db_password = $row['password'];
if ($password==$db_password)
{
echo json_encode(array("status" => "ok", "message" => "Login successful!"));
} else {
echo json_encode(array("status" => "error", "message" => "Please re-enter username and password, they did not match!"));
//header("Location: ../login.php"); you don't need this
}
you can't echo json, then some text after it. You can, but it is not recommended at all.
Im doing a basic login system with jQuery and it seems everything fine for me, but Im always entering im my jquery here: alert('Error in system');.
But its very strange because When I do this alert(answer); its showing all my data of my $_SESSION['userlogin'].
Somebody there understand what might be wrong?
Im have this jQuery to show validator messages in a login form:
$('form').submit(function(){
var login = $(this).serialize() + '&action=login';
$.ajax({
url: 'switch/login.php',
data: login,
type: 'POST',
success: function(answer){
if(answer == 'errorEmpty'){
$('.msg').empty().html('<p class="warning">Informe seu usuário e senha!</p>').fadeIn('slow');
}
else if (answer == 'errorPass'){
$('.msg').empty().html('<p class="error">Error ,wrong pass or username!</p>').fadeIn('slow');
}
else if(answer == 'sucess'){
window.setTimeout(function(){
$(location).attr('href','dashboard.php');
},1000);
}
else{
alert('Error in system');
}
alert(answer);
},
beforeSend: function(){
$('.loginbox h1 img').fadeIn('fast');
},
complete: function(){
$('.loginbox h1 img').fadeOut('slow');
},
error: function(){
alert('Error in system');
}
});
return false;
});
});
Then I have my php file:
switch ($action){
case 'login':
$user = $_POST['user'];
$pass = $_POST['pass'];
if(!$user || !$pass){
echo 'errorEmpty';
}else{
$searchUser = $pdo->prepare("SELECT * FROM admins WHERE login=:login AND pass=:pass");
$searchUser->bindValue(":login", $user);
$searchUser->bindValue(":pass", $pass);
$searchUser->execute();
$num_rows = $searchUser->rowCount();
$result = $pesquisaUser->fetch(PDO::FETCH_ASSOC);
if($num_rows>=1){
$_SESSION['userlogin'] = $result;
echo 'sucess';
print_r($_SESSION['userlogin']);
}
else{
echo 'errorPass';
}
}
break;
default:
echo 'Error';
}
Put return; after echo sucess statement, I think the problem is print_r($_SESSION['userlogin']);.
After placed the return; the print_r will not executed.
echo 'sucess';
return;