AJAX Success function never true - php

I don't know why my success function isn't working. I mean although it passes the JSON data to the PHP file and changes the password.
// this is the id of the form
$("#password_form").submit(function(e) {
e.preventDefault();
$(".verify-user-loader").addClass("force-display-block");
password = $("input#password-reset").val();
url = 'reset-pass.php';
$.ajax({
type : 'POST',
url : url,
dataType : 'json',
data : {
cardnumber: <?php echo '\''.$cardnumber.'\''; ?>,
act_token: <?php echo '\''.$activationToken.'\''; ?>,
password: password
},
success : function(success){
alert("success");
},
error : function(request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
}
});
});
This file works as expected, it changes the password using the POST data
reset-pass.php
include_once '/../login/user.class.php';
$activationToken = $_POST['act_token'];
$cardnumber = $_POST['cardnumber'];
$password = $_POST['password'];
$user = new User();
$verifyToken = $user->verifyToken( $activationToken, $cardnumber );
if ($verifyToken['status'] === true) {
$tokenStatus = "inactive";
$user->signUp( $cardnumber, $password );
$user->changeTokenStatus( $cardnumber, $tokenStatus );
$success = true;
return $success;
}else{
print_r($verifyToken);
}

You should use echo instead of return, because when you work without function you should need to use echo.
So the code will be
echo true; // or you can write echo $success = true;
exit(); // exit is use to stop further processing of code.

1 ) you need to echo $success; instead of return $success;
Ajax response should be any browser out put (i.e like html or echo or print_r these are browser output ) . instead of return .
2) simple add data like this
........
data : {
cardnumber: '<?php echo $cardnumber; ?>',
act_token: '<?php echo $activationToken; ?>',
password: password
},
........

Related

How to return value from second page to jquery page

I need to get the value from second page member_verify.php in my jQuery resonse which is in first page. I need to get $age value in first page. Now message displays correctly.
I need to get the age which I fetched in member_verify.php with $age=$fet['Age'];:
function memberid(em) {
var memid=$("#memid").val();
$.ajax({
type:'post',
url:'member_verify.php',
data:{memid: memid},
success:function(msg){
if (msg.length> 0) {
alert(msg);
}
else{
$("#disableDiv :input").attr("disabled", false);
}
}
});
}
member_verify.php
<?php
$s=$_POST['memid'];
include "common/config.php";
$echeck="select * from insmemberdetails where LoginId='".$_POST['memid']."'";
$echk=mysqli_query($conn,$echeck);
$fet=mysqli_fetch_assoc($echk);
$age=$fet['Age'];
$ecount=mysqli_num_rows($echk);
if($ecount=='0')
{
echo "Member Id Not exists";
}else
{
$fet=mysqli_fetch_assoc($echk);
$verify=$fet['verify'];
if($verify=='0')
echo "Member Id not Verified";
}
?>
Change your member_verify.php to get age in ajax response otherwise you will get validation message.
<?php
$s=$_POST['memid'];
include "common/config.php";
$echeck="select * from insmemberdetails where LoginId='".$s."'";
$echk=mysqli_query($conn,$echeck);
$ecount=mysqli_num_rows($echk);
if($ecount <= 0)
{
echo "Member Id Not exists";
}
else
{
$fet=mysqli_fetch_assoc($echk);
$age=$fet['Age'];
$verify=$fet['verify'];
if($verify==0)
{
echo "Member Id not Verified";
}
else
{
echo $age;
}
}
?>
And below is your JS file.
function memberid(em) {
var memid=$("#memid").val();
$.ajax({
type:'post',
url:'member_verify.php',
data:{memid: memid},
success:function(data){
console.log(data);
}
else{
$("#disableDiv :input").attr("disabled", false);
}
}
});
}
Hope this will help you.
May be you could know something about json.
php code:
if($ecount!=0){
echo json_encode(array(
errno: 0,
data: $age
));
}else{
echo json_encode(array(
errno: 500,
errmsg: 'your error info'
));
}
your js here:
$.ajax({
// add this option
dataType: 'json'
})
And if you try that :
<?php
$age=$fet['Age'];
$champAgeExist = isset($age);
if (champAgeExist == true) {
echo $age
?>

Reload a function without reloading the page

I want to callout a function without the page is reloading.
I know that this is possible with AJAX but i don't know how it works with calling a function.
I want to put a timer so it will reload the function every 3 seconds, so the users doesnt need to reload the page everytime to see if there is a new message.
$object = new Messages();
$object->ShowMessage($nick);
ShowMessage(); is the function that i want to call out every 3 seconds.
Full code :
public function ShowMessage() {
$st = $this->db->prepare("SELECT * FROM bericht");
$st->execute();
if($st->rowCount() == 0){
echo 'There is no message jet!';
}
foreach ($st as $bericht){
$uid = $bericht['uid'];
$nick = $this->db->prepare("SELECT * FROM users WHERE id=?");
$nick->bindParam(1, $uid);
$nick->execute();
foreach($nick as $name) {
$image = $name['foto'];
if($image == 'nophoto.jpg'){
echo '<img src="image/nophoto.jpg" width="60px" height="30px">';
} else {
echo '<img src="image/'; echo $image.'"'; echo ' width="60px" height="30px">';
}
echo json_encode($name['name']) .': ';
echo json_encode($bericht['message']).' <br> ';
}
}
}
You can do that with ajax. In order to do that, you need to implement ajax client function on frontend and a handler for processing ajax request. In frontend you can use jquery for ajax operations;
setInterval(function() {
$.get( "handler.php", function( data ) {
// You can use data. It is in json format.
// Ex: alert(data.message) . "message" is one of the
// fields of returned array in php handler file
});
}, 3000);
handler.php
<?php
$object = new Messages();
$result = $object->ShowMessage($nick);
// I assume this returns array.
// Ex: array("type" => "error", "message" => "Error occured on feed");
echo json_encode($result);
?>
Update: If you do not want to use json data
Update your code like below. Only use echo, you do not need to return json data.
public function ShowMessage() {
$st = $this->db->prepare("SELECT * FROM bericht");
$st->execute();
if($st->rowCount() == 0){
echo 'There is no message jet!';
}
foreach ($st as $bericht){
$uid = $bericht['uid'];
$nick = $this->db->prepare("SELECT * FROM users WHERE id=?");
$nick->bindParam(1, $uid);
$nick->execute();
foreach($nick as $name) {
$image = $name['foto'];
if($image == 'nophoto.jpg'){
echo '<img src="image/nophoto.jpg" width="60px" height="30px">';
} else {
echo '<img src="image/'; echo $image.'"'; echo ' width="60px" height="30px">';
}
echo $name['name'] .': ';
echo $bericht['message'].' <br> ';
}
}
}
and in js;
setInterval(function() {
$.get( "handler.php", function( data ) {
// alert(data);
});
}, 3000);
You need to do that integrating javascript to your php code.
Using jquery, you can take a look at $.post function. You can rise the event with the javascript function window.setInterval(yourFunction(),3000)
You also need to create a php page that will reply to the Ajax request, that will be passed as a parameter to the $.post
Just call that script via ajax:
.html:
setInterval(function(){
$.ajax({
url: "showMessageScript.php",
type: "post",
data: {nick: $("#nick").val(), token: <?php echo $_SESSION['token']; ?>},
success: function(jsonData){
$('#display').text(jsonData['message']);
}
});
},
3000);
showMessageScript.php:
function showMessage($nick) {
$object = new Messages();
$object->ShowMessage($nick);
echo json_encode(array('message': 'Your message is here'));
}
// check if authorized to do some action
if (!empty($_SESSION['token']) && $_SESSION['token'] == $_POST['token'] && !empty($_POST['nick'])) {
showMessage($nick);
} else {
echo json_encode(array('message': 'not authorized'));
}

ajax check user logged in before running script

i have a pretty basic voting system i have implemented on my site. using the following ajax when a user clicks on the link there vote is added to the database and the vote is updated +1.
this all works fine but i would like to check if the user is logged in before allowing them to vote if there not display an error pop up or redirect to the login page (eventually i will display a lightbox popup asking for them to login or register.
<script type="text/javascript">
$(document).ready(function() {
$(".voteup a").click(function() {
var ID = <?php echo $moviedetails['id'] ?>
//$("#vote").text();
var rating = <?php echo $vote['vote_up'] ?>
var queryString = 'id=' + ID + '&vote=' + rating;
$("#voteup").text (rating + 1);
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(html) {
$("#votethanks").html('Thanks');
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
});
});
});
</script>
and vote_up.php
<?php
require_once("header.php");
$data = $_POST['id'];
$updatevote = "UPDATE `vote` SET `vote_up` = vote_up +1 WHERE `movie_id` = '$data'";
mysqli_query($con, $updatevote);
?>
i have tried
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
echo "<script>alert('Please login.')</script>";
}
else { //then the javascript
but it just checks the users logged in on page load, if there not it displays the please login error, but i need it to do this onclick of the javascript.
any help appreciated
thanks
lee
You can consider doing the check with PHP in the vote_up.php and check the response in your ajax. Something like this:
$.ajax({
type: "POST",
url: "vote_up.php",
data: queryString,
cache: false,
success: function(result) {
if (result.error) {
alert(result.msg);
} else {
$("#votethanks").html(result.msg);
$("#votethanks").slideDown(200).delay(2000).fadeOut(2000);
}
}
});
in your vote_up.php:
<?php
if (!(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '')) {
// User is not logged in!
$result = array(
'error' => true,
'msg' => 'Please login first!'
);
} else {
// write the needed code to save the vote to db here
$result = array(
'error' => false,
'msg' => 'Thanks!'
);
}
// Return JSON to ajax call
header('Content-type: application/json');
echo json_encode($result);
Why not use your PHP to insert into a authenticated variable, just as you do with vote and ID?
For example:
var authenticated = <?php !(isset($_SESSION['sess_user_id']) && $_SESSION['sess_user_id'] != '') ?>
Note: Completely untested. I just copied and pasted the php code from your "I have tried..."
Does this help?
Add a boolean. Every time the user clicks on the voting, send an ajax call to check if the user is logged in.
$(document).ready(function()
{
$(".voteup a").click(function()
{
var the_user_is_logged_in;
the_user_is_logged_in = checkLoggedIn();
if the_user_is_logged_in{
// do ajax call
}
else{
alert('Please log in!')
}
}
}
function checkLoggedIn(){
$.get('getsession.php', function (data) {
return data;
});
And in getsession.php you should write
<?php
session_start();
print json_encode($_SESSION);
I didn't try the code, but it should work.
This is what worked for me in the end. I am only sharing this to help someone who my encounter the same problem and end up with a migraine.
The ajax script:
<script type="text/javascript">
function review_likes ( addresscommentid )
{ $.ajax( { type : "POST",
async : false,
data : { "txt_sessionid" : addresscommentid },
url : "functions/review_likes.php",
beforeSend: function() {
// checking if user is logged in with beforeSend
<?php if (!(isset($_SESSION['signed_in_uid']) &&
$_SESSION['signed_in_uid']
!= '')) { ?>
$(window.location.href = 'admin/index-signin.php');
<?php } ?>
},
success : function ( sessionid )
{
$('#reviewlikes').removeClass('like-action');
$('#reviewlikes').load(document.URL + ' #reviewlikes');
},
error : function ( xhr )
{
alert( "You are not Logged in" );
}
});
return false;
}
</script>
On the review_likes.php page header:
<?php
$kj_authorizedUsers = "";
$kj_restrictGoTo = "../admin/index.php";
if (!((isset($_SESSION['kj_username'])) &&
(isAuthorized("",$kj_authorizedUsers,
$_SESSION['kj_username'], $_SESSION['kj_authorized'])))) {
$kj_qsChar = "?";
$kj_referrer = $_SERVER['PHP_SELF'];
if (strpos($kj_restrictGoTo, "?")) $kj_qsChar = "&";
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
$kj_referrer .= "?" . $_SERVER['QUERY_STRING'];
$kj_restrictGoTo = $kj_restrictGoTo. $kj_qsChar . "accesscheck=" .
urlencode($MM_referrer);
header("Location: ". $kj_restrictGoTo);
exit;
}
?>
The above code is a bit overkill, but it helps to get the current URL and redirect the user to the requesting page after successful login.

Ajax call doesn't return data after echoed

The ajax call successfully update the record but doesn't return the string of echo. This script was working before but might be because of some upgrade it stops working. It is working fine on my local system but when I move it to bluehost server then it does not work.
Here is my Ajax call:
// call to ajax script to update site
function autopost_update_site() {
// get base directory url
var baseDir = jQuery('#baseDir').val();
var id = jQuery('#site_id').val();
var site_name = jQuery('#site_name').val();
var site_url = jQuery('#site_url').val();
var is_active;
if ( jQuery('#active_radio').is(':checked') ){
is_active = '1';
} else {
is_active = '0';
}
var username = jQuery('#login_username').val();
var login_pass = jQuery('#login_pass').val();
// call to ajax script to update script
jQuery.ajax( {
type: "POST",
url: baseDir + "/autopost_ajax_actions.php",
data: "id=" + id + "&site_name=" + site_name + "&site_url=" + site_url + "&is_active="+ is_active + "&username=" + username + "&login_pass="+login_pass +"&action=update_site",
beforeSend: function() {
jQuery('#update_site_button').attr("disabled", true);
// shortcode edit button
jQuery('#update_site_button').html('Updating...');
// admin page edit button
jQuery('#update_site_button').val('Updating...');
},
complete: function() {
jQuery('#update_site_button').attr("disabled", false);
// shortcode edit button
jQuery('#update_site_button').html('Update');
// admin page edit button
jQuery('#update_site_button').val('Update');
},
success: function(data) {
alert("Result: " + data); // NOTHING IS HAPPENING HERE, NO ALERT DATA
if (jQuery.trim(data) === "success") {
alert("Site updated.");
// refresh page
window.setTimeout('location.reload()', 200);
} else {
alert("Some error occured, Please try again.");
}
}
});
}
Here is my custom php script for ajax actions:
// update site
if ( $_POST['action'] == 'update_site' && isset ($_POST['id']) ) {
// collect site data
$site_name = $wpdb->escape($_POST['site_name']);
$site_id = intval($wpdb->escape($_POST['id']));
$site_url = $wpdb->escape($_POST['site_url']);
$username = $wpdb->escape($_POST['username']);
$login_pass = $wpdb->escape($_POST['login_pass']);
$is_active = $wpdb->escape($_POST['is_active']);
$query = $wpdb->prepare("UPDATE " . $autopost_sites_table_name . " SET site_name = %s, site_url = %s, username = %s, login_pass = %s, is_active = %s WHERE id = %s", $site_name, $site_url, $username, $login_pass, $is_active, $site_id);
#$log->LogDebug($query);
// execute query
$result = $wpdb->query($query);
#$log->LogDebug($result);
if ( $result !== FALSE || $result !== 0) {
// return success
$response = "success";
#$log->LogDebug($response);
echo $response; // THIS RESPONSE IS NOT SHOWING ON AJAX SUCCESS
} else {
$log->LogError("Failed to update site with ID: " . $_POST['id']);
echo "Failed to update site.";
}
}
Can anyone tell me what is missing?
Change data as follows
data:{
id:id,
site_name:site_name,
site_url:site_url ,
is_active:is_active ,
username:username,
login_pass:login_pass,
action:"update_site"
}
As It is mentioned that the script is working great on local but not working on server. So it was some server issue and I was getting error for "Access-Control-Allow-Origin" in chrome network.
I just added
header('Access-Control-Allow-Origin: *');
to my ajax action script and it worked! Thanks
after
echo $response;
put
die();
See http://codex.wordpress.org/AJAX_in_Plugins
In the example it says:
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}

Jquery ajax parsing error for json

I am trying to send some data using php and jquery ajax using json datatype method.
Here is my code:
$("#username").on("keyup change keypress", function () {
var username = $("#username").val();
$.ajax
({
type: "POST", // method send from ajax to server
url: window.location.protocol + '//' + window.location.host + '/' + "admin/admins/user_exists",
data: {
username: username
},// Specifies data to be sent to the server
cache: false, // A Boolean value indicating whether the browser should cache the requested pages. Default is true
contentType: "application/json",
dataType: 'json', // The data type expected of the server response.
success: function (response_data_from_server) {
for (var key in response_data_from_server)
var result = response_data_from_server[key] + ""; // JSON parser
if (result == 'true') {
console.log("---------------- in true");
$("#username_alert").text("ERROR");
$('#username_alert').removeClass("alert-success");
$("#username_alert").css("visibility", "visible");
}
else {
if (result == 'false') {
console.log("---------------- in false");
$("#username_alert").text("NO ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').addClass("alert-success");
}
else {
if (result == 'empty') {
console.log("---------------- in empty");
$("#username_alert").text("ERROR");
$("#username_alert").css("visibility", "visible");
$('#username_alert').removeClass("alert-success");
}
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
and it always goes to an error function. The error that I receive is the following:
parsererror SyntaxError: Unexpected token  {}
My url location is correct and is indeed returning the correct json format. Here is my php code:
public function user_exists()
{
$username = $this->input->post("username");
$is_exists = "false";
$this->load->database();
if ($username != "")
{
$rows = $this->db->query("
SELECT * FROM `admins` WHERE `username` = '" . $username . "'
")->num_rows();
if ($rows > 0)
{
$is_exists = "true";
}
else
{
$is_exists = "false";
}
}
else
{
$is_exists = "empty";
}
$arr = array ('result' => $is_exists );
$response = json_encode($arr);
echo $response;
}
I've debugged it million times, the firebug sees the response as correct and expected json, however the client side seems to refuse to get it as a json respone, for what I believe.
Will appreciate any help!
...
header('Content-type: application/json');
echo $response;
Maybe you could use "header('Content-type: application/json');" before "echo"

Categories