AJAX and HTML element not working - javascript

I am trying to set a div tag to display a message if user isn't found in the database.
This is the line I can't get to work:
$("message").html(msg);
If you could help me understand what I'm doing wrong it would help. Thanks
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var code = $("#code").val();
var msg = "Who are you?!";
var dataString = 'username='+ username + '&code='+ code;
localStorage.setItem("number",code);
if(username==''||code=='')
{
alert("Um..you are missing something...");
}
else
{
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
cache: false,
success: function(result){
if(result != 0)
alert(result);
},
error: function(){
$("message").html(msg);
}
});
}
return false;
});
});
My PHP code
<?php
$username = trim($_POST["username"]);
$code = trim($_POST["code"]);
include_once './inc/config.php';
$con = new mysqli(HOST, USER, PASSWORD, DATABASE);
$sql="SELECT * FROM info WHERE First_Name='".$username."' AND Line_Number='".$code."'" ;
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,$sql);
$num_rows = mysqli_num_rows($result);
if($num_rows != 0){
echo true;
}
else{
//echo "Who are you?!";
return false;
}
mysqli_free_result($result);
mysqli_close($con);

If your message element has the ID message, select it like this:
$("#message").html(msg);
If it has the class message, select it like this:
$(".message").html(msg);
The JQuery documentation contains an overview and in-depth description of all selector types.
In addition, to trigger the error method in your Javascript, your server-side code needs to send a HTTP error code, for example like this:
header("HTTP/1.1 404 Not Found");
Or like this:
http_response_code(404);

Is message a class or an ID? Make sure that you use the proper selector on which your output is to be displayed.

Use, # for id and . For class
error: function(){
$("#message").html(msg);

To target a div with id message use
$("#message")
You have missed the #
Try this:
$.ajax({...
success: function(data){
if(data)
$("#message").html (msg);
else
alert(data);
}
});

Apart from the obvious error in the message selector, another problem I can see is in your code is in your PHP.
Your php code does not return an error condition, it returns a true or false, so always your success callback will be called.
So
if($num_rows != 0){
echo true;
}
else{
//echo "Who are you?!";
echo false;
}
then
$.ajax({
type: "POST",
url: "verify.php",
data: dataString,
cache: false,
success: function (result) {
if (result) {
alert(result);
} else {
alert(msg);
//make sure you use a proper selector here
$("message").html(msg);
}
},
error: function () {
$("message").html(msg);
}
});

error: function(){
$("message").html(msg);
}
Do you respond with 404 or anything else, except of 2xx, when user is not found? And, yes, selector is incorrect. Your function will be called only in case of HTTP error during request to the server.
This
else{
//echo "Who are you?!";
return false;
}
will not run your function.
This
else{
//echo "Who are you?!";
header("HTTP/1.0 404 Not Found");
exit;
}
can do it, but not a very nice solution. The best one is to return something like this
$response = array('status' => 'failed', 'text' => 'Whatever');
header('Content-type: application/json');
echo json_encode($response);
exit;
and in your success function work with data, check the 'status' and so on.

Related

Reading a response in Ajax php and mysql

I can't get the code to work and redirect to 2 different pages depending if the information is correct or not...
So far I have this on my login page:
$(function () {
$('#form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'newfile.php',
data: $('#form').serialize(),
success: function (response){
alert(response);
if (success.text="Username or Password incorrect")
window.location.href = "index.php";
else if (success.text="login successful") {
window.location.href = "login_success.html";
} else {
}
}
})
})
and the information Im reading from is (from another page):
<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die(" Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
$sql="SELECT myusername, mypassword FROM user WHERE myusername = '" . mysqli_real_escape_string($conn, $myusername) . "' and mypassword = '" . mysqli_real_escape_string($conn, $mypassword) . "';";
$result = $conn->query($sql);
if ($result->num_rows >0) {
echo "login successful";
} else {
echo "Username or Password incorrect";
}
$conn->close();
?>
I hope this will work for you try this:
if (response=="usernames or Password incorrect") {
window.location.href = "index.php";
}
else if (response=="login successful")
{
window.location.href = "login_success.html";
}
else { }
Use this code in ajax success. Actually you are using simple ECHO in PHP and using response.text in ajax success.
UPDATE:
you are using = sign for comparing it should be == operator for compare.
UPDATE 2:
i suggest to use status as true false not long string in php like:
if ($result->num_rows >0) {
echo true;
} else {
echo false;
}
Than in ajax response:
if(response == true){
// Success url
}
else {
// failure url
}
The variable success will be undefined inside the success callback function. So the next line will not be executed. So the page will not be redirected. According to your php code , you need to check if response is equal to the corresponding result of not.

Ajax login issues

I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.

PHP adding unwanted line break to ajax result

Why is PHP adding a line break to my simple AJAX result? This couldn't be much easier. Am I missing something?
Here is my JS:
$(document).ready(function() {
$('#inputEmail').change(function(){
// Check to see if email exists
var email = $('#inputEmail').val();
//alert(email);
$.ajax({
url : "php/checkUserEmail.php",
type: "POST",
dataType: "text",
data: {email: email},
success: function(data){
alert(data);
if(data === "exists"){
alert(data);
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("ajax error");
}
});
});
});
Here is my php:
<?php
include_once("db_connect.php");
// Catch results sent via $.post and assigns them to php variables.
$email = $_POST['email'];
// Check to see if email exists
$sql = "SELECT * FROM users WHERE email = '$email'";
$conn->prepare($sql);
$result = $conn->query($sql);
$rowCnt = $result->num_rows;
if($rowCnt == 0){
echo trim('new');
}else{
echo trim('exists');
}
For whatever reason, my result data string is returned as /r/nexists, rather than just exists, and thus never gets into my if block, even if I only use == to evaluate the condition. I tried adding the trim() function as you can see without result. Your help is much appreciated as this has taken me hours of time for a stupid if condition.
Check if there is an "empty" space after or before the php question marks, those line-breaks are also represented as part of the response.
I mean here
<?php?>
And here
I found a solution but I still do not like or understand what is happening. You should be able to return a simple string for a result. Anyway, what I did was to just echo the number of rows returned from the DB to my ajax success function. I then checked if the result was > 0 on the client and am finally in my IF block. Here is what I did:
JS:
$(document).ready(function() {
$('#inputEmail').change(function(){
// Check to see if email exists
var email = $('#inputEmail').val();
//alert(email);
$.ajax({
url : "php/checkUserEmail.php",
type: "POST",
dataType: "text",
data: {email: email},
success: function(data){
console.log(data);
if(data > 0){
console.log("HURRAY! I'm in my IF");
}
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("ajax error");
}
});
});
});
Here is the PHP:
// Catch results sent via $.post and assigns them to php variables.
$email = $_POST['email'];
// Check to see if email exists
$sql = "SELECT * FROM users WHERE email = '$email'";
$conn->prepare($sql);
$result = $conn->query($sql);
$rowCnt = $result->num_rows;
echo $rowCnt;
?>
This works, and is actually maybe alittle more elegant, but you should be able to return a string without issue.
John

PHP return to jquery / ajax not working

PHP return to jquery / ajax not working,
In my edit function error message is displayed yet success function executed and in my delete function nothing is displayed yet success is executed..
Have tried everything :( (well obviously not everything...)
Any ideas?
currentPage.EditItem = function(id) {
if (confirm('Are you sure you wish to edit?')) {
console.log("DetailPage :: edit");
var itemm = $("#itemm").val();
var amount = $("#amount").val();
var statuss = $("#statuss").val();
var Uid = localStorage.getItem("Uid");
console.log(statuss);
if (itemm == "") {
alert("Please enter item");
} else if (amount == "") {
alert("Please enter amount");
} else if (statuss == "") {
alert("Please enter status");
} else {
$.ajax({
type:'POST',
url:'http://www.mywebsite.com/edit.php',
data:{'Uid':Uid,'itemm':itemm,'amount':amount,'statuss':statuss},
success: function(data) {
alert("Edit item success");
window.location.href = "new_up.html";
},
error: function() {
alert("Edit user failure");
},
});
window.location.href = "new_up.html";
};
};
};
PHP
<?php
// Check connection stuff
$itemm_id = $_POST['Uid'];
$itemm_itemm = $_POST['itemm'];
$itemm_amount = $_POST['amount'];
$itemm_statuss = $_POST['statuss'];
print($itemm_statuss );
$qry = "xxxxxxxxxxx";
if (!mysqli_query($con,$qry))
{
die('Error: ' . mysqli_error($con));
}
echo "success";
mysqli_close($con);
?>
DELETE
currentPage.deleteItem = function(id) {
if (confirm('Are you sure you wish to delete?')) {
var Uid = localStorage.getItem("Uid");
$.ajax({
type:'POST',
url:'http://www.mywersite.com/delete.php',
data:{'Uid':Uid},
success: function(data){
if(data == "YES"){
alert("Item deleted!");
window.location.href = "new_up.html";
}
else{
alert("can't delete the row")
}
},
});
};
};
PHP
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$itemm_id = $_POST['Uid'];
$qry = "DELETE FROM balance1 WHERE id ='$itemm_id'";
if (!mysqli_query($con,$qry))
{
die('Error: ' . mysqli_error($con));
}
echo "YES";
mysqli_close($con);
?>
You might want to improve the indentation of your code before posting. It's hard to read this way. Posting a clear question with clear example code will get you more responses.
I didn't check the whole code because of this, but I think this will help you to find the error:
The success function of your ajax call gets fired whenever it manages to send its data to the server and gets a textual reply. This means it is also fired when the server returns an SQL error: this error message is also a reply.
You might want to view the results in the console to see what is going on:
success: function(data) {
console.log(data);
},
Or have the script check the response to see if the expected string 'success' was returned or something else (like an SQL error):
success: function(data) {
if(data == 'success'){
// OK!
}else{
// The server didn't say 'success' so something fishy is going on.
}
},
Also: 'success' will always be echoed the way you've written your code now. You should place it somewhere it will only be triggered when it was actually ok:
if (mysqli_query($con,$qry)){
echo "success";
}else{
die('Error: ' . mysqli_error($con));
}
You could do:
if (!mysqli_query($con,$qry)) {
header("HTTP/1.0 404 Not Found");
exit;
}
which should trigger the error: option in your jQuery call.
The reason why your code won't work is because die('Error: ' . mysqli_error($con)); to jQuery actually means "success": the server returned some text as response with a header 200 - jQuery is not going to parse that text to see if it contains the word "Error".

Trying to show sucess message with jQuery concatenated with php echo

Im trying to do a recover password system with jQuery messages and Im having a problem.
The code below is working fine, when I click in the button to recover my username and password I get the message <p class="sucess">Email sent with your data..</p>.
But I want to put the email of the user in the message. Like this:
<p class="sucess">Email sent with your data for email#example.com!</p>
Im trying like this in my php
else {
echo 'sucess'; //here I show the jQuery message
echo $result['email']; //and then I want to show my $result['email']
return;
}
I already try like this:
echo 'sucess'.$result['email'].'';
But I have always the same problem, Im entering here in my jQuery:
else
{
alert('Error in system');
}
And if I dont put this echo in $result['email'] the sucess message works fine, but when I try to echo my $result['email'] Im always entering in this jQuery condition.
Somebody there have any idea why this is happening?
My php:
switch ($action){
case 'recover':
$email = $_POST['email'];
if($email == ''){
echo 'errorempty';
}else{
$searchEmail = $pdo->prepare("SELECT * FROM admins WHERE email=:email");
$searchEmail->bindValue(":email", $email);
$searchEmail->execute();
$num_rows = $searchEmail->rowCount();
$result = $searchEmail->fetch(PDO::FETCH_ASSOC);
if($num_rows <=0 )
{
echo 'erroremail';
return;
}
else {
echo 'sucess';
echo $result['email'];
return;
}
}
break;
default:
echo 'Error';
}
}
My jQuery:
$('#recover').submit(function(){
var login = $(this).serialize() + '&action=recover';
$.ajax({
url: 'switch/login.php',
data: login,
type: 'POST',
success: function(answer){
if(answer== 'erroempty'){
$('.msg').empty().html('<p class="warning">Inform your email!</p>').fadeIn('slow');
}
else if (answer == 'erroemail'){
$('.msg').empty().html('<p class="error">Email dont exist!</p>').fadeIn('slow');
}
else if(answer == 'sucess'){
$('.msg').empty().html('<p class="sucess">Email sent with your data..</p>').fadeIn('slow');
window.setTimeout(function(){
$(location).attr('href','dashboard.php');
},1000);
}
else{
alert('Error in system');
}
},
beforeSend: function(){
$('.loginbox h1 img').fadeIn('fast');
},
complete: function(){
$('.loginbox h1 img').fadeOut('slow');
},
error: function(){
alert('Error in system');
}
});
return false;
});
you can simple echo the $email like this
$email=$result["email"];
echo $email;
then in ajax success function
if(answer.email)
{
$('.msg').empty().html('<p class="sucess">Email sent with your data..'+answer.email+'</p>').fadeIn('slow');
}
The problem is, that you server side is returning just unstructured data and the client side part will just receive a plain string like sucessdummy#example.com in the answer variable.
This answer variable is compared with strings that do not match thought your script ends in the error case. I would go for a solution by returning some kind of structured data like json.
Your server side code could look something like
$result = array('msg'=>'success','mail'=>$result['email']);
header('Content-type: application/json');
echo json_encode($result);
You have to pass the dataType:'json' option in your jquery ajax call to make it work and can access the data in the call back function like answer.msg, answer.mail

Categories

Resources