jQuery AJAX not updating its responses [duplicate] - php

This question already has answers here:
Prevent browser caching of AJAX call result
(21 answers)
Closed 2 years ago.
I have encountered a really weird situation. Im developing a software, to which I want to add a feature to confirm email, so basically, it sends an ajax request to my server and server responds with a key, this key will be also sent in the email within a link. This key is saved as a variable and then I add a setInterval, which runs a link, which by the key responds if the user has clicked the link or not. The data is stored in mysql. That everything works perfectly fine with one little issue. The AJAX responses do not update and just keep the old value although when I open the checking link in my browser the response is indeed different, does anybody have any thoughts what might by causing this issue?
$.ajax({
url: "http://...&em=" + email,
type: "GET",
success: function(rese){
if(rese === "E1") {
}else{
var checker = setInterval(function(){
$.ajax({
url: "http://...&key=" + rese,
type: "GET",
success: function(resee){
alert(resee);
}
});
}, 3000);
}
}
});
Edit - Server responses:
so, the data is updated in the moment, when user does click the link, the value changes to "yes", while normally, it would respond with just "no", but anyway, ajax keeps alerting me with no, even when i just have updated the value straight in the database

try adding a dynamic url to prevent cache:
$.ajax({
url: "http://...&em=" + email,
type: "GET",
cache: false,
success: function (rese) {
if (rese === "E1") {
} else {
var checker = setInterval(function () {
$.ajax({
url: "http://...&key=" + rese,
type: "GET",
cache: false,
success: function (resee) {
alert(resee);
}
});
}, 3000);
}
}
});

Related

PHP script not echoing data when called via AJAX

I have been staring at this problem for the past 2 hours and can't seem to fathom it, even after validating that everything loads correctly when scouring the console.
I basically have two sliders on my page which will eventually populate results in a table, every time I change my slider I send an array of two values to my AJAX script:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
The browser successfully finds update_results.php but it does not perform the logic on the page ( I assume it has found the page as the 404 error does not appear in my console. )
At this point in time the script is extremely bare-bones as I'm obviously trying to establish communication between both files:
<?php
$vals = $_GET['values'];
echo $vals;
In this case $vals is never echoed to the page, am I missing something in my AJAX? I know the values enter the function as alerted them out before attaching the PHP script.
Ajax Calls are suffering from Browser Cache. If your browser thinks, that he already knows the content of update.php, he will return the cached content, and not trigger the script. Therefore your
modified code might simply not get executed. (Therefore your insert query wasn't executed)
To ensure this is not happening in your case, it is always a good idea to pass a parameter (timestamp) to the script, so your browser thinks it's another outcome:
function update_results(values)
{
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php?random_parameter=" + (new Date().getTime());
data: { query : values },
cache: false,
success: function(data) {
// eventually some success callback
}
});
}
This will ensure that - at least - the browser cache is refreshed once per second for update_results.php, no matter what browser cache-settings or server-side cache advices are telling.
when Ajax is done, the success callback is triggered and the output of you php script is saved in data.
you can handle the data like this:
$.ajax({
type: "GET",
url: "./app/core/commands/update_results.php",
data: { query : values },
cache: false,
dataType: "text",
success: function(data) {
document.write( data )
}
});
PHP, running at server, is unaware of what happening at the front-end browser and it simply respond to ajax request as any other normal http request. So the failure of SQL query has nothing to do with javascript, which only responsible for sending ajax request and receiving and handling the response. I guess there's some errors in your php script.

PHP Cookies returning empty from jQuery/Ajax call

I have a domain (example.com) that sets a cookie using PHP like so:
$source = 123;
setcookie("source", $source, time()+3600, '/', ".example.com");
I want to share this cookie across sub-domains. When I navigate to "sub.example.com/index.php" and run the following PHP code:
echo $_COOKIE['source'];
...I get the correct output: 123. Good!
The problem I have is that when I make an ajax call using jQuery to "sub.example.com", the cookie doesn't output. It's empty.
$.ajax({
type: "POST",
url: 'http://sub.example.com/index.php',
dataType: "text",
error: function(jqXHR,textStatus,errorThrown) {
},
success: function() {
// DOES SOMETHING
}
});
Is there something I don't know about ajax and cookies across subdomains?
(I'm aware the above Ajax call doesn't do anything. In my real-life code, the page on the sub-domain writes the COOKIE value to a database. When I load the page directly in my browser, the database is correctly updated. When I load the page from ajax, the database entry is updated but all values are empty.)
In the end, the problem was the ajax call. Because it was crossdomain (or across subdomains), the answer was in the xhrFields param (http://api.jquery.com/jQuery.ajax/).
$.ajax({
type: "POST",
url: 'http://sub.example.com/index.php',
dataType: "text",
xhrFields: {
withCredentials: true
}
error: function(jqXHR,textStatus,errorThrown) {
},
success: function() {
// DOES SOMETHING
}
});

Optimize ajax synchronously calls

I have some ajax script that fire off about 250 synchronous PHP calls . This is my script
$(document).ready(function(){
$("#generate").html("<div class='modal'><p>Initializing...</p></div>");
$.ajax({
url:'/fetch around 250 url from database.php',
async:false,
dataType: 'json',
success: function(data){
$.each(data,function(key,val){
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
saveimage(val.url);
}
$("#generate").html("<div class='modal'><p>done</p></div>");
finalcreate();
},
});
});
function saveimage(){
$.ajax({
url: 'do some php work.php',
async: false,
});
}
function finalcreate(){
$.ajax({
url: 'do some php work.php',
async: false,
});
}
In the first part script fetch more than 250 urls from database and for every url script do some php calculation using another ajax call. when the loop ends script do final ajax call.
When i run this programe in firefox, it run successfully for only 40 urls, then browser shows dialog box with option of whether user want to stop this script or not, if user want to run this script then the script run again for next 40 urls , same proccess occure till the end.
How i can optimize this script, i dont want browser show option to stop this script. Please help.
Thanks
Try this:
function nextrequest() {
if (requests.length == 0) {
$("#generate").html("<div class='modal'><p>done</p></div>");
finalcreate();
return;
}
var val = requests.pop();
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
saveimage(val.url);
}
var requests = [];
$(document).ready(function(){
$("#generate").html("<div class='modal'><p>Initializing...</p></div>");
$.ajax({
url:'/fetch around 250 url from database.php',
dataType: 'json',
success: function(data){
requests = data;
nextrequest();
},
});
});
function saveimage(){
$.ajax({
url: 'do some php work.php',
success: function(data) {
// do something...
nextrequest();
}
});
}
function finalcreate(){
$.ajax({
url: 'do some php work.php',
});
}
You store all the URLs in a global variable, and everytime a request is done, you get the next one, until all of them are consumed, (requests.length == 0), you call the final request.
This way the user can still do something else on the page, and you can display progress everytime a request is done. Also, a good thing is that you can make 2 calls at once, or more, to make the process faster.
Ajax call needs much time to complete, as it communicates with remote server. The slowest thing there is a query to the server. You should send one batch request with all data needed to the server, that should separate the data and handle it. Everything should be completed about 250 times faster.
make some time interval for each ajax request
success: function(data){
$.each(data,function(key,val){
$("#generate").html("<div class='modal'><p>Fetching "+val.url+"</p></div>");
setTimeout(saveimage(val.url),3000);
}

How should I check if record exists or not using jQuery Validate Plugin?

I am using jQuery Validate Plugin found from below URL
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
I just wanted to make a validation rule to check if the record exists in database or not. I also made ajax script like blow & added it using $.validator.addMethod but it is not working. can someone please suggest how to do this ?
$.validator.addMethod("check_exists", function(value) {
$.ajax({
type: "POST",
url: "xyz.com/check_exists.php",
data: $( "#frmEdit" ).serialize(),
success: function(result){
if(result=="exists")
return false;
else
return true;
},
});
}, 'This record is already exists');
Validation plugin has a built in remote option you provide a url to and the request will be made to server from within plugin. For what you are doing there is no need to creat a whole new method
http://docs.jquery.com/Plugins/Validation/Methods/remote#options
The problem you are running into is that (1) the AJAX call is asynchronous so the method is returning before the AJAX call completes and (2) the return statements within the callback handler return from the handler not the validation function. The simplest way to fix this is to use the remote validation method. If you want to do it yourself, you need to have the AJAX call be synchronous (async: false) and capture the result into a variable that is returned from the function.
$.validator.addMethod("check_exists", function(value) {
var status;
$.ajax({
type: "POST",
async: false,
url: "xyz.com/check_exists.php",
data: $( "#frmEdit" ).serialize(),
success: function(result){
status = result=="exists";
},
});
return status;
}, 'This record is already exists');

Jquery getting information from php

I need to get information from a php file and put the information in jquery and i also need to know if the information has changed
Extremely vague question.
If you are putting the information into jquery:
$.ajax({
type: "GET",
url: "PHPFILE.php",
data: "data="+data,
success: function(data){ /* called when request to barge.php completes */
//SET VARIABLES
);
},
});
PHP:
if ($_GET["data"] != WHATEVER YOU ARE CHECKING HAS CHANGED)
{
echo "new stuff";
}
For checking if the php page has changed, pass the current data in and do a comparison.

Categories