Trying to show sucess message with jQuery concatenated with php echo - javascript

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

Related

jquery ajax not catch the data back

I have this jquery ajax script
$.ajax({
type: "POST",
url: "register.php",
data: "name=" + name + "&email=" + email + "&password=" + password + "&confirm_password=" + confirm_password + "&captcha=" + captcha,
success: function(data){
if(data == "Success"){
$("#tombol_submit").remove();
$("#register_sukses").fadeIn(500);
}else{
$("#register_gagal").html(data).fadeIn(500);
$("#submit").removeAttr("disabled").attr("value", "Submit");
}
}
in the register.php, once the data successfully added to database, it will echo the "Success" word, the word Success is appear in the form page, but the button (tombol_submit) not removed, otherwise it back into Submit button (just like in 'else' statement). How to remove the button, so the client cannot click the submit button again?
here's the register.php script
<?php
session_start();
include "config/koneksi.php";
if(!empty($_POST['captcha'])){
if($_POST['captcha'] == $_SESSION['hasil']){
$fullname = $_POST['name'];
$email = $_POST['email'];
$password = md5($_POST['password']);
$queryform = "INSERT INTO register (fullname,email,pass)
VALUES('$fullname','$email','$password')";
if ($hasilform = mysqli_query($konek2, $queryform)) {
echo "Success";
} else {
echo "Failed";
}
} else {
echo "The captcha code is wrong";
}
} else {
echo "The captcha cannot be empty";
}
?>
Normally $().remove() will work.
If you are asking why this if...else... doesn't work and always goes to else, please check the response from your backend to make sure the response is only a "Success" string.
You can try like this
$("#tombol_submit").css("display","none");
use this:
$("#tombol_submit").hide();
i think
id "tombol_submit" is not exit
Check console for error,
then based on error you can fix the problem.

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".

AJAX and HTML element not working

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.

If statement not working in javascript/ajax

Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.

Ajax getting a value from php?

I am trying to use ajax to add a div to display an error message. But instead of the correct error message I get null every time. The null is a result of
<?php echo json_encode($_SESSION['msg']['login-err']); ?>;
How can I fix this? Why is it showing as null?
JavaScript:
$(document).ready(function(){
$("#open").click(function(){
$("#register").fadeIn(500);
});
$("#close").click(function(){
$("#register").fadeOut(500);
});
$("#log").click(function(){
username=$("#username").val();
password=$("#password").val();
submit=$("#log").val();
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(html) {
if(html==true) {
}
else {
$("#error-log").remove();
var error_msg = <?php echo json_encode($_SESSION['msg']['login-err']); ?>;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
<?php unset($_SESSION['msg']['login-err']); ?>
}
}
});
return false;
});
members.php:
<?php if(!defined('INCLUDE_CHECK')) header("Location: ../index.php"); ?>
<?php
require 'connect.php';
require 'functions.php';
// Those two files can be included only if INCLUDE_CHECK is defined
session_name('Login');
// Starting the session
session_set_cookie_params(7*24*60*60);
// Making the cookie live for 1 week
session_start();
if($_SESSION['id'] && !isset($_COOKIE['FRCteam3482Remember']) && !$_SESSION['rememberMe'])
{
// If you are logged in, but you don't have the FRCteam3482Remember cookie (browser restart)
// and you have not checked the rememberMe checkbox:
$_SESSION = array();
session_destroy();
// Destroy the session
}
if(isset($_GET['logoff']))
{
$_SESSION = array();
session_destroy();
header("Location: ../../index.php");
exit;
}
if($_POST['submit']=='Login')
{
// Checking whether the Login form has been submitted
$err = array();
// Will hold our errors
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
$_POST['rememberMe'] = (int)$_POST['rememberMe'];
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,usr FROM members WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['usr'])
{
// If everything is OK login
$_SESSION['usr']=$row['usr'];
$_SESSION['id'] = $row['id'];
$_SESSION['rememberMe'] = $_POST['rememberMe'];
// Store some data in the session
setcookie('FRCteam3482Remember',$_POST['rememberMe']);
}
else $err[]='Wrong username and/or password!';
}
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}
Normally a AJAX request makes a request to a PHP page which returns a value. It is often JSON but does not have to be. Here is an example.
$.ajax({
type: "POST",
url: "a request URL",
data:{
'POST1':var1,
'POST2':var2
}
success: function(result)
{
//Do something based on result. If result is empty. You have a problem.
}
});
Your PHP page doesn't always return a value so its hard to know whats going on. Your work-around for this is to use javascript variables wich hold echoed PHP data when your page returns empty. But this won't work in your case. Echoing PHP variables into javascript might work fine on occasion to but it is not good practise.
It won't work in your case because your javascript variables are set when the page is first loaded. At this point the variable $_SESSION['msg']['login-err'] has not been set (or might hold some irrelevant data) and this is what your javascript variables will also hold.
When you do it the way I mentioned you can also use functions like console.log(result) or alert(result) to manually look at the result of the PHP page and fix any problems.
I would suggest doing something like the following.
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
echo $_SESSION['msg']['login-err'];
}
else
echo 'success';
}
Javascript
$.ajax({
type: "POST",
url: "",
data: "submit="+submit+"&username="+username+"&password="+password,
success: function(response) {
if(response=='success') {
alert("Woo! everything went well. What happens now?");
//do some stuff
}
else {
alert("oh no, looks like we ran into some problems. Response is"+ response);
$("#error-log").remove();
var error_msg = response;
$("#s-log").append('<div id="error-log" class="err welcome dismissible">'+error_msg+'</div>');
}
}
});
This may not necessarily work exactly as you intended but its a good start for you to build on.
By going through the code , it seems that you are doing redirect first then sending the response.
There is something wrong in below code snippet
if($err) {
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: index.php");
}
else
header("Location: workspace/index.php");
echo 'true';
exit;
}

Categories

Resources