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();}
}
});
Related
I am submitting a form using ajax. Then it is processed in PHP, and in the response i get the whole PHP/HTML code back. What is the right method to send back a "response" as variables from the PHP?
My JS
$.ajax({
url: 'index.php',
type: 'post',
data: {
"myInput" : $('#myInput').val(),
},
success: function(response) {
if(!alert(response)) {
// do something
}
}
});
and my PHP simply accepts the posted Input value and manipulates it:
if (isset($_POST["myInput"])) {
// doing something - and I want to send something back
}
Just echo and exit:
if (isset($_POST["myInput"]))
{
// doing something - and I want to send something back
exit('Success');
}
Then in your JS:
success: function(response) {
if (response == 'Success') {
// do something?
}
}
For example:
test.php single page html + php post handler
<?php
// Post Handler
if (count($_POST))
{
// do something with posted data
echo "You Posted: \r\n";
print_r($_POST);
exit();
}
// dummy data outside of the post handler, which will never be sent in response
echo "Test Page";
?>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.post('test.php', { "hello": "world" }, function(result) {
alert(result);
});
});
</script>
Outputs:
$.ajax({
url: 'index.php', // change your url or give conditional statement to print needed code
type: 'post',
data: {
"myInput" : $('#myInput').val(),
},
success: function(response) {
if(!alert(response)) {
// do something
}
}
});
I'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});
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";
}
});
I have an ajax function in jquery calling a php file to perform some operation on my database, but the result may vary. I want to output a different message whether it succeeded or not
i have this :
echo '<button id="remove_dir" onclick="removed('.$dir_id.')">remove directory</button>';
<script type="text/javascript">
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
if(rmd==0)
alert("deleted");
else
alert("not empty");
window.location.reload(true);
}
});
}
</script>
and this
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if(isset($_POST['dir_id'])){
$rmd=remove_dir($_POST['dir_id'],$bdd);
}
?>
my question is, how to return $rmd so in the $.ajax, i can alert the correct message ?
thank you for your answers
PHP
<?php
require('bdd_connect.php');
require('functions/file_operation.php');
if (isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
?>
JS
function removed(did){
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did}
}).done(function(rmd) {
if (rmd===0) {
alert("deleted");
}else{
alert("not empty");
window.location.reload(true);
}
});
}
i advice to use json or :
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo $rmd;
}
You need your php file to send something back, then you need the ajax call on the original page to behave based on the response.
php:
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
echo "{'rmd':$rmd}";
}
which will output one of two things: {"rmd": 0} or {"rmd": 1}
We can simulate this return on jsBin
Then use jquery to get the value and do something based on the response in our callback:
$.ajax({
type: "POST",
dataType: 'json',
url: "http://jsbin.com/iwokag/3",
success: function(data){
alert('rmd = ' + data.rmd)
}
});
View the code, then watch it run.
Only I didn't send any data here, my example page always returns the same response.
Just try echoing $rmd in your ajax file, and then watching the console (try console.log(rmd) in your ajax response block)
$.ajax({
type: "POST",
url: "rmdir.php",
data: {dir_id: did},
success: function(rmd){
console.log(rmd);
}
});
You can then act accordingly based on the response
Try echo the $rmd out in the php code, as an return to the ajax.
if(isset($_POST['dir_id'])){
$rmd=remove_dir($dir_id,$bdd);
//if $rmd = 1 alert('directory not empty');
//if $rmd = 0 alert('directory deleted');
echo $rmd;
}
Your "rmd" in success: function(rmd) should receive the callabck.
I wish to authenticate a user each time they click a button. If the user is logged out, and they attempt to click on a button, they are redirected home.
However the code after validate() is executes before the user is redirected home. In this example the popup always displays before the user is directed back home. How do I wait for the execution of validate() to complete before the rest of the event handler attempts to execute?
$("#main-display").on('click', 'button', function (event){
validate();
hello = window.open( '', '', "height = 100, width = 100");
hello.document.write('hello');
});
function validate(){
$.ajax({
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}
}
});
}
validate_user.php
<?php
session_start();
if(!isset($_SESSION['userId'])){
session_destroy();
$response['status'] = 'false';
}
else {
$response['status'] = 'true';
}
echo json_encode($response);
?>
EDIT
Thanks for the answers, however the popup still displays before the user is directed back even with the code bits of the most upvoted answers.
You could run your code in the ajax callback instead of directly after you start the request. What the below does is set up your validate function to take a single function parameter. This function is called after the AJAX has been run.
You could even use else on line 14 to only run the code if they are valid users.
$("#main-display").on('click', 'button', function (event){
validate(function(){
//some code here
});
});
function validate(callback){
$.ajax({
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}
callback();
}
});
}
This is flexible as it allows validate to be used in different contexts.
Use jQuery's Deferred objects, which are encapsulated in each jqXHR. Looks like
function validate(){
return $.ajax({ // <-- new return statement
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}
}
});
}
..and after you returning that jqXHR, continue like:
$("#main-display").on('click', 'button', function (event){
validate().done(function() {
// this code gets executed after the request successfully finished
});
});
This is a very nice and convinient technique to work with asyncronous processes. You can also catch more cases, like .fail() for any error case.
Have a further read:
http://api.jquery.com/category/deferred-object/
Use a callback function at the end of your success handler:
$("#main-display").on('click', 'button', function (event){
validate(function() {
//code to execute after validate AJAX is complete
});
});
function validate(cb){
$.ajax({
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}
cb();
}
});
}
This will execute the callback function after the AJAX request is complete, without locking up the UI in the meantime.
What about that:
$("#main-display").on('click', 'button', function (event){
validate();
});
function validate(){
$.ajax({
url: 'validate_user.php',
dataType: "json",
success: function(response) {
if(response.status == 'false') {
location.href = 'home.php';
}else{
//some code here
}
}
});
}
You can use preventDefault:
$("#main-display").click(function(event) {
event.preventDefault();
// do the rest of the code
});
Use Synchronous AJAX request dude. By default it will be Asynchronous.
you can do this by adding one parameter..
async : false,