I have a page that has to run an ajax command a few times. It has to use the results of the previous ajax call in for the current one.
in laymen's terms:
call ajax, build entity on remote server, return result (i get a proprietary id as result)
...
call ajax, use result to post additional data to remote server, get id of this post
...
call ajax, post ids..etc
my first idea was async:false, but i see this is widely unacceptable and it ruins code execution order. My goal too, is to have a dialog window that prints the results of the ajax calls as they happen. Currently, the dialog window appears once all ajax calls are done. I don't get the pretty little: Build....done then additional Options.....done and so on...
if i make asynch:true, i wont have the id's need to process the next ajax..
what other options do i have have?
//form var is set earlier, standard serialized form.
var functions = ['build','additionalOptions','completion'];
$('#submitButton').click(function(){
$('#createGroupDialog').dialog({
autoOpen:false,
width: 1200,
height:800,
modal: true,
position: {my: "top", at: "top"},
resizable: false,
closeOnEscape: true
});
$("#createGroupDialog").dialog('open').html("<p>Please Wait...</p>");
function fireAjax(form,func)
{
$.ajax({
type: "POST",
url: "createGroup/createGroupDo.php",
data: form+"&func="+func,
asynch: false,
success: function (result) {
$('#createGroupDialog').append(result);
}
});
}
jQuery.each(functions , function(i,func){
fireAjax(form,func);
});
});
asynch:false is indeed a terrible way to deal with asynchronous data. It doesn't mess with the execution order but it blocks until the request finishes meaning no other JavaScript can run in the mean time, this includes things like onclick handlers and animations.
Since your requests rely on a previous request you have to write them like that:
$.ajax({
url: "request1.php",
data: data,
success: function (result_1) {
$.ajax({
url: "request2.php",
data: result_1,
success: function (result_2) {
$.ajax({
url: "request3.php",
data: result_2,
success: function () {}
});
});
});
}
});
But as you can see this gets tedious. You can use callbacks, but it's better use the Promise API.
Use like:
$.ajax({
url: "request1.php",
data: data
}).then(function (result_1) {
alert(result_1);
return $.ajax({
url: "request2.php",
data: result_1,
});
}).then(function (result_2) {
alert(result_2);
return $.ajax({
url: "request3.php",
data: result_2
});
}).then(function (result_3) {
alert(result_3);
});
It's worth noting that jQuery does a lot of work under the hood to make this API possible. $.ajax is a very flexible function. This means you can use it in many ways. It's best to chose one way and to stick with it. The current state of art really leans towards Promises.
Related
I have tried tons of thing to get json data from another url with jQuery. I have working code in php, but dont have any idea how to do it in jquery.
PHP:
$skin = rawurlencode($market_hash_name);
$skin2 = str_replace('%0A', '', $skin);
$link = "http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=".$skin2;
$json2 = file_get_contents($link);
$obj2 = json_decode($json2);
$mediumPrice = $obj2->median_price;
Example of jQuery that i have tried:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
});
Typically a easy way around that is to create a Proxy, that is just a fancy word for saying have something else send and receive the data between the end points.
This can be as simple as using ajax to a PHP file on your server, from that PHP file using CURL to your endpoint, back to the output through echoing the return of the CURL script.
That way you can get around the restrictions on JavaScript. You mention
I have working code in php
So it should be relatively trivial to pipe the ajax call through that code and back.
Ok so instead of doing this
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
Do this
$.ajax({
type: 'GET',
url: 'http://yoursever.com/proxy.php/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'json',
success: function (data) {
alert(data.median_price);
}
});
Then in proxy.php or whatever you chose to name it, use your working php code to make the call then simply return that data to the client through JSON as per normal AJAX. Then you are technically calling the remote sever using PHP and don't have the cross domain issue. But because you are using your sever as a Proxy you can still do it in real time.
i am sending data through ajax call to the php code my ajax code is this
var values = JSON.stringify({ dstring: dataString, ukey:ukey });
var page_path = server_url+"save_data.php";
$.ajax({
type: "POST",
url: page_path,
cache: false,
data: values,
dataType: "json",
success: function(msg){
},
error:function(xhr, status, error) {
}
});
and in the ajax it send data like this
{"dstring":{"q2":"11","q3":"22","q4":"33","q5":"44","q6":"55"},"ukey":"1"}
and in the php when i try to get it through REQUEST it dont show me data , i am bit confuse on how to handle this data in php
Don't stringify data on your ajax call. You should then be able to $_POST['dstring']on the PHP script. Also, you should add in some debug code at least into that error handler to know what's up. Last but not least, inspect the network calls.
You have to get file_get_contents("php://input") and run that through json_decode.
I know how to use $.ajax. I have a Codeigniter project so I just call:
url:'<?php echo base_url()."somecontroller/somefunction"?>',
This is all ok but ajax waits for the response. I just want to the call the url as you would by typing it in your browser. I don't want to wait for the response because the controller does a redirect and then loads a view. Also i need to be able to send some data via POST.
How can I do this?
You can use the following for sending asynchronous request with additional parameters.
$.ajax({
type: "POST",
url: url,
data: data, // additional parameters
async:true,
success: function(response){
}
});
If you want the request to be synchronous, set async:false.
For post, type:POST
Refer http://api.jquery.com/jQuery.ajax/
Do you can try this ?
Change the (alert) function with your function
$.ajax({
url: 'test.html',
async: false,
success: function () { alert('hello people from the world'); }
});
Never use async: false.
Since Javascript runs on the UI thread, an async: false request will freeze the browser until the server replies
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);
}
My PHP file doing 2 operations: 1. Submits data from form into db table, 2. Sends email.
What I want to do is to show status messages via ajax. For example, "First operation done, please wait for second" and then when second one will be finished show the next message "Second operation done too". Now my ajax looks like that.
How can I modify it?
//add status data to form
form.data('formstatus', 'submitting');
if (validate()) {
//send data to server for validation
$.ajax({
url: formUrl,
type: formMethod,
dataType: "json",
data: formData,
success: function (data) {
$.notifyBar({
cls: data.status,
html: data.message
});
form.data('formstatus', 'idle');
}
});
}
in the success block you can perform another ajax call. That's the simplest. You can do it to in .success(), .ajaxSucces(), .complete(), or .then() function like this: $.ajax(...).success(...);
ideally you would embed the code in a function, by example
$.ajax({
url: formUrl,
type: formMethod,
dataType: "json",
data: formData,
success: function (data) {
notifyResponse(data);
form.data('formstatus', 'idle');
sendMail();
}
});
function sendMail() {
$.get(mailUrl, function(data) { // or $.post(...
notifyResponse(data);
});
}
function notifyResponse(data) {
$.notifyBar({
cls: data.status,
html: data.message
});
}
If you've to do two operations that have different execution times, just send two different AJAX queries, and get the responses from them.
Divide your PHP service in two parts. If the second part depends on the first, instead of sending the two requests at the same time, send the second request when the first one returns.
In other words, in your success callback, you're going to notify the user that the first operation has been completed and you proceed to call the second operation, whose success callback will inform that the second operation has been completed.