JQuery is not picking up echo from php - php

I'm echoing a message ('ok') from a PHP script to a JQuery ajax call.
I'm echoing out the correct message, and its showing up in the console when i log it, but the appropriate jquery function is not firing - according to the code i should get an Your password has been changed successfully" message, but I only get a "there was a problem" message - can anyone suggest a reason why?
here is the code first the PHP:
if(isset($_POST['oldpass'])){
$oldpass = mysql_real_escape_string($_POST['oldpass']);
$newpass = mysql_real_escape_string($_POST['newpass']);
$sql = "SELECT password, salt FROM users WHERE email='$log_email' AND id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$numrows = mysqli_num_rows($query);
if($numrows > 0){
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$current_salt = $row["salt"];
$db_pass = $row["password"];
}
$old_pass_hash = crypt($oldpass, $current_salt);
if ($old_pass_hash != $db_pass){
echo "problem";
exit();
}
}
$s = "$2a$10$";
$random = randStrGen(20);
$salt = $s.$random;
$p_crypt = crypt($newpass, $salt);
$sql = "UPDATE users SET password='$p_crypt', salt='$salt' WHERE email='$log_email' AND id='$log_id' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
if ($query == true){
$_SESSION['password'] = $p_crypt;
echo 'ok';
exit();
}
}
?>
This is the javascript/JQuery
function change_password(){
var oldpass = $('#old_pass').val();
var newpass = $('#new_pass').val();
var newpass_conf = $('#confirm_new_pass').val();
if(newpass != newpass_conf){
$('#status').html("Your passwords do not match");
} else if(newpass=="" || oldpass==""){
$('#status').html("You have not entered anything");
}
$.ajax({
type: 'POST',
url: "changePassword.php",
dataType: 'text',
data: {
"oldpass": oldpass,
"newpass": newpass_conf },
success:function(data){
if(data == "ok"){
$('#change_password_form').html("<h2> Success</h2><div class='noerror'><p> Your password has been changed successfully.</p> <p> You may now close this window.</p></div>");
} else {
$('#status').html("There was a problem");
}
}
});
}
$(document).ready(function(){
$(document).on('click','#change_password', function(){
change_password();
});
});
</script>
and finally the html
<div> <h1>Change your password</h1></div><hr>
<form id="change_password_form" class="input" onsubmit="return false;">
<div> <label for="old_pass">Current Password:</label>
<input id="old_pass" type="text" class="searchbox" onfocus="emptyElement('status')" maxlength="88" value=""></div>
<div> <label for="new_pass">New Password:</label>
<input id="new_pass" class="searchbox" type="text" onfocus="emptyElement('status')" maxlength="88" value=""> </div>
<div><label for="confirm_new_pass">Confirm New Password:</label>
<input id="confirm_new_pass" class="searchbox" type="text" onfocus="emptyElement('status')" maxlength="88" value=""><div>
<input type="button" style="position:relative;top:10px; float:right;" id="change_password" value="Change Password"></form>
<span id="status" class="statuserror"></span>
</body>
</html>

change the dataType: "json" in your ajax call
then in your php code return json data
json_encode(array('response'=>'ok'));
your ajax success function should look like this,
success: function (data) {
var resultObject = jQuery.parseJSON(data);
if(rersultObject['response']=='ok') {
$('#change_password_form').html("<h2> Success</h2><div class='noerror'><p> Your password has been changed successfully.</p> <p> You may now close this window.</p></div>");
} else {
$('#status').html("There was a problem");
}
}
}`
here parseJSON is used to convert JSON string to javascript object.

I got this problem a while ago and could never figure it out, although different scenario. What I did was to change the data type to json like so:
$.ajax({
type: 'POST',
url: url,
data: 'data=data&other=other'
dataType: 'json',
//if everything goes out as planned
success: function(response) {
alert(response['data']);
}
});
and in the php
$respond = array("data" => 'ok',
"other" => 'whatever else'
);
echo json_encode($respond); //send a response back to javascript
exit();

Related

using ajax to login with php

I am trying to use window.location = "userpage.php"; after a successful login but the page does not redirect.
I am using Ajax and a modal form in my code
Everything works fine. I don't get any errors. I check the network headers. and there is no response in the network
I have not been able to figure out the issue.
I have tried
window.location.href
window.location.replace.
Nothing is working
need help
Thanks
This is part of the js file
$("#loginform").submit(function(event) {
//prevent default php processing
event.preventDefault();
//collect user inputs
var datatopost = $(this).serializeArray();
//send them to login.php using AJAX
$.ajax({
url: "login.php",
type: "POST",
data: datatopost,
success: function(data) {
if (data == "success") {
window.location = "user_page.php";
} else {
$("#loginmessage").html(data);
}
},
error: function() {
$("#loginmessage").html(
"<div class='alert alert-danger'>There was an error with the Ajax Call. Please try again later.</div>"
);$
}
});
});
This is part of my login.php file
//Start session
session_start();
//Connect to the database
include("connection.php");
...
$email = mysqli_real_escape_string($conn, $email);
$password = mysqli_real_escape_string($conn, $password);
$password = hash('sha256', $password);
//Run query: Check combinaton of email & password exists
$sql = "SELECT * FROM users WHERE email='$email' AND password='$password' AND activation='activated'";
$result = mysqli_query($conn, $sql);
if (!$result) {
echo '<div class="alert alert-danger">Error running the query!</div>';
exit;
}
//If email & password don't match print error
$count = mysqli_num_rows($result);
if ($count !== 1) {
echo '<div class="alert alert-danger">Wrong Username or Password</div>';
} else {
//log the user in: Set session variables
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['email'] = $row['email'];
if (empty($_POST['remember'])) {
echo "success";
} else {
// todo logic for remember me
}
}
This is the form modal
//Start session
session_start();
//Connect to the database
include("connection.php");
...
<form method="post" class="login_form modal" id="loginform">
<div class="form-body">
<div class="form-head"><h3>Login form</h3></div>
<div class="form-logo"><img src="/dist/img/logo.svg" alt="" /></div>
<div id="loginmessage"></div>
<div class="form-inputs">
<p><input type="email" name="email" placeholder="email" /></p>
<p><input type="password" name="password" placeholder="Password" /></p>
</div>
<div class="login-session">
<div class="remember">
<input type="checkbox" id="remember" name="remember" value="remember" />
<label for="remember">Remember me</label>
</div>
<div class="">
Forgot my password
</div>
</div>
<div class="form-submit">
<input class="btn btn-primary" type="submit" value="log in"/>
<a class="btn btn-small" href="#signupform" rel="modal:open">register</a>
</div>
</div>
</form>
I finally found the solution to the issue.
In the index.js file:
success: function(data) {
if (data == "success") {
window.location = "user_page.php";`
was changed to:
success: function(data) {
if ($.trim(data) == "success") {
window.location = "user_page.php";`
Because the response message success for some reason had whitespace in it. I trimmed all whitespace and it worked.

How to check if jquery ajax send POST request or not?

I have created a simple Login Register program using PHP.
Now I am trying to validate if username already exists or not using jquery ajax. The jquery code runs but keeps on showing 'Checking Availability'.
Here is the code I have used. Please ignore the vulnerability and other errors in my PHP code ( which may not affect jquery ajax process ) as I am new to this. I'm working for improving those things.
Register.php
<?php
include('config.php');
if(isset($login_session))
{
header("Location: login.php");
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$username = mysqli_real_escape_string($obj->conn,$_POST['username']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$name = mysqli_real_escape_string($obj->conn,$_POST['name']);
$email = mysqli_real_escape_string($obj->conn,$_POST['email']);
$password = md5($password);
$sql ="SELECT uid from users WHERE username = '$username' or email = '$email'";
$register_user = mysqli_query($obj->conn,$sql) or die(mysqli_error($sql));
$no_rows = mysqli_num_rows($register_user);
if($no_rows == 0)
{
$sql2 = "INSERT INTO users(username, password, name, email) values ('$username', '$password', '$name', '$email')";
$result = mysqli_query($obj->conn, $sql2) or die(mysqli_error($sql2));
echo "Registration Successfull!";
}
else{
echo "Registration Failed.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/username.js"></script>
</head>
<body>
<form action="register.php" method="post">
<label>UserName:</label>
<input type="text" id="username" name="username" required/>
<span id="status"></span><br />
<label>Password :</label>
<input type="password" name="password" required/><br/>
<label>Full Name :</label>
<input type="text" name="name" required/><br/>
<label>Email :</label>
<input type="email" name="email" required/><br/>
<input type="submit" value=" Submit "/><br />
</form>
</body>
</html>
username.js
$(document).ready(function()
{
$("#username").change(function()
{
var username = $("#username").val();
var msgbox = $("#status");
if(username.length > 3)
{
$("#status").html('<img src="img/loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "php/username-check.php",
data: "username="+ username,
success: function(msg){
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK')
{
msgbox.html('<img src="img/yes.png" align="absmiddle"> <font color="Green"> Available </font> ');
}
else
{
$("#username").removeClass("green");
$("#username").addClass("red");
msgbox.html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="#cc0000">Enter valid User Name</font>');
}
return false;
});
});
username-check.php
<?php
include("config.php");
if(isSet($_POST['username']))
{
$username = $_POST['username'];
$username = mysqli_real_escape_string($obj->conn,$username);
$sql = "SELECT username FROM users WHERE username='$username'";
$sql_check = mysqli_query($obj->conn,$sql);
if (!$sql_check)))
{
echo 'could not complete query: ' . mysqli_error($obj->conn,$sql_check);
}else{
echo 'query successful!';
}
if(mysqli_num_rows($obj->conn,$sql_check))
{
echo '<font color="#cc0000"><b>'.$username.'</b> is already in use.</font>';
}
else
{
echo 'OK';
}
}
?>
and I want to know if there is a way to check if jQuery Ajax sent the POST request to that file or not?
You are confusing ajax functions...Syntax will be like this
$.ajax({
url: url,
data: data,
type: "POST",
beforeSend: function () {
},
success: function (returnData) {
},
error: function (xhr, ajaxOptions, thrownError) {
},
complete: function () {
}
});
Examine the request using a browser utility
- Launch the chrome browser
- Right click and select inspect element menu
- click on Network tab
- Load your URL
- Perform the Ajax request
- You can see the request here (new request will be last in the list).
- Click on it
- Right side window shows you request and response data
You did correct.Easy way to check them is use firebug tool on your browser...I recommend firefox with firebug.install it first and then open it before you post your form.then goto console log and send your form...Check it out,best software.

AJAX > PHP Log in not working

I'm trying to create a log in form using html > ajax > php, the problem is the php is not working, I don't know where is the problem, I think the ajax cannot execute my php file. I need help. Thanks in advance.
Here is my HTML code: my form and inputs are below
<form id="loginForm">
<input type="text" data-clear-btn="true" name="username" id="username" value="" placeholder="Username / ID No.">
<input type="password" data-clear-btn="true" name="password" id="password" value="" placeholder="Password">
<input type="checkbox" name="rem_user" id="rem_user" data-mini="true">
<label for="rem_user">Remember me</label>
<input type="submit" name="login" id="login" value="Log in" class="ui-btn" />
</form>
<div class="err" id="add_err"></div>
AJAX script that sends request on my php file
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is in database.
var dataString = 'username=' + username + '&password=' + password;
if (username == '' || password == ''){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: dataString,
success: function(result){
window.location="#report_page";
}
});
}
return false;
});
});
</script>
PHP File
<?php
require "includes/connection.php";
include "includes/function.php";
if(isset($_POST['login'])){
$username = $_POST['username'];
$password = $_POST['password'];
$username = sanitize($username);
$password = sanitize($password);
$pass2 = md5($password);
$salt = "sometext";
$validateHash = $salt.$pass2;
$pass = hash("sha512", $validateHash);
$sql = "SELECT * FROM user_login WHERE username='".$username."' and password='".$password."'";
$result = mysqli_query($con,$sql) or die("Error: ". mysqli_error($con));
$count=mysqli_num_rows($result);
while($row=mysqli_fetch_array($result))
{
$id = $row['user_id'];
$username = $row['username'];
$name = "".$row['firstname']." ".$row['lastname']."";
$acc_type = $row['Acc_Type'];
}
if($count==1){
if($acc_type == 'user') {
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
$_SESSION["name"] = $name;
echo 'true';
}
else {
echo 'false';
}
}
}
?>
as Cattla mentioned in comments.
Your PHP is looking for $_POST['login'], and your $.ajax call didn't pass that in.
so here is the answer
var dataString = 'login=login&username=' + username + '&password=' + password;
Debug tips
Did ajax send all required inputs to PHP (you can inspect this from browser developer tool)
Did php receive all required inputs (you could var_dump($_POST)
Did php connect to mysql successfully
Did ajax receive data from PHP (use alert or console.log)
try this, and if you get error state what it is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#loginForm").submit(function(){
if (username == ' ' || password == ' '){
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "php/login-action.php",
data: $(this).serialize(),
success: function(result){
alert('sucess'); //window.location="#report_page";
}
});
}
return false;
});
});
</script>

Ajax Login return modified headers error [duplicate]

This question already has answers here:
How to fix "Headers already sent" error in PHP
(11 answers)
Closed 9 years ago.
I am using wordpress as my base and made a custom login form.
ajax:
(function ( $ ) {
jQuery(document).ready(function() {
$("#login_form").submit(function(event){
//check the username exists or not from ajax
jQuery.ajax({
type: 'POST',
url: my_ajax.ajaxurl,
data: $('#login_form').serialize(),
cache: false,
//dataType: 'json',
success: function(result) {
var result=trim(result);
if( result == 'success' ){
window.location='/my-dashboard';
} else {
$('#message').html(result);
}
console.log(result);
}
});
return false;
});
});
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
}( jQuery ));
login form:
<p id="message" style="color:red;"></p>
<form method="post" action="" id="login_form">
<div align="center">
<div >
Email : <input name="email" type="text" id="email" value="" />
</div>
<div style="margin-top:5px" >
Password :
<input name="password" type="password" id="password" value="" />
</div>
<div class="buttondiv">
<input type="hidden" name="action" value="my_ajax_callback" />
<input type="hidden" name="func" value="check_login" />
<input name="submit" type="submit" id="submit" value="Login" style="margin-left:-10px; height:23px" /> <span id="msgbox" style="display:none"></span>
</div>
</div>
</form>
functions.php
// Ajax
add_action( 'wp_ajax_nopriv_my_ajax_callback', 'my_ajax_callback' );
add_action( 'wp_ajax_my_ajax_callback', 'my_ajax_callback' );
// Your Login function
function check_login( $params ){
require_once('lib/hash.php');
$session = new SC_Session;
// now you can use $session here
$message=array();
if(isset($_POST['email']) && !empty($_POST['email'])){
mysqli_real_escape_string($mysqli, $params['email']);
}else{
$message[]='Please enter email';
}
if(isset($_POST['password']) && !empty($_POST['password'])){
$password= mysqli_real_escape_string($mysqli, $params['password']);
}else{
$message[]='Please enter password';
}
$countError=count($message);
if($countError > 0){
for($i=0;$i<$countError;$i++){
echo ucwords($message[$i]).'<br/><br/>';
}
} else {
$hc=$mysqli->query("SELECT password FROM %table% email='".$email."' AND active=1");
while($hp = $hc->fetch_object()) {
$stored_hash = $hp->password;
}
$hasherd = new PasswordHash(8, false);
$check = $hasherd->CheckPassword($password, $stored_hash);
if($check) {
//now validating the username and password
$result=$mysqli->query("SELECT id, first_name, last_name, zip, email, password FROM %table% WHERE email='".$email."' AND active=1");
while($row = $result->fetch_object()) {
//if username exists
if($result->num_rows > 0)
{
$date = date('Y-m-d h:i:s');
$update_sql = $mysqli->query("UPDATE %table% SET last_login='".$date."'");
$firstname = $row->first_name;
$lastname = $row->last_name;
$zip = $row->zip;
$user_id = $row->id;
$sex = $row->sex;
$session->set_userdata( 'user_id', $user_id );
$session->set_userdata( 'email', $email );
$session->set_userdata( 'firstname', $firstname );
$session->set_userdata( 'lastname', $lastname );
$session->set_userdata( 'zip', $zip );
$session->set_userdata( 'sex', $sex );
}
}
echo ucwords('success');
//return $params;
} else{
echo ucwords('please enter correct user details');
}
}
}
/**
* Ajax Submit
*/
function my_ajax_callback() {
$response = call_user_func($_POST['func'], $_POST);
header( "Content-Type: application/json" );
echo json_encode($response);
exit;
}
The login currently works great, but whenever a error is thrown from $message it displays along with the header warnings.
Warning: Cannot modify header information - headers already sent by (output started at /%wordpresslocation%/wp-content/themes/%theme%/functions.php:77) in /%wordpresslocation%/wp-content/themes/%theme%/functions.php on line 86
null
ANSWER
I feel like an idiot, figured it out, I kept mixing php with javascript as I am proficient in php.
(function ( $ ) {
jQuery(document).ready(function() {
$('#message').slideUp();
$("#login_form").submit(function(event){
$('#message').slideUp();
//check the username exists or not from ajax
jQuery.ajax({
type: 'POST',
url: my_ajax.ajaxurl,
data: $('#login_form').serialize(),
dataType: 'json',
success: function(params) {
if( params == 'success' ){
$('#message').html(params).fadeIn();
document.location='/my-dashboard';
} else {
$('#message').html(params).fadeIn();
}
}
});
return false;
});
});
}( jQuery ));
and changed
echo ucwords('success');
//return $params;
} else{
echo ucwords('please enter correct user details');
}
to this
$params = 'success';
return $params;
}else{
$params = 'fail';
return $params;
and sent back the params
function check_login( $params ){
Thats because an error was printed (echo ucwords('please enter correct user details');)
Then, you try to set a header. That's not possible, headers always have to be set before anything else (that's how http works)
You will have to rewrite the parts that print text before the header is send. Also it doesn't send valid json so it wont work anyway

Getting all the content of table and append it using ajax with jquery

I made a simple sample on how to insert using AJAX and retrieving it then append it in a <div> after getting it. But I am having trouble on getting all the content of the table, it's returning a null values.
<div id="wrap-body">
<form action method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
jQuery:
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$('#info').append("<p> you are:"+data.username+"</p> <p> your message is:"+data.mesg);
}
});
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$return = $row['user_name'];
$return = $row['message'];
}
echo json_encode($return);
?>
Your while should create array and then do json_encode
Try below code
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message']
);
}
echo json_encode($data);
exit
Now write your javascript success handler as below
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$.each(data, function(i, item) {
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
});​
}
});
There are several issues you have to fix, but you have to start with returning the same type as expected by the ajax call:
$return = array()
if ($row = mysql_fetch_array($result))
{
$return['username'] = $row['user_name'];
$return['mesg'] = $row['message'];
}
echo json_encode($return);

Categories