I have an ajax call to one php script via jquery but it takes a lot of time to return results , So I would like to know how can I display results as its are being printed on my script. here just example of my php script:
<?php
// process.php
for($i = 0; $i <= 4; $i++){
echo json_encode(array("name" => $i) );
sleep(2); // this sleeps for 2 seconds
}
?>
Now with my jquery i am calling that page and have a form with id ajaxquery on page:
$("#ajaxquery").live( "submit" , function(){
var formdata = $(this).serialize();
$.ajax
({
type: "POST",
url: "process.php",
data: formdata,
dataType: "json",
success: function(data)
{
$("#success").html(data.name);
}
});
return false;
});
now this will output all results at same time after few seconds in div#success but how can i achieve it print that echo statements as soon process.php process it and then again wait 2 seconds and add next result in div success. thanks for any help.
You will have to setup a javascript timer on the client and call you php script every two seconds to get the new data. That data you can append for example with the jquery .append function.
The success function is called only when the $.ajax function gets a successful response from the server and that happens only when the PHP script finishes it's execution. You must change your logic, for example by making another ajax call after the first one finishes that "resume" the work server side
Related
title says it all, the way the script currently works is if its successful, it brings back a message back from my php code, i want it to also refresh the page after 3 seconds
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "postadvert.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#result').html('<div class="success"><img src="../../images/loading-blue.gif" width="25" /></div>');
},
success: function(data){
$('#result').html(data),
$('#result2').html('<meta http-equiv="refresh" content="3">'); // i added that doesn't working
}
});
});
});
A couple of things. First, you need a semicolon after your first line in the success function. Next, you can use the setTimeout function in javascript where you pass a function and a time to wait in milliseconds. Lastly, you can call the location.reload() to refresh the page.
success: function(data){
$('#result').html(data);
setTimeout(function(){location.reload();},3000);
}
Include the following in your success callback:
window.setTimeout(function() {
document.location.href = document.location.href;
}, 3000);
Assigning to document.location.href automagically causes the browser to load the URL so assigned; assigning its own value back to it therefore causes a refresh. The window.setTimeout() call tells the browser to wait three seconds, then run the function given as its first argument.
i have an ajax load request working in wordpress, but i would like to load the content from another page into the container div. at the moment it just passes the url in $dataToSend as a string?
jQuery(document).ready(function(){
var $dataToSend = "my-page.php";
var $testBtn = jQuery('#text-ajax-btn');
var $holdingCtn = jQuery('#my-holding-ctn');
$testBtn.click(function(){
jQuery.ajax({
type:'POST',
url: myAjax.ajaxurl,
data:{
action:'myAjax',
dataToSend:$dataToSend,
},
success: function(data,textStatus,XMLHttpRequest){
$holdingCtn.html("");
$holdingCtn.append(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
how can i pass an entire .php page through as the $dataTosend?
I do this all the time for wordpress, give me a sec to access my repository and I will show you example code.
I think problem is your my-page.php! I imagine you custom coded it. So it doesn't have necessary functions loaded.
put following code at the top of your my-page.php (this will help with 500 error you are getting)
require('../../../wp-load.php');
ajax part should look something like this:
//start ajax
$.ajax({
url: "http://localhost/wp-content/themes/theme/my-page.php",
type: "POST",
data: data,
cache: false,
success: function (data) {
console.dir(data);
}
})
If you want to load content from my-page.php file then you can load from the server side using
$data = file_get_contents('path/to/file/my-page.php'); // pass right path/url
Then, just echo the content from your function (registered ajax handler in WordPress using add_action) and in this case it should be
echo $data;
die(); // terminate the further execution
So, it should look something like
add_action( 'wp_ajax_myAjax', 'yourAjaxHandler' );
add_action( 'wp_ajax_nopriv_myAjax', 'yourAjaxHandler' );
function yourAjaxHandler(){
$data = file_get_contents('path/to/file/my-page.php');
die($data); // echo out the string and terminates execution
}
In your success callback, you can use
success: function(data){
jQuery('#my-holding-ctn').html(data);
}
Not sure if this is fully applicable, but the super easy way is just
$("#myDiv").load("myFile.php?foo=1&bar=2...");
I have a key_gen.php file that contains a function to generate a random key. When executed, the php file gives back one key (tested and it works).
In my javascript file I have a click event on a button (that works), something like this:
$('#kg_btn').click(function(){});
Then, inside my click event I have a functions:
var get_key = function(){
for(var i = 0; i < kg_quantity; i++) {
$.ajax ({
url: "../keygen/gen_rkey.php",
type: "GET",
datatype: "json",
success: function(data) {
var j_obj = JSON.parse(data);
//alert("Success!");
prs = j_obj.test;
console.log(prs);
//add_key();
},
error: function(error) {
alert("Error! Can't send the data");
}
}); //ajax call ends
}
}
When I run this function once (by setting up the "Kg_quantity" variable to 1), every time I click my button I get a correct behavior. The result is a different key on the console.log per click.
If I set up the "kg_quantity" to any other number than 1 (for example: 3,9,10), I do get the console.log messages back, but the number generated is the same.
I was hoping that by inserting the ajax object into a for-loop would execute the ajax call several times. I tried to put the ajax call within a prototype function, as well, but I get the same result.
Edit: I tried adding a closure (as Ross suggested), but I get the exact same result.
Thanks.
AJAX is asynchronous. Your loop will finish before the first AJAX response most likely.
I would restructure that so the success response from the AJAX call will trigger the next iteration. Or if you're lazy you can just set async:false:
$.ajax ({
url: "../keygen/gen_rkey.php",
type: "GET",
async: false,
....
Or even better, put the strain on the server and reduce the back-and-forth so you get all your keys in one response:
url: "../keygen/gen_rkey.php?qty=" + kg_quantity,
UPDATE: Async design method:
function getKeys(max,cur) {
cur = cur || 1;
if (cur == max) {
return;
}
$.ajax({
....
success(function(data) {
// do stuff....
// recursive iteration
getKeys(max,cur + 1);
}
});
}
getKeys(5);
I am getting data from php file through ajax. Based on the data I need to do some processing. I have put a few alerts in my code, and from that I realize that the code outside the ajax is being executed before ajax gets the data. I want the code to be done after the data is received from php file.
Code:
$(function () {
var originalData="";
$.ajax({
url: 'data.php',
data: "",
dataType: 'text',
success: function(data)
{
originalData=data;
alert("originalData 1 "+ originalData);
}
});
alert("originalData 2 "+ originalData);
...
Processing code
...
});
The sequence of alerts is:
First : "originalData 2"
Second : "originalData 1"
One option is that I include the Processing code inside the success function, but I cannot do it because later I want to put a logic such that I can have a buffer of data (atleast 4-5 stack deep) because I want user to get new data instantly after processing code for current data, rather than wait for the data to be retrieved through php.
Ajax uses asynchronous processing model, where once the request to server is sent the client will executing the next statements without waiting for the response to comeback. Once the server response either the success or failure callback will get called depending on the status of the response.
You need to put all your processing using the data from the ajax call in the success callback.
ex:
$.ajax({
....
}).done(function(data) {
//To all you post processing here
}).fail(function(){
//Do your error handling here
});
A ajax call doesn't stop the next line execution so you will have to do something like below:
$(function () {
var originalData="";
$.ajax({
url: 'data.php',
data: "",
dataType: 'text',
success: function(data)
{
originalData=data;
alert("originalData 1 "+ originalData);
myFunction();
}
});
function myfunction()
{
alert("originalData 2 "+ originalData);
...
Processing code
...
}
});
My AJAX calls from a page I wrote is hanging after an indeterminate number of calls. The page makes a request after a preset amount of time (currently 5 seconds) gets data from my server then waits the amount of time again. When I put the following as my AJAX Request:
myAjax = new Ajax.Request(
url,
{
method: 'get',
asynchronous: true,
url: url,
parameters: querystring,
onInteractive: document.getElementById('meh').innerHTML='Interactive',
onSuccess: processXML
});
The div with the id "meh" will get the word Interactive written to it, but the Success condition never gets executed (same if onSuccess is replaced with onComplete).
So why is my code doing this? Thanks.
Shouldn't the onInteractive event handler be a reference to a function?
as pb said, shouldn't it be
onInteractive: function(){
document.getElementById('meh').innerHTML='Interactive'
}