PHP Script doesnt return variables to AJAX - php

The code is for simple login validation.
The PHP script doesnt seem to run when returning values to JavaScript but runs fine when there are not variables to return.
So is there anything wrong or do I need to add anything else to return the values from PHP.
<?php
header('Content-type: application/json; charset=utf-8');
include("config.php");
$formd=array();
//Fetching Values from URL
$username2=$_POST['username1'];
$password2=$_POST['password1'];
$query = mysqli_query($db,"SELECT username FROM login WHERE username = '$username2'");
$result=mysqli_fetch_assoc($query);
$sql=mysqli_query($db,"SELECT password FROM login WHERE username = '$username2'");
$resul=mysqli_fetch_assoc($sql);
$row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$count = mysqli_num_rows($query);
$pass=$resul['password'];
if((password_verify($password2,$pass))and($count==1)) {
echo "ds";
} else {
echo "no";
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit();
?>
JavaScript
<script>
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ username + '&password1='+ password;
if(username==''||password=='') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
dataType: "json",
data: dataString,
success: function(data){
alert(data.no);
}
});
}
return false;
});
});
</script>

your Php code has 2 echo statements
if((password_verify($password2,$pass))and($count==1))
{
echo "ds"; // first
}
else
{
echo "no"; // first
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd); // second
This way, your php script returns malformed JSON data and hence $.ajax() cannot handle it.
Also, as others pointed out, please use the developer console to verify your script returns the expected data.

The if else part of your php script has an echo statement and then outside the if else you echo the array $formd. This malforms the JSON response. Also, you should use exit(1) as there is no exception being raised in your code.
Here the snippet you should use to get the script working.
if((password_verify($password2,$pass))and($count==1))
{
echo "ds";
}
else
{
// echo "no"; this is not required
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit(1);

Related

mysql popup forgot password

I have a form forgot password that confirms if the user exists and send a email with a link for password reset, it works fine but i do like that message "email was been sent..." should appear in a popup instead on the same page.
I tried this but does not works:
response.php
var useremail = document.getElementById("email").value();
$.get( "validation.php?email=" function( response ) {
// console.log( response ); // server response
response = response.trim();
if(response == 1){
alert("Email sent....");
} else{
alert(response);
return false;
}
});
}`
Form:
<form class="register" id="email" action="forgot.php" method="post" onSubmit="checkAll();">
mysql
if ($result=="") { $result = "Email has been sent"; }
echo "<div>$result</div>";
}
?>```
I have sorted all and now it works i let here the solution in a hope that can helps someone else:
function alert(){
echo "<script type='text/javascript'>";
echo "alert('Email has been sent - Please click on the link in the email to confirm.');";
echo "</script>";
}
if ($result=="") { $result = alert(); }
}
?>

My AJAX query isnt validating properly

New to web design here. I have a login form that validates and works perfectly in php but when I try and validate using ajax it doesn't work. When i run the page it says it is a success no matter the input into the form. I have tried for days trying to get it to validate in many different methods. If there is a better way please let me know!
php here and is on same page as login form
if (isset($_POST['login'])) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
echo json_encode('true');
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
$_SESSION['logged_in'] = true;
} else {
echo json_encode('false');
$errormsg = "Incorrect Email or Password!!!";
}
}
?>
$(document).ready(function() {
$('#login_submit').click(function() {
var form = $('#login_form').serialize();
$.ajax({
type: "POST",
url: "header.php",
data: form,
success:function (response){
alert('Hi');
},
error: function(response){
alert('Nope');
}
});
});
});
<form id="login_form" form role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="loginform">
<label class="login_form_labels"> Email:</label>
<input type="email" id="email" class="login_input" name="email"><br><br>
<label class="login_form_labels"> Password:</label>
<input type="password" id="password" class="login_input" name="password"><br>
<div id="stay_log">
Stay logged in.
<input type="checkbox" name="stayLoggedIn" value=1 id="checkbox_1">
</div>
<input class="login_form_btn" name="login" value="Submit" type="Submit" id="login_submit">
<button class="login_form_btn" type="button">Forget your Password?</button>
</form>
Please help!
set dataType as Json in your ajax as like given below
$.ajax({
type: "POST",
url: "header.php",
dataType: json,
data: form,
success:function (response){
alert('Hi');
},
error: function(response){
alert('Nope');
}
});
Try this...
I think you need to require pure JSON response from server side and handle it in your ajax success method.
In your PHP code.
$response=array();
if (!empty($_POST)) {
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = mysqli_real_escape_string($con, $_POST['password']);
$result = mysqli_query($con, "SELECT * FROM users WHERE email = '" . $email. "' and password = '" . md5($password) . "'");
if ($row = mysqli_fetch_array($result)) {
echo json_encode('true');
$_SESSION['usr_id'] = $row['id'];
$_SESSION['usr_name'] = $row['name'];
$_SESSION['logged_in'] = true;
$response['type']="success";
$response['message']="Login done successfully";
} else {
$response['type']="error";
$response['message']="Incorrect Email or Password!!!";
}
}
else
{
$response['type']="error";
$response['message']="invalid post request";
}
ob_clean();
echo json_encode($response);
die();
In above way from server you can response in only json format.
In you ajax call javascript code
$(document).ready(function() {
$('#login_submit').click(function() {
var form = $('#login_form').serialize();
$.ajax({
type: 'post',
url: $('#login_form').attr("action"),
data: form,
dataType:'json'
success:function (response){
if(response.type=="success")
{
alert(response.message);
// write code for handle your success login;
}
else
{
alert(response.message);
// write code for handle your failure login;
}
},
error: function(response){
alert('Nope');
}
});
});
});
You have to handle JSON response from server side in your ajax success response
In jQuery/AJAX, the HTTP response code termines whether it is a success or not. So if the login failed, you should set a header in PHP indicating this failure.
if (.. login has failed .. ) {
// HTTP 401 = 'Unauthorized'.
http_response_code(401);
}
By doing this, you won't even have to process the resulting JSON, only maybe to get additional info. But the basic result will tell you enough: if the success callback was called, logging in was successful. If error was called, it was not successful for whatever reason.
This sets out your basic flow, and after that you could parse the result message to see any details of what's going on (internal server error, user unknown, password doesn't match, etc).
See List of HTTP response codes, for a list of alternatives and this question for an argumentation about using 401.
First use alert(response) to find out the response you are getting. It should be true or false.
success:function (response){
if(response === "true")
{
alert("hi");
}
else
{
alert("nope");
}
},

ajax satuts cancelled after some attempts

im making and update in mysql table when button click, the problem is ajax jquery not working sometimes. It works fine and somehow after x attempts it stop working and stars cancelling my pettitions
my jquery code:
$.ajax({
type:'GET',
url: 'php/updateCosto.php',
data:{
obrero: $obrero,
fechai: $fechaa,
fechaf: $fechab,
costo: $costoS,
},
success: function(result){
if (result == 1) {
alert('Registro Actualizado');
location.reload(true);
}else {
console.log("no actualizado entrada");
alert('Registro No Actualizado');
location.reload(true);
}
}
}); // fin del ajax
the php one:
<?php
include('../db/conn.php');
$maestro = mysql_real_escape_string($_GET['obrero']);
$costosemanal = mysql_real_escape_string($_GET['costo']);
$fechai = mysql_real_escape_string($_GET['fechai']);
$fechaf = mysql_real_escape_string($_GET['fechaf']);
$update = "UPDATE tbl_costos
SET costo_semanal = '$costosemanal'
WHERE fechai = '$fechai'
AND fechaf ='$fechaf'
AND obrero = '$maestro'";
$result = mysql_query($update);
$rows = mysql_affected_rows();
echo ($rows);
mysql_free_result($result);
?>
the problem is after x number of attempts the success part of ajax object is not being used and im getting the STATUS (canceled) from network.
I dont know if it is an issue of CORS AJAX pettition or something!!

jQuery plugin Validation email check if else CRAZY WIERD

I have successfully implemented the Jquery Validation Plugin http://posabsolute.github.com/jQuery-Validation-Engine/ but i am now trying to get an ajax database email check to work (email exists / email available) and i have written some php script to get this done. Its kinda working but i am getting the most unexpected heretically odd behavior from my IF ELSE statement (seems really crazy to me). observe ### marked comments
PHP code: LOOK AT THE IF ELSE STATEMENT
/* RECEIVE VALUE */
$validateValue = $_REQUEST['fieldValue'];
$validateId = $_REQUEST['fieldId'];
$validateError = "This username is already taken";
$validateSuccess = "This username is available";
/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results = array($row['Email']);
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR ### popup shows "validating, please wait" then "This username is already taken" when email typed is in database - i.e. Working
file_put_contents('output.txt', print_r("1 in array - Email is Taken " . $validateValue, true)); ### this runs!!
}else{
$arrayToJs[1] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success ### popup shows "validating, please wait" when email typed is NOT in the database - i.e. not Working
file_put_contents('output.txt', print_r("2 else - Email is available " . $validateValue, true));
//### THIS RUNS TOO !!!!!!!!!!!!! i.e. echo json_encode($arrayToJs) wont work for both.. If I change (in_array()) to (!in_array()) i get the reverse when email is in database.
//i.e. only the else statements echo json_encode($arrayToJs) runs and the popup msg shows up green "This username is available" crazy right???
//so basically IF ELSE statements run as expected (confirmed by output.txt) but only one echo json_encode($arrayToJs) will work.!!!!
//If i remove the json_encode($arrayToJs) statements and place it once after the IF ELSE statement i get the same problem.
//both $arrayToJs[1] = false; and $arrayToJs[1] = true; can work separately depending on which is first run IF or ELSE but they will not work in the one after another;
}
HERE IS THE REST OF THE CODE-->
1-HTML FORM INPUT CODE:
<tr>
<td> <Label>Business Email</Label>
<br>
<input type="text" name="Email" id="Email" class="validate[required,custom[email],ajax[ajaxUserCallPhp]] text-input">
</td>
</tr>
2-Relevant JQUERY code in jquery.validationEngine.js:
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
3-Relevent code for ajaxUserCallPhp in jquery.validationEngine-en.js:
"ajaxUserCallPhp": {
"url": "validation/php/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "*Validating, please wait"
},
Im sure the problem lies with this echo.
echo json_encode($arrayToJs)
Please help i've spent to long on this and its almost working fully.
To clarify - I basically am trying to code it so that if i type an email in the db it shows red "This username is taken" then if i edit the input box to an email not in the database it changes to green "username is available" at the moment only one json_encode will run in any scenario no matter how i change the if else statement –
Thank you very much in advance.
Ok got it finally after a fiddle. I found that json_encode() returns false when any error or warning is posted. using the php error log file in xampp/php/logs/error_logs file i realised that i was getting an error only when the query result was null making $results = null. this caused an output error preventing json_encode() from echoing true, which is why i only got one response.
To fix it i made sure that the $result array was not empty by using the following code after the query to array part.
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
The whole code is now
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = $row['Email'];
}
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = 0;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
} else {
$arrayToJs[1] = 1; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
}
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})

Passing a variable from a PHP page to a Javascript page via jQuery.ajax()

Basically, I'm calling a page (login.php) which checks to make sure the user is verified and the password matches up through my javascript (init.js). If it is, I echo "all-good" within the PHP page, which is passed back to init.js where it checks to see if "all-good" was echoed.
Obviously this is pretty insecure, so I was thinking of doing something like $verify_string = md5(uniqid($username)); within login.php, but I'm having trouble figuring out how to pass that variable back to init.js.
Anyone have any suggestions? Here's what I'm doing now:
init.js
$.ajax({
type: "POST",
url: "login.php", // Send the login info to this page
data: str,
success: function(msg){
$(".status").ajaxComplete(function(event, request, settings){
// show 'submit' button
$('.submit').show();
// hide ajax loading gif
$('.ajax-loading').hide();
if(msg == "all-good") { // login ok?
var login_response = '<div id="logged-in">' +
'<img src="img/load-bar.gif">' +
'<br><span style="padding-top: 5px; font-size: .9em;">Logging in...</span>'
'</div>';
$('a.modalCloseImg').hide();
// resize container after processing
$('#simplemodal-container').css("width","auto");
$('#simplemodal-container').css("height","auto");
$(this).html(login_response); // refers to 'status'
// redirect after 2 seconds
setTimeout('go_to_private_page()', 2000);
}
else { // error?
var login_response = msg;
$('.login-response').html(login_response);
}
});
}
});
login.php
// checks the entered pw with the hashed pw in the db
while($row = $stmt->fetch()) {
if (crypt($password, $row['hashed_pw']) == $row['hashed_pw']) {
$_SESSION['username'] = $username;
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['redirect'] = $redirect;
setcookie('username', $username, time()+3600, '/', '', 0, 0);
setcookie('user_id', $row['user_id'], time()+3600, '/', '', 0, 0);
// this is what I want to send back:
$verify_string = md5(uniqid($username));
echo $verify_string;
// this is what is currently being sent back for verification
echo "all-good";
exit();
} else {
$errors[] = "Bad username/password combination. Try again.";
}
}
You could use an array and then encode in json with the following php function :
json_encode
$arr = Array(md5(uniqid("username")), "all-good");
echo json_encode($arr);

Categories