jQuery ajax: Want to sequence the code process - ajax

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
...
}
});

Related

load mypage.php via ajax into a div in wordpress

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...");

jQuery $.ajax post show partial results

Is possible to get partial results and write to a div from a $.ajax post?
My js code
$('#submit').livequery('click', function(event) {
event.preventDefault();
$('#loading').show();
var myvar= $("#myvar").val();
$.ajax({
type: "POST",
url: "process.php",
cache: false,
data: ({'myvar':myvar}),
success: function(data){
$('#loading').hide();
$('#main_content').html(data);
},
});
return false;
});
The code from process.php
function send($string = "") {
echo $string;
echo str_pad('', 4096)."\n";
#ob_flush();
#flush();
}
for($i=1;$i<=10;$i++){
send($i);
sleep(5);
}
Is possible to show on #main_content the result like this:
show 1 -> wait -> show 2 -> wait .....
Right now i get all result after the process is made: 12345678910
PHP code is run on the server and, as such, cannot affect the client-side browser behavior like you are asking. The way to accomplish what you want is to pass all the information from PHP to your browser and handle the logic in jQuery or javascript. Send all of your information and store it in some variables/arrays and after your POST, split up the info and display it to the browser with a timeout callback like this:
setTimeout(function() {
// Do something after 5 seconds
}, 5000);

prevent redirection on submit to form

I have the following code I am using to submit my form to a processing script. the form gets submitted but I am getting redirected to the response html from the server. I want to stay on the same page and run the callback function inside success:
the response header is sending
location:http://url-I-am-Redirected-to-and-don't-want-to-be.html
I am working with third party and have no control over the server side code I am submitting to.
$('#go').click (function () {
$.ajax ( {
type: 'POST',
data: $('#newsletter form').serialize(),
url: $('#newsletter').attr('action'),
success: function(){
$('#image_container').hide (1000,
);
}
});
}
At the end of the click block add
return false

how can i show ajax-loading when i fetching some information from database?

i used jQuery with Ajax By this code it works fine
$.ajax({
type : 'POST',
url: 'http://localhost/msite/index.php/site/ajax',
data : catdata,
success : function (msg){
$('body').html(msg);
}
});
but i want to show the ajax-loading gif while fetching that information from database?
And , is that way secure Or i have to add some security to it?
$('body').html("<img src='spin.gif' />").fadeIn(100, function () {
$.ajax({
type: 'POST',
url: 'http://localhost/msite/index.php/site/ajax',
data: catdata,
success: function (msg) {
$('body').html(msg);
}
});
});
If you make your database query synchronous on the server then your Ajax will be spinning as long as the request is being processes, including a database query and server request/response roundtrip.
I believe you have to do this yourself within the jQuery. Create a hidden image on the page, call .show() just before calling the ajax command and be sure to call .hide() inside the complete event...
complete: function () {
$("#ticker").hide();
}
You can download a suitable image from ajaxload.info.

jQuery.ajax() sequential calls

Hey. I need some help with jQuery Ajax calls. In javascript I have to generste ajax calls to the controller, which retrieves a value from the model. I am then checking the value that is returned and making further ajax calls if necessary, say if the value reaches a particular threshold I can stop the ajax calls.
This requires ajax calls that need to be processes one after the other. I tried using async:false, but it freezes up the browser and any jQuery changes i make at the frontend are not reflected. Is there any way around this??
Thanks in advance.
You should make the next ajax call after the first one has finished like this for example:
function getResult(value) {
$.ajax({
url: 'server/url',
data: { value: value },
success: function(data) {
getResult(data.newValue);
}
});
}
I used array of steps and callback function to continue executing where async started. Works perfect for me.
var tasks = [];
for(i=0;i<20;i++){
tasks.push(i); //can be replaced with list of steps, url and so on
}
var current = 0;
function doAjax(callback) {
//check to make sure there are more requests to make
if (current < tasks.length -1 ) {
var uploadURL ="http://localhost/someSequentialToDo";
//and
var myData = tasks[current];
current++;
//make the AJAX request with the given data
$.ajax({
type: 'GET',
url : uploadURL,
data: {index: current},
dataType : 'json',
success : function (serverResponse) {
doAjax(callback);
}
});
}
else
{
callback();
console.log("this is end");
}
}
function sth(){
var datum = Date();
doAjax( function(){
console.log(datum); //displays time when ajax started
console.log(Date()); //when ajax finished
});
}
console.log("start");
sth();
In the success callback function, just make another $.ajax request if necessary. (Setting async: false causes the browser to run the request as the same thread as everything else; that's why it freezes up.)
Use a callback function, there are two: success and error.
From the jQuery ajax page:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
// Do processing, call function for next ajax
}
});
A (very) simplified example:
function doAjax() {
// get url and parameters
var myurl = /* somethingsomething */;
$.ajax({
url: myurl,
context: document.body,
success: function(data){
if(data < threshold) {
doAjax();
}
}
});
}
Try using $.when() (available since 1.5) you can have a single callback that triggers once all calls are made, its cleaner and much more elegant. It ends up looking something like this:
$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function(a1, a2){
// a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively
var jqXHR = a1[2]; /* arguments are [ "success", statusText, jqXHR ] */
alert( jqXHR.responseText )
});

Resources