Ajax/PHP not echoing after first post - php

I've made a settings page for users and the issue im having is that after you send the form once and say you get an error like "Please fill in all fields" and then you go to submit it again it won't echo out any more errors or success messages but it will update your password.
JS:
<script type="text/javascript">
$(document).ready(function() {
$("#changePassword").click(function(){
var userIdSettings = <?php echo $_SESSION['id']; ?>;
var currPass = $("#currentPass").val();
var newPass = $("#newPass").val();
var newPassRe = $("#newPassRe").val();
$.post("inc/ajax.php", {userIdSettings: userIdSettings, currPass: currPass, newPass: newPass, newPassRe: newPassRe}, function(data){
$(".message").html(data).delay(2000).fadeOut('slow', function(){
});
});
});
});
</script>
PHP:
if ($_POST['userIdSettings']) {
$userIdSettings = $_POST['userIdSettings'];
$currPass = $_POST['currPass'];
$newPass = md5($_POST['newPass']);
$newPassRe = md5($_POST['newPassRe']);
if (!empty($currPass) && !empty($newPass) && !empty($newPassRe)) {
$data = new db();
$data->dbConnect();
$data->dbSelect();
$currPass = md5($currPass);
$checkPass = mysql_query("SELECT * FROM users WHERE id = '$userIdSettings'") or die("Error: ".mysql_error());
$checkPass = mysql_fetch_assoc($checkPass);
if ($currPass == $checkPass['password']) {
if ($newPass == $newPassRe) {
mysql_query("UPDATE users SET password = '$newPassRe' WHERE id = '$userIdSettings'") or die("Error: ".mysql_error());
echo '<div class="messages green large"><span></span>Your password has been updated!</div>';
exit;
} else {
echo '<div class="messages red large"><span></span>Your new passwords dont match!</div>';
exit;
}
} else {
echo '<div class="messages red large"><span></span>Your current password is not correct!</div>';
exit;
}
} else {
echo '<div class="messages red large"><span></span>Please fill in all fields!</div>';
exit;
}
}

$(".message").html(data).show().delay(2000).fadeOut('slow', function(){});
Notice the .show()
You are printing the data to the page, then using the fadeOut method, which at the end result sets display:none. Then you are trying to output more data, but the display is still none, resulting in nothing being displayed on the page, even though the DOM element is being updated. If you add the show() method, this will ensure the CSS value of display is set to block; show the new text for the DOM element; and then fadeOut... slowly... after 2 seconds.

Related

Not redirecting to another page after successful ajax request complete

I am validating a sign In form through ajax. After successful validation the form is not redirecting to the required page.
Ajax Codes
function login_submit(){
var stat="";
$("#submit").val("Loging in...");
$.ajax({
type: "POST",
url: "php/login.php",
data: {
uname: $("#uname").val(),
pass : $("#pass").val()
},
success: function(result) {
if(result=="parent"){
window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index";
}
else if(result == "sucess_normal"){
window.location.assign("../normal_admin");
}
else if(result == "deactivated account") {
window.location.assign("reactivate_account/");
}
else if(result == "banned account") {
window.location.assign("banned_account/");
}
else{
$("#submit").val("Login");
$("#error_msg").css({color: 'red'});
document.getElementById("error_msg").innerHTML= result;
stat = false;
}
}
});
if(!stat)
return false;
}
The php code
if(isset($_POST['uname']) && isset($_POST['pass'])){
$username = encode($_POST['uname']);
$password = encrypt(encode($_POST['pass']));
// check if entered username and password is in the database
$result = mysqli_query($conn,"SELECT * From admin_account where admin_account.username = '$username' AND admin_account.password = '$password' ");
if($row = mysqli_num_rows($result) == 1){
$found = mysqli_fetch_array($result);
if($found['state'] == 1){
$account_id = $found['account_id'];
setcookie("admin_id", $account_id, time() + (86400 * 30), "/");
$_SESSION['admin_id'] = $account_id;
$result1 = mysqli_query($conn,"SELECT role_id From admin where admin_id = '$account_id'");
$found1 = mysqli_fetch_array($result1);
$_SESSION['account_type'] = $found1['role_id'];
if($found1['role_id'] == "1"){
echo "parent";
//header("Location: http://localhost:90/auction/augeo/admin/parent_admin/index");
}else{
echo "sucess_normal";
}
}
elseif($found['state'] == 2){
echo "banned account";
}
else{
$_SESSION['deactivated_id'] = $found['account_id'];
echo "deactivated account";
}
}
else{
echo "Incorrect Username or Password";
}
}
I have tried all I could do but to no avail. I want to check if result=="parent" and if result=="parent" it should redirect to window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index"; but instead it is echoing out parent.
You say "it is echoing out parent". But this should never happen with the AJAX code you supplied.
So I'm suspecting that you have a form that's running its own default submit, and that is what you're seeing.
You may want to check out this answer:
$('#idOfYourForm').submit(function() {
var $theForm = $(this);
// This is a button or field, right? NOT the form.
$("#submit").val("Logging in...");
$.post(
'php/login.php',
{
uname: $("#uname").val(),
pass : $("#pass").val()
}
).done(function(result) {
// check the result
alert("Server said: " + result);
});
// prevent submitting again
return false;
});
You get the button with
$("#submit")
This is ok, but if the button is defined as:
<input type="submit" id="submit" value="..." />
You'll get a subsequent submit of the form the button is defined in.
To avoid this, a far easier solution to the other suggested, is to not use a submit button at all. Instead, use a simple action button. These are two examples, the second of which is probably better because it is easier to design with bootstrap/HTML5/CSS...
<input type="button" id="submit" value="..." />
or better:
<button type="button" id="submit">...</button>
In case of slow server/network, you'll probably want to aid AJAX usability by disabling the button:
$("#submit").val("Logging in...").prop("disable", "disable");
This helps avoiding multiple submits when the server is slow and the user impatient.

How to get a single mysql value and output it to an ajax call?

I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.
ajax:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});
});
php:
<?php
$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];
require "../code/connection.php";
$SQL = "select userAmount from user where userID= '$userID'";
$reply = $mysqli->query($SQL);
while($row = $reply->fetch_array() )
{
}
if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}
$mysqli->close();
echo $msg;
?>
Pretty straightforward - you just grab the value from the row and cast it as a float.
while($row = $result->fetch_array() )
{
$msg = floatval($row['userAmount']);
}
if($msg > 0) {
echo $msg;
} else {
echo "error" . $mysqli->error;
}
$mysqli->close();
And one small change in your ajax call:
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
You need to add echo $row['userAmount']; inside or after your while loop, and drop the second echo. You should be able to take result within your AJAX code and use it as a number directly.
Here function(query), query is the response from the AJAX call. So your alert should be:
alert(query);
result is empty.
You also should be using prepared statements and outputting the value you want.
Something like:
<?php
$userID = $_GET["ID"];
$amount= $_GET["amount"];
require "../code/connect.php";
$SQL = "SELECT userAmount FROM user WHERE userID= ?";
$reply = $mysqli->prepare($SQL);
if($mysqli->execute(array($userID))) {
$row = $reply->fetch_array();
echo $row['amount'];
}
else
{
$msg = "error" . $mysqli->error;
}
$mysqli->close();
?>
Then JS:
$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var result = '';
$.get("code/value.php",
{
ID:user,
amount:amount,
result:result
},function(query)
{
alert(query);
});
});
});
You can use https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat or https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt to convert the value to an integer/float in JS.

ajax error handling / show error if mysql result is false?

I have a form where a user can input a voucher code:
<form>
<input type="text" name="promo" id="promo">
<div class="promo_check"></div>
</form>
the user can click on my div 'promo_check' which runs the following ajax:
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.promo_check', function() {
var promo = $("#promo").val();
$.ajax({
type: "POST",
url: "process_promo.php",
data: {data:promo},
success: function(data)
{
window.alert(data);
}
});
});
});
</script>
this then executes my mysql query to check if the voucher exists in the database and that the $_SESSION['user_name'] / i.e. the logged in user has the permission to use that voucher.
process_promo.php:
<?php
$username = "mark";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$_SESSION['username'] = 'mark';
$promo = $_POST['data'];
$query = "SELECT * FROM hewden1.supplier_users WHERE promo_code = '$promo'";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
if (mysql_num_rows($result) > 0) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}else{
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
} }
}else{
echo 'error';
}
}
?>
this all works fine, if the voucher code matches for that user then it echo's 'correct' and my ajax will show an alert saying 'correct'. Then if the voucher code does not match for the user then it echo's 'not correct for user'.
The problem i have is when the voucher is not valid at all and cannot be found in the database it is suppose to echo 'error' however ajax show a blank/empty alert message instead of showing 'error'.
I think this is because i am using success: in my ajax but when i try to add an error: call back my script stops working. can someone please show me what i'm doing wrong? thanks in advance
Looking at process_promo.php, if you get no result from the database query, then the contents of the while loop never get executed. Putting it another way, inside the while loop you'll never have a mysql_num_rows($result) == 0 condition.
Here I moved your while loop inside your mysql_num_rows check:
if (mysql_num_rows($result) > 0) {
while($row = mysql_fetch_assoc($result)) {
if ($row['user_name'] == $_SESSION['username']) {
echo 'correct';
}
else {
if ($row['user_name'] !== $_SESSION['username']) {
echo 'not correct for user';
}
}
}
}
else {
echo 'error';
}
...which also pulls the error report outside the while loop and gives it a chance to execute.

Ajax and PHP with database connection

i have problems with the code below, I'm trying to bring a message of error if the email already exists, but I'm not having success .. Look at the code:
Ajax an jQuery:
<script type="text/javascript">
// Centering the text content
jQuery(window).resize(function () {
boxHeight();
}).load(function() {
boxHeight();
// Show the content and focus the email input
$("#content").fadeIn();
$("#email").focus();
});
jQuery(document).ready(function($){
$('#subscribe').submit(function(e){
e.preventDefault();
email = $('input#email');
email_regex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
if(!email_regex.test(email.val())) {
$('#response', form).fadeIn(500, function() {
$('#response', form).html('<p class="message warning" align="center">Invalid email</p>');
});
return;
} else {
$('#response', form).html('<p class="message">Please Wait...</p>');
}
var form = $(this);
var post_url = form.attr('action');
var post_data = form.serialize();
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function(responseText) { if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else { if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
}
});
});
});
</script>
PHP Database connect:
<?php
$host="xxxx"; // Host name
$username="xxxx"; // Mysql username
$password="xxxx"; // Mysql password
$db_name="xxxx"; // Database name
$tbl_name="xxxx"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get values from form
$email = $_POST['email'];
$query = mysql_query("SELECT email FROM banco_emails WHERE 'email' = '$email'");
if(mysql_num_rows($query) == 1) { // if return 1, email exist.
echo '1';
} else {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
The problem is that the ajax code does not show the error message, only the message "Please wait ..." and nothing happens, i don't know why...
Sorry for my bad english.
Thanks in advanced!
Problem solved, the problem was in the php code, I did it and it worked!
$query = mysql_query("SELECT email FROM banco_emails WHERE email = '$email' LIMIT 1");
$email_check = mysql_num_rows($query);
if ($email_check > 0) {
echo '1';
} else if ($email_check == 0) {
// Insert data into mysql
$sql="INSERT INTO $tbl_name(email) VALUES ('". $email . "')";
$result=mysql_query($sql);
echo '<p class="message">Thanks for registering. Our bar is getting crowded!</p>';
In your success function you incorrectly handle what PHP returns on success. If the email was new and was added to the database, PHP will echo:
<p class="message">Thanks for registering. Our bar is getting crowded!</p>
Your JS parses the response like this:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
if(responseText == "") {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
}
The problem here is that you only display the HTML message if responseText is an empty string. You should get rid of the if statement:
if(responseText == 1) {
$('#response', form).html('<p class="message">Error...</p>');
} else {
$(form).fadeOut(500, function(){
form.html(msg).fadeIn();
});
}
This way the responseText is displayed. And I'm not 100% sure what your submission HTML looks like, but after you show the message you might want to fade out the "please wait" if it would still be visible after you hide the form.
Try to this way:
Make unique email column.
If the email address is already exist its return an error, and you can show the error message to user, on ajax error section.

Print like count without page refresh

I have a like/unlike post on my website, and when I click the like button I would like the value of check2 to show beside like without me having to refresh the page to see it. Currently I'll click like and it inserts the data but only shows on a page refresh. I'm hopeless with this kind of stuff.
Here is the code in the order it executes.
Thanks for any help.
POST LIKE
echo "<div class='stream_option'><a id='likecontext_".$streamitem_data['streamitem_id']."' style='cursor:pointer;' onClick=\"likestatus(".$streamitem_data['streamitem_id'].",this.id);\">";
if($checklikes>0){
echo "Unlike";
}else{
echo "Like";
}
echo "</a> ";
$check2 = user_core::print_like_count($streamitem_data['streamitem_id']);
if($check2>0){
echo "(".$check2.")";
}
Ajax Function
function likestatus(postid,contextid){
var obj = document.getElementById(contextid);
if(obj.innerHTML=="Like"){
obj.innerHTML="Unlike";
}else{
obj.innerHTML="Like";
}
$.post("../include/like_do.php", { streamitem_id: postid} );
}
LIKE_DO
$check = user_core::check_liked($_SESSION['id'],$_POST['streamitem_id'],1);
user_core::do_like($_SESSION['id'],$_POST['streamitem_id'],1);
if($check==0){
?>
<?php
}else{
?>
<?php
}
}
else{
echo "<script>alert('Error liking post');</script>";
}
?>
USER_CORE
function check_liked($id,$streamid,$value){
$check = "SELECT feedback_id FROM streamdata_feedback WHERE feedback_streamid=$streamid AND feedback_userid=$id AND feedback_rating=$value";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
return $check2;
}
function print_like_count($streamid){
$check = "SELECT feedback_id FROM streamdata_feedback WHERE feedback_streamid=$streamid AND feedback_rating=1";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
if($check2>0){
echo "(".$check2.")";
}
}
What you're looking for is an AJAX submission using DHTML to change the value of the likes.
<script language="javascript">
$(".likeButton").click(function() {
$.post("likeProcessor.php", {
id: $(this).attr('id')
}, function(data) {
$("#likeIndicator" + $(this).attr('id')).html(data);
});
</script>
Then your likeProcessor script will simply return the number of likes for that item.
NOTE: This is pseudo-code to give you an idea of what needs to happen. For further info on jQuery and Ajax, RTM at http://www.w3schools.com/jquery/default.asp and http://www.w3schools.com/ajax/default.asp respectively.

Categories