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;
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 written code in AJAX which checks whether password exists or not. if yes it sends "OK" as output else "Incorrect " as output . i want to success handler in AJAX call's response to do task based on that. How can handle it? I want if password is correct , to remove Attribute of disabled in a form element else i want i want that form element's attribute remained back as disabled.
AJAX code goe like this :
$("#currentpassword").keyup(function() {
var name = $(this).val();
if (name.length > 5) {
$("#result").html('checking...');
$.ajax({
type: 'POST',
url: 'checkPassword.php',
data: $(this).serialize(),
success: function(data) {
if (data == "1") {
$("#result").html(data);
$("#newpassword").removeAttr("disabled");
$("#confirmpassword").removeAttr("disabled");
} else {
$("#result").html(data);
}
}
});
return false;
} else {
$("#result").html('');
}
});
checkpassword php file looks like below :
<?php
include_once 'includes.php';
// Submitted form data
$currentpassword=$_POST['currentpassword'];
$result = mysqli_query($db,"SELECT * FROM `users` WHERE `password`='$currentpassword' AND `username`='$session_username'");
$row = mysqli_num_rows($result);
if($row!=1) {
echo "<span style='color:red;'>Incorrect Password !!!</span>";;
}
else {
echo "OK";
}
// Output status
?>
The Good way is The PHP file should look like this
<?PHP
header('Content-type:application/json;charset=utf-8');
include_once 'includes.php';
$currentpassword=$_POST['currentpassword'];
$result = mysqli_query($db,"SELECT * FROM `users` WHERE `password`='$currentpassword' AND `username`='$session_username'");
$count = mysqli_num_rows($result);
if($count! = 1) {
header('HTTP/1.1 401 Unauthorized', true, 401);
echo json_encode('In Correct Password');
} else {
header('HTTP/1.1 404 Not Found', true, 404);
echo json_encode('Not Found');
}
And your Jquery will be
$.ajax({
type: 'POST',
url: 'checkPassword.php',
data: $(this).serialize(),
success: function(data) {
// Only 200 comes here
}, error(jqXHR, exception) {
// All errors except 200 comes here.
}
});
Hope this helps
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
I know there is a few questions like this on here. but I have done a lot of researching and bug fixing all day to try work out why my ajax does not return a response from the php file. All I want is for it to tell me a user has been registered so I can let the user move on with the signing up process. And I just need someones wise guidance to tell me what I am doing wrong!!
so I wont bore you with the validation part of the js file just the ajax
if(ValidationComplete == true){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(register, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url:url,
type:type,
data: data,
dataType: 'json',
success: function(result){
alert(result.status);
console.log(result.data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
return false;
} else {
return false;
}
currently with this, if I remove the dataType bit the alert bit happens but currently with it there nothing does.
again I will just skip to the chase on the php file
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password',
'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
echo json_encode(array("response"='true'));
Any help would be amazing!!!!!
updated code:
<?php
if( isset($_POST['firstname']) &&
isset($_POST['surname']) &&
isset($_POST['email']) &&
isset($_POST['day']) &&
isset($_POST['month']) &&
isset($_POST['year']) &&
isset($_POST['password']) &&
isset($_POST['re_type_password'])){
$first_Name = $_POST['firstname'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$password = $_POST['password'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$re_type_password = $_POST['re_type_password'];
$emailCode = md5($_POST['$first_Name'] + microtime());
if(!empty($first_Name)&&
!empty($surname)&&
!empty($email)&&
!empty($day) &&
!empty($month) &&
!empty($year) &&
!empty($password)&&
!empty($re_type_password)){
if(strlen($firstname)>30 || strlen($surname)>30 || strlen($email)>50){
echo 'the data enetered is to long';
} else {
if($password != $re_type_password){
echo 'passwords do not match, please try again.';
} else{
$query = "SELECT email FROM person WHERE email ='$email'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run)==1){
echo 'Email address already on databse';
} else{
if($day>31 || $month>12){
echo 'date of birth wrong';
} else{
$dob= $year.'-'.$day.'-'.$month;
$query = "INSERT INTO person
VALUES('','$first_Name','$surname','$email','$dob','$password'
,'1','','0','1','','','','$emailCode')";
if($query_run =mysql_query($query)) {
email($email, 'Email Confirmation', "hello ". $first_Name." ,
\n\n you need to activate your account so click the link ");
$return_data['status'] = 'success';
echo json_encode($return_data);
} else {
echo #mysql_error();
}
}
}
}
}
} else {
echo "<p id='error'> All fields are required. Please try again.</p>";
}
}
?>
<?php
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
?>
</body>
</html>
the last line it should be
echo json_encode(array("response"=>'true'));
see the added > in the array declaration, that is used to assign arrays with keys.
also in general you should put a error capture in your ajax statement, see this answer for more info
EDIT: Ok wow, that's some spaghetti code you have there, but after a little clean-up your problem is too many closing braces } you have to remove the } just before the following line also get rid of the closing and opening tags around this line, they serve no use.
} // <------- THIS ONE!
} else if (loggedIn()) {
echo 'you are already registed and logged in';
}
I should also mention two other issues with your code
You are accepting input from the user without cleaning it up and testing it properly. This is no no read here to find out more
You are using mysl_ functions, these are old and depreciated they are also security risks. Check out PDO instead
EDIT:
Add ini_set('error_reporting',1); to the top of your php script.