PHP With ajax if else not working and md5()? - javascript

when i execute my javascript this code why just else statement is working but not if,and when i use md5($_POST['password']) can't login?? but when not using md5 everything is ok
help me please :)
this is my database
this is my javascript
<script type="text/javascript">
$(document).ready(function() {
$("form#form_login").submit(function(event){
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type:'POST',
url :'../assets/js/utama/login.data.php',
data:formData,
async:false,
cache:false,
contentType:false,
processData:false,
success:function(data){
if(data == "success")
{
window.location = '../index.php?hal=home';
}else{
alert('error');
}
}
});
});
return false;
});
</script>
this is my php file
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password'])
$sql_login = "select * from user where email_user ='$email ' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
}else{
echo "alert('errorr')";
}
}
?>

You need to echo "success" in your PHP script response.
semicolon(;) missing md5($_POST['password']);
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='$email' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "error";
}

Please make sure all "password_user" column contain the md5 string in Database. So you have to store md5 for a password at the time of user registration. You have one non-md5 entry in the database for user "reza". So for this user md5($_POST['password']) will not match in database.
And write echo 'success'; in IF statement in PHP script.

In your code, in your select query there is space after $email and also you need to echo success when your if condition is executed. Improvise your php code as below:
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='".$email."' AND password_user='".$pass."'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "alert('errorr')";
}
}
?>
Hope this will help!

Yes It will always go in else part because you haven't eco success from php file then how can it will be go in success!!!??
change your php script to
<?php
session_start();
if(isset($_POST['email'])){
include "../../../konten/koneksi.php";
$email = $_POST['email'];
$pass = md5($_POST['password']);
$sql_login = "select * from user where email_user ='$email ' AND password_user='$pass'";
$run_login = mysql_query($sql_login);
$data = mysql_fetch_array($run_login);
if(isset($data['email_user'])){
$_SESSION['email_user'] = $data['email_user'];
$_SESSION['status'] = $data['status'];
echo "success";
}else{
echo "error";
}
}
?>
Also mark that don't use mysql* its deprecated and completely remove in PHP7. Use mysqli* or PDO instead

Related

Success function in ajax not returning anything in console

Here is my code, and while running it's not giving anything in the console.
This is how I am trying to check the data. If the data correctly I want the mentioned console in success code. But if it is not then I want else code to run. But the if-else conditions are not working properly. I am including PHP code and ajax code which I have tried. Am I doing it right?
<?php
$host = "dpydaldermt01.******.com";
$username = "test";
$password = "Test";
$database_name = "test";
$conn = mysqli_connect($host, $username, $password, $database_name) or die("Connection failed: " . mysqli_error());
$sql = "select ID, user_email from ci_iwp_wp_users limit 10";
$result = mysqli_query($conn, $sql);
$users = array();
?>
<script>
(function($) {
<?php
while($row = mysqli_fetch_assoc($result)) {
$email = $row['user_email'];
?>
var mail = "<?php echo $email ?>";
$.ajax({
type:'POST',
url:'http://bluepages.ibm.com/BpHttpApisv3/wsapi?byInternetAddr='+mail,
dataType:'someData',
success: function(data) {
if(data === '# rc=0, count=0, message=Success') {
console.log(data);
}
}
});
<?php
$users[]=$row;
}
?>
});
</script>
<?php
echo json_encode($users);
?>
Just Remove dataType:'someData', from your code because it always request and response in json so you dont have to declare separately.

Jquery ajax not submitting form to database

My jquery ajax is not submitting form to my php file. The success alert only alert blank on submit and it won't insert anything to my database. But my php file inserts to database without using ajax.
Here is my code, any idea or new way to do this
This is the AJAX CODE
$(document).ready(function(){
alert("mannn");
$("#adduser").submit(function(){
$.ajax({
type: "POST",
url: "adduser_processor.php",
data: $('#adduser').serialize(),
success: function(data){
alert(data);
}
Here is the php code to insert to database
if (isset($_POST['submit'])) {
//Check if the form is submitted
$fullname = $_POST['fullname'];
$username = $_POST['username'];
$gender = $_POST['gender'];
$about = $_POST['about'];
$number = $_POST['number'];
$password = $_POST['password'];
$timeadded = date("Y/m/d, \a\\t G.ia ( l)");
$address = $_POST['address'];
// Wanna Clean Values to prevent fro Hackers
$fullname = cleaninputs($fullname);
$username = cleaninputs($username);
$about = cleaninputs($about);
$number = cleaninputs($number);
$gender = cleaninputs($gender);
$password = cleaninputs($password);
$address = cleaninputs($address);
$checkuserq = "SELECT username FROM pos_staffs WHERE username = '$username'";
$exeq = mysqli_query($connection, $checkuserq);
$numrow = mysqli_num_rows($exeq);
if ($numrow > 0) {
$msg = "<li class='list-group-item list-group-item-danger'>Username ($username) Choosen by Another Staff</li>";
//echo $msg;
//header("location:addnewuser.php?msg=$msg");
} else {
$insertquery = "INSERT INTO pos_staffs(id,fullname,username,password,about,gender,address,date_joined)
VALUES('','$fullname','$username','$password','$about','$gender','$address','$timeadded')";
$insertq = mysqli_query($connection, $insertquery);
if ($insertq) {
//header("location:addnewuser.php?msg=$msg");
$msg = "New Staff ($fullname) has being added he can now Login";
echo $msg;
} else {
$msg = "Something Went Wrong";
echo $msg;
}
But i dont think my php file has an error because it insert normally without error.

Ajax success object

I'm trying to validate the form using AJAX. This is what I've done so far:
$('#login-form').submit(function(e) {
e.preventDefault();
var user = username.value;
var pass = password.value;
if (user != '' && pass != '') {
$('#login').html('Proccessing...');
$.ajax({
url: 'login.php',
type: 'POST',
data: {
username: user,
password: pass
},
processData: false,
contentType: false,
success: function(response) {
if (response == 'success') {
window.location.href = 'admin.php';
} else {
$('.login_message').html('Incorrect Credentails');
$('#login').html('Login');
}
}
});
} else {
$('.login_message').html('Fill All Fields');
$('#login').html('Login');
}
})
and it seems like response doesn't return success. Below is the login.php file
<?php
session_start();
$password = $username = '';
$_SESSION['user'] = $_SESSION['error'] = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['login'])) {
include_once('db.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$password = md5($password);
echo 'username: ' . $username . ' and ' . ' password: ' . $password;
$sql = "select * from users where username = '" . $username . "' limit 1";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_assoc($query);
$dbpass = $row['password'];
if ($password == $dbpass) {
;
$_SESSION['user'] = $username;
header('Location: admin.php');
} else {
$_SESSION['error'] = 'Wrong username or password!';
}
} else {
echo mysql_error();
}
}
}
?>
If it happens you have found the solution, please explain to me how you find the solution and what I've done wrong.
Thank you in advance.
Since this is ajax request,we need to send some response from server. As you did in your question check if(response=='success'). To do that, you need to send success to your client. If everything is ok (data send to server and query) then in your login.php edit this line
if($password == $dbpass) {
$_SESSION['user'] = $username;
//comment this line
//header('Location: admin.php');
echo "success";
} else {
$_SESSION['error'] = 'Wrong username or password!';
}
Here I put one line code echo "success"; and I believe this will resolve your issue.
Returning values from PHP back to JS
When using AJAX, I believe if you do echo in the PHP target file (here login.php) it will act as a return. Therefore the code after a echo will not run as you might expect.
Also in your code you have: echo $_SESSION['error'] = '';
Use == to compare two object, = is the assignment operator.
Retrieving AJAX data in PHP file
The use of the ajax() method from jQuery in your code looks correct to me. So when the call is made the information is sent asynchronously to the server. More precisely it will send the parameters to the PHP file you've specified in the ajax object properties: login.php.
In login.php you can access your passed parameters in the $_POST array.
You would have the following:
$username = $_POST['username'];
$password = $_POST['password'];
// process information...
$state = 'success'
// now you can return a JSON object back to your page
// I strongly recommend using a PHP array and converting it to JSON
// this way it's very easy to access it back with JS
$response = array(state=$state)
echo json_encode($response);
And back in your jQuery code you access the state value with response.state
if(response.state == 'success') {
alert('It is a succcess!');
}
Debugging PHP target files
Now you generally have problems in the code in this PHP files. And it's not an easy thing to debug it. So the way I proceed is: I set the parameters in stone in login.php for instance:
$username = 'usernameTest'; // $username = $_POST['username'];
$password = 'passwordTest'; // $password = $_POST['password'];
Then I would open the PHP file in a browser and run it do see if it echoes the object and if there are any bugs.
Then you can put back $username = $_POST['username']; and $password = $_POST['password'];.
Actual code
<?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
include_once('db.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$password = md5($password);
$sql = "select * from users where username = '" . $username . "' limit 1";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_assoc($query);
$dbpass = $row['password'];
if ($password == $dbpass) {
$state = 'success';
} else {
$state = 'failed';
}
} else {
echo mysql_error();
}
}
Warning mysql(), md5() and SQL injections
Don't use the deprecated and insecure mysql_* functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7 (in 2015). Use MySQLi or PDO instead.
You are wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Using strip_tags() is far from a safe way to escape data.
Don't use md5() for password hashing. It's very insecure. Use PHP's password_hash() and password_verify() instead. If you're running a PHP version lower than 5.5 (which I really hope you aren't), you can use the password_compat library to get the same functionality.
- Magnus Eriksson

PHP - AJAX - Validate simple login form (check if user is a especified one)

I have this simple form I'm testing. It's just a test for the beginning of a form that will be improved later on; I only need it to work correctly. I still don't have the database ready, so in my code I have two users that I want to pass as 'registered'.
Here's the code for the form:
<form action="" method="POST">
<label>User: </label>
<input type="text" name="user" id="usuario" />
<label>Password: </label>
<input type="password" name="password" id="password" />
<div class="text-center">
<button type="button" class="boton-submit" name="submit" onClick="login()">Sign In</button>
</div>
</form>
These two inputs are validated with JavaScript, and the values are sent through AJAX.
This is the code (only the AJAX part, the rest are only validations and they work fine):
function login(){
if(validationLogin()){
$.ajax({
url: "http://localhost/MyApp/extras/processLogin.php",
type: "POST",
data: {"user": user,
"password": password,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
if(data == "OK"){
window.location.href = "http://localhost/MyApp/loginSuccess.php";
}else{
window.location.href = "http://localhost/MyApp/loginFail.php";
}
}
});
}else{
//alert("Incorrect data");
}
}
And this is code in the PHP file:
<?php
session_start();
$user = "";
$password = "";
$errors = array();
if (isset($_POST['submit'])){
if(isset($_POST['user'])){
if(!empty($_POST['user'])){
$user = $_POST['user'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
if(isset($_POST['password'])){
if(!empty($_POST['password'])){
$password = $_POST['password'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
//TEST: Check if user is --> LAURA 123456 or LUIS 567899
if((($user == "LAURA") && ($password == "123456")) || (($user == "LUIS") &&
($password == "567899"))){
$data = "OK";
echo $data;
//header("location: ../loginSuccess.php");
}else{
$data = "ERROR";
echo $data;
//echo "No se encontrĂ³ usuario";
//header("location: ../loginFail.php");
}
}
At the beginning, I had an action in the form that sent data to the PHP directly, and in that way it worked fine --> if user was LAURA or LUIS it would redirect to loginSuccess.php and greeted the user, if not, it would redirect to loginFail.php (that's why the headers are commented)
I just want to test that this functions, but when I modified the code to use AJAX, it always fails, even if the user is LAURA or LUIS, it redirects to the loginFail page...
I suspect there is some problem in the success function in the AJAX call.
Any help is appreciated :) Have a nice day!
There's no submit index your $_POST array, so this condition if (isset($_POST['submit'])){ ... will always fail. Remove this conditional check if (isset($_POST['submit'])){ ... } entirely, and refactor your backend PHP code in the following way,
<?php
session_start();
$user = "";
$password = "";
$errors = array();
if(isset($_POST['user'])){
if(!empty($_POST['user'])){
$user = $_POST['user'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
if(isset($_POST['password'])){
if(!empty($_POST['password'])){
$password = $_POST['password'];
}else{
$errors = 1;
}
}else{
$errors = $errors;
}
$_SESSION['user'] = $user;
$_SESSION['password'] = $password;
//TEST: Check if user is --> LAURA 123456 or LUIS 567899
if((($user == "LAURA") && ($password == "123456")) || (($user == "LUIS") &&
($password == "567899"))){
$data = "OK";
echo $data;
//header("location: ../loginSuccess.php");
}else{
$data = "ERROR";
echo $data;
//echo "No se encontrĂ³ usuario";
//header("location: ../loginFail.php");
}
?>

Having trouble in sending the results from pdo to ajax

I want to do is if the user successfully registered the pdo will provide an information and send it to ajax and the ajax will message if the user is registered or not. It was working properly after i put this condition in my pdo and now it wont insert no more and ajax tells "error registering user!" all the time.
script:
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function (e) {
e.preventDefault();
var data = {};
data.name = $('#name').val();
data.age = $('#age').val();
data.gender = $('#gender').val();
data.address = $('#address').val();
data.image = $('#imgInp').val();
$.ajax({
type: "POST",
url: "user.php",
data: data,
cache: false,
success: function (response) {
if (Number(response) == 1)
{
alert("User successfully registered");
}
else
{
alert("Error registering user!");
}
}
});
return false;
});
});
</script>
user.php:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "test";
$dbc = new PDO("mysql:host=" . $host . ";dbname=" . $db, $user, $pass);
$dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$name = #$_POST['name'];
$age = #$_POST['age'];
$address = #$_POST['address'];
$gender = #$_POST['gender'];
$imageName = #$_FILES['image']['name'];
$q = "INSERT INTO students(name, age, address, gender, imageName ) VALUES(:name, :age, :address, :gender, :image)";
$query = $dbc->prepare($q);
$query->bindParam(':name', $name);
$query->bindParam(':age', $age);
$query->bindParam(':address', $address);
$query->bindParam(':gender', $gender);
$query->bindParam(':image', $imageName);
$results = $query->execute();
$results ? echo "1"; : echo "2"; ;
?>
It seems that you have error in :
$results ? echo "1"; : echo "2"; ;
yours demo
try like this :
echo $results ? "1" : "2";
working demo
you can see here a tutorial.

Categories