Page reload not working when the page was called by AJAX - php

Let's say this is my AJAX
function call_page(id)
{
$.ajax({
type: "POST",
url: "call_me.php",
data: "id=" + id,
success: function(msg){ }
});
}
call_me.php was successfully called.
Let's say this is my call_me.php content
<?php
$var = $_POST['id'];
if(empty($var))
{
header("location: call_me.php?id=101");
}
else
{
do something...
}
?>
Assuming that the first condition 'if(empty($var))' is always satisfied.
The page must reload and the go to the else statement.
But this is not happening. I guess the page isn't reloading.
How can I correct this problem?
Thanks!

Try this
<?php
$var = $_GET['id'];
if(empty($var))
{
// here flag for redirection is set
echo 1;
}
else
{
do something...
}
?>
In AJAX:
$.ajax({
type: "POST",
url: "call_me.php",
data: "id=" + id,
success: function(msg){
// checking the response is for redirection
if(msg == 1)
// javascript code for redirecting to callme.php
window.location = "call_me.php?id=101";
}
});

Related

jquery - how to create condition in success function

I want to create jquery ajax success function based resp from logout.php. If users not sign in,It redirect bring them to login page.,but it's not working as I'm expected,no event occur when user is logged or not.So, what is wrong with my ajax function?
logout.php
<?php
if( !$user->is_logged ) {
echo 'true';
}else{
echo 'false';
}
?>
jquery function in index.html
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
if(resp =='true'){
document.location = '../login_test.html';
}
if(resp=='false'){
alert('U are logged');
}
}
});
});
Change some errors and made it to better view:
PHP:
<?php
header('Content-Type: application/json');
if( !$user->is_logged ) {
echo json_encode(array('status' => 'ok'));
}else{
echo json_encode(array('status' => 'bad'));
}
?>
Javascript:
$(function(){
$.ajax({
type: 'GET',
url: "logout.php",
success: function(resp){
var state = JSON.parse(resp).status
if(state == 'ok'){
document.location.href = '/login_test.html';
}
else{
alert('U are logged');
}
}
});
});
If you have no alert, and have no redirect - you have not .success callback, and problem one level above your condition. In that case show us your errors from js-dev-console from browser.

ajax like/unlike button not switching back

I am trying to make a like button on a page and cant seem to get it to work right. Basically there are three function that use ajax to send the data to a php page that updates the database. Ive checked the db and all three update correctly. If the user doesnt originally like and clicks, it correctly shows the unlike button but then, if you click unlike it doesnt switch back (although it does update the database).
Is this the correct way to set this up? Im pretty new to ajax and am not sure if this is the right approach. THanks in advance
Steve
public function likesScript($p){?>
<script>
//display list of people who like this
function getLikes(){
$.ajax({
type: "POST",
url: "likelist.php",
data: { p: "<?php echo $_GET['p']?>"}
}).success(function(res) {
//check to see if current user likes this
if($('li#<?PHP echo $_SESSION['userId']; ?>').length){
$(".Like").addClass('hidden');
$(".UnLike").removeClass('hidden');
}
else{
$(".UnLike").addClass('hidden');
$(".Like").removeClass('hidden');
}
$("#likedBy").append(res);
console.log(res);
});
}
function removeLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "0" }
})
getLikes();
return false;
}
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" }
})
getLikes();
return false;
}
$(document).ready(function() { getLikes();
$(".UnLike").live('click',removeLike);
$(".Like").live('click',addLike);
});
</script>
likelist.php:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/view.class.php';
$view = new view();
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$p = $_POST['p'];
$view->printLikes($profile->getLikes($p));
}
likedata.php:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$liker = $_POST['arg1'];
$likee = $_POST['arg2'];
$likeYesNo = $_POST['arg3'];
$profile->insertLikes($liker, $likee, $likeYesNo);
}
?>
AJAX is ayshcronous so the getLikes functions will fire before the AJAX is completed in both addLike and removeLike. You definitely need to put getLikes into the success callback of $.ajax so it doesn't retrieve data that may not have been updated
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" },
success: getLikes
})
}
Ok... this is what I have learned from using ajax repeat calls...
IE hates them and sometimes they just don't work the way they should.
Try this
function addLike() {
var randnum = Math.floor(Math.random()*1001); //Add This Here on all Ajax Calls
$.ajax({
type: "POST",
url: "likedata.php",
cache: false, //Add This Here - Assists in helping Browsers not to cache the Ajax call
data: yourdata + '&random=' + randnum, // Add this to the end of your data you are passing along *'&random=' + randnum,*
success: function() {
getLikes();
}
})
}
Adding a random piece of data causes the browsers to think its a new call.
Also, the random=randnum wont effect anything on the php side.

jQuery AJAX return variable + value possible?

I'm submitting a form via jQuery.ajax()
Now my PHP script is checking if a specific input field is empty, example:
$is_error = $user->is_error;
if($is_error !=0)
{
echo $is_error;
}
Back to my jQuery.ajax() , I'd like to check if the value of $error was true or not, within the sucess: part of the jQuery.ajax() call.
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(data)
{
// show response from the php script if there is an error message
// like:
// if(is_error) {show specific error message}
// else {show everything positive message}
}
});
Is it possible to check the PHP variable's value in there? Like if/else ?
Best regards!
if($_POST['name'] == "")
{
$error = 1;
}
else
{
$error = 0;
}
echo $error;
This code will echo the value.
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(data)
{
// show response from the php script if $error == 0 or $error == 1.
if(data==1)
....
}
});
Then you check what is the returned value.
With your variable data, you can return values from PHP. And after in your scope success you can check.
You have to echo the error so that it can be returned as data.. The ajax only returns what has been created in html..
In instances like this I would use the following:
if($_POST['name'] == "")
{
$error = 1;
}
else
{
$error = 0;
}
echo $error;
jQuery.ajax({
type: "POST",
url: "edit.php",
data: jQuery("#idForm").serialize(),
success: function(response)
{
if(response == 1){
alert('Error');
}else{
alert('No error');
}
}
});
i think you should try the following in php script
echo $error;
and then in jquery.ajax() do
success: function(data){
//data is $error
}

Can't get this AJAX request to work

So basically here is my script, which is in index.php -
<script type="text/javascript">
setInterval(function() {
jQuery.ajax({
url: "ajaxChecker.php",
context: document.body
}).done(function(response) {
if(response == true) {
location.reload(true);
}
});
}, 1000 * 60);
</script>
It should each minute send request to balanceChecker.php for receiving data, and then check wether it's true reload page otherwise do nothing.
Here is ajaxChecker.php file
<?php
return true;
?>
but it doesn't work. Any ideas?
EDITED the AJAX Part, doesn't work now also -
setInterval(function() {
jQuery.ajax({
url: "ajaxChecker.php",
context: document.body,
success: function(response) {
if(response == "true") {
location.reload(true);
}
}
});
}, 1000 * 10);
and in ajaxChecker.php file replaced return to echo and true to "true".
in your php file write
<?php
echo true;//can also use echo 1
?>
Because pages can't return anything
You doesn't output anything by your php.
Should be:
<?php echo "true";?>
and in js:
if(response == "true") {
Also I would reccomend to not include PHP closing tag: ?> to avoid unnecessary new lines and to prevent sending header info:
<?php
echo "true";
you can use "success" instead of .done:
var str="the data you want to send to ajaxChecker.php";
$.ajax({
type: "POST",
url: "ajaxChecker.php",
data: str,
success: function(msg) {
// msg is the return you receive from ajaxChecker.php
if(msg==1) {location.reload();}
}
});

how can i create a success back function?

$(function() {
$(".follow").click(function(){
var element = $(this);
var I = element.attr("id");
var info = 'id=' + I;
$.ajax({
type: "POST",
url: "listen.php",
data: info,
success: function(){}
});
$("#follow"+I).hide(); ///showing the remove button after the data has been entered
$("#remove"+I).show();
return false;
});
});
The PHP file listen.php
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
$registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')");
?>
what I want to do is when I click the follow button, I want to check if the data has been entered into the database, before showing the remove button, basically checking on the background.
mysql_query will return TRUE or FALSE. You can echo that from the PHP script, and have the ajax call read it.
listen.php:
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
$registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')");
echo json_encode(array('response'=>$registerlistener));
?>
In your JavaScript:
$.ajax({
type: "POST",
url: "listen.php",
data: info,
dataType: 'json',
success: function(data){
if(data.response){
// mysql_query returned TRUE
$("#follow"+I).hide();
$("#remove"+I).show();
}
else{
// FALSE
}
}
});
If you want, you can use the $.post shorthand:
$.post('listen.php', info, function(data){
if(data.response){
// mysql_query returned TRUE
$("#follow"+I).hide();
$("#remove"+I).show();
}
else{
// FALSE
}
}, 'json');
Put the code you want to execute inside your 'success' callback function.
$.ajax({
type: "POST",
url: "listen.php",
data: info,
success: function(){
$("#follow"+I).hide();
$("#remove"+I).show();
}
});
do it like this:
listen.php
<?php session_start();
include_once ('includes/connect.php');
$id = $_POST['id'];
$follower = $_SESSION['user_id'];
if($registerlistener = mysql_query("INSERT INTO relationships (leader, listener) VALUES('".$id."', '".$follower."')")):
echo "true";
else:
echo "false";
endif;
?>
pass parameter in success function, example "msg". whatever was echo'ed in listen.php will be in the msg variable now
success: function(msg){}
if(msg == "true")
{
//do something
}
else
{
//show error message
}
});

Categories