Multiple Ajax Request waits each other to run - javascript

I try to send multiple ajax requests. But each request waits for previous one complete to start.
Is there any reason for that?
Here is my JS code.
tjq.ajax({
type: 'POST',
data: { id: _id },
dataType: 'json',
url: '/dynamic-packages?act=addtocart',
success: function (r) {
///...
}
});
Here is the C# code. I just put a sleep for 10 sec to demonstrate duration in developer console.
protected void Page_Load(object sender, EventArgs e) {
if (Request["act"] == "addtocart")
{
Thread.Sleep(10000);
Response.End();
}
}
As you can see the SS duration increases by 10 sec for each request.
UPDATE:
Here is how I call ajax request
for (var i = 0; i < Destinations.length; i++) {
getHotels(i);
}

Use async statement for give prority in first or next it.
Setting async to false means that the statement you are calling has to complete before the next statement in your function can be called. If you set async: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.
async: false
function getData1(){
var data;
var param1 = jQuery('field1').val();
var param2 = jQuery('field2').val();
jQuery.ajax({
url: "ajx_request1.php",
type: 'POST',
data: {
'field1': param1,
'field2': param2
},
dataType: "json",
async: false,
success: function(result){
data=result;
},
error: function(result) {
alert("Error");
}
});
return data;
}
function getData2() {
var data;
var param1 = jQuery('field1').val();
var param2 = jQuery('field2').val();
jQuery.ajax({
url: "ajx_request2.php",
type: 'POST',
data: {
'field1': param1,
'field2': param2
},
dataType: "json",
async: false,
success: function(result){
data=result;
},
error: function(result) {
alert("Error");
}
});
return data;
return data;
}
getData1();
getData2();
You Can Also Set Timeout for response get late another from one statement.
setTimeout(function() {
var data = getData2();
console.log("The data is: " + data);
},1000);

Related

Ajax. On Ajax success call same ajax function one more time

This is what i tried.
tjq.ajax({
type: 'POST',
url: '<?php echo base_url();?>getCmsHotel?t=<?php echo $traceId;?>',
dataType: 'JSON',
encoding:"UTF-8",
contentType: "application/json",
traditional: true,
async: true,
error: function (request, error) {
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
return false;
},
success: function (data) {
//alert(data.status);
if(data.status == 'FAILURE'){
//searchresults = data;
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
return false;
}else if(data.status == 'SUCCESS'){
var recalajx = '2';
if(recalajx =='2' && recalajx!=3){
recalajx ='3';
tjq.ajax(this);
}
alert(recalajx);
tjq('.searchresultsDiv').remove();
hotelsresults = data;
//hotelssearchObj.hotelsResults(data);
gblStartCount = 1;
gblHotelData = tjq.extend(true, {}, data);
gblHotelDisplayData = tjq.extend(true, {}, data);
hotelssearchObj.hotelsResults(gblHotelDisplayData);
searchApiCount++;
hotelssearchObj.reloadFunctions(searchApiCount);
tjq("div#divLoading").removeClass('show');
}
}
});
This code calling multiple times. Am trying to call tjq.ajax(this); only once after 1st ajax SUCCESS.
when tried to alert getting 3 but still axaj calling for multi times.
How to stop this can some help!
One solution is to put the Ajax call in a function, and check how many times it has been called with a counter. If the counter is less than 2, call the function again.
here's an example:
ajaxCall();
function ajaxCall(counter = 0) {
$.ajax({
type: 'POST',
success: function() {
counter++
if (counter < 2) {
ajaxCall(counter);
}
}
});
}

Getting Data from Ajax request displayed

I've already read this article How do I return the response from an asynchronous call? However I couldn't come up with a solution.
I'm doing an ajax request
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
}
});
}
And Console displays everything fine but when I say
var chinese = getdata();
to get the data. I keep getting:
Uncaught TypeError: Cannot read property 'length' of undefined error for this line
var text = chinese[Math.floor(Math.random()*chinese.length)];
Can anybody help me here?
The problem is that you are using an asynchronous method expecting a synchronous result.
Therefore you should use the code in the result of the asynchronous call like the following:
function getdata(url) {
console.log('Started');
jQuery.ajax({
type: 'GET',
url: url,
dataType: 'json',
error: function(xhr) {
console.log('Error', xhr.status);
},
success: function(chinese) {
var text = chinese[Math.floor(Math.random()*chinese.length)];
// Do something else with text
}
});
}
getData('http://myserver.com/myscript.php');
I hope it helps :)
The error you get is because of the asynchronous nature of the call. I suggest you to assign the value after you get the success response from the API like below.
var chinese = getdata();
Then the function getdata() will be like
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
initChinese(response.data);
}
});
}
And create a function initChinese() like
var text;
function initChinese(chinese){
text = chinese[Math.floor(Math.random()*chinese.length)];
}
You can also declare the text variable in global scope and then assign the value to text variable inside the success function without having to create a new function initChinese.
The problem is your getdata function does not return anything. In your getdata function you're doing a ajax request, which is an asynchronous request. So the data you're requesting won't, and can't be returned with your getdata function.
But you will have the requested data in your success function:
function getdata(url)
{
console.log('Started');
jQuery.ajax({
type: "GET",
url: "http://myserver.com/myscript.php",
dataType: "json",
error: function (xhr) {
console.log('Error',xhr.status);
},
success: function (response) {
console.log('Success',response);
var text = response[Math.floor(Math.random()*response.length)];
}
});
}
As I'm not able to test your code, you've to debug the rest on your own. But the response variable will be most likely your "chinese" variable.
You could try using callbacks or you could look at Promises.
The idea with callbacks is that you pass a function that is run after the ajax request is finished. That callback can accept a parameter, in this case the response.
Using callbacks:
function getData(url, successCallback, errorCallback) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
errorCallback(xhr.status);
},
success: function(response) {
successCallback(response);
}
});
}
var chinese;
getData("http://myserver.com/myscript.php", function(response) {
chinese = response; // you can assign the response to the variable here.
}, function(statusCode) {
console.error(statusCode);
});
Using Promises (< IE11 doesn't support this):
function getData(url) {
return new Promise(function(resolve, reject) {
console.log('Started');
jQuery.ajax({
type: "GET",
url: url,
dataType: "json",
error: function(xhr) {
reject(xhr.status);
},
success: function(response) {
resolve(response);
}
});
});
}
var chinese;
getData("http://myserver.com/myscript.php").then(function(response) {
chinese = response;
console.log(chinese);
}, function(statusCode) {
console.error(statusCode);
});

ajax success response change as #html.raw

I have following jquery code in my Razor viewpage
$(document).ready(function () {
var grouplistvalues = #Html.Raw(Json.Encode(Session["grouplist"]));
$("#nsline").click(function () {
alert(grouplistvalues)
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
alert(response)
},
error: function ()
{
}
});
});
$("#ewline").click(function () {
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
},
error: function ()
{
}
});
});
in above grouplistvalues its taking session as html raw
when I alert it on #nsline click function I can see it,
in above function I'm calling to ajax function and above grouplistvalues value updating
once I alert it on #nsline click function success response I can see a alert like folllowing
since this(grouplistvalues value) 1,2,.. changing as [1,2..] I cannot call to other ajax function in #ewline click function since parameter difference,
this is the above common ajax call
[HttpPost]
public JsonResult SetupGroups(long[] grouplist)
{
Session["grouplist"] = null;
List<long> groupList = new List<long>();
foreach (var groupitem in grouplist)
{
groupList.Add(groupitem);
}
long[] grouparray = groupList.ToArray();
Session["grouplist"] = grouparray;
return Json(grouparray);
}
}
Though I have two click functions its work with only the first click(ewline or nsline only the first time)
How to solve this
It was the dataType in your ajax request. It should be json:
dataType: "json"

How to load data in breaks from Ajax call?

Guys I have an ajax call on my page, which is being called on scroll down event (lazy loading).
This is the whole call :
function callMoreData()
{ $.ajax( {
type: "GET",
url: "/api/values/getnotice",
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
updateData(data);
},
error: function (x, e) {
alert('problem while fetching records!');
} });}
function updateData(data) {
updateData = function (data) { };
$.each(data, function (index, value) {
BindNotice(value);
});
}
function BindNotice(values)
{
...appending some div here with values...
}
now this call is returning all the data and display it all at once on first scroll event. What I want to do is, load the data in sets of two. For example, each loop gets executed on index 0 and 1 at first scroll, then on second scroll index 2 and 3 gets processed and then so on. How would I do about doing as? I have a very limited experience with JS/AJAX...
EDIT : CODE FROM CUSTOM LIBRARY :
$(".mainwrap .innnerwrap").mCustomScrollbar({
autoDraggerLength:true,
autoHideScrollbar:true,
scrollInertia:100,
advanced:{
updateOnBrowserResize: true,
updateOnContentResize: true,
autoScrollOnFocus: false
},
callbacks:{
whileScrolling:function(){WhileScrolling();},
onTotalScroll: function () {
callMoreData();
}
}
});
WebApi CODE :
[WebMethod]
[HttpGet]
public List<Notice> GetNotice()
{
string con = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
SqlConnection Connection = new SqlConnection(con);
string Query = "uSP_GetAllNotice";
SqlCommand cmd = new SqlCommand(Query, Connection);
cmd.CommandType = CommandType.StoredProcedure;
DataTable dt = new DataTable();
Connection.Open();
dt.Load(cmd.ExecuteReader());
Connection.Close();
List<Notice> objNoticeList = new List<Notice>();
foreach (DataRow row in dt.Rows)
{
Notice objNotice = new Notice();
objNotice.Subject = row["subject"].ToString();
objNotice.Date = Convert.ToDateTime(row["IssueDate"]);
objNotice.Department = row["Department"].ToString();
objNotice.Body = row["Body"].ToString();
objNotice.NoticeImage = row["NoticeImage"].ToString();
objNotice.Icon = row["Icon"].ToString();
objNoticeList.Add(objNotice);
}
return objNoticeList;
}
First of all, you have to make sure the server-side delivers only as mutch elements as you like, so that would be something like
[...]
type: "GET",
url: "/api/values/getnotice/" + start + '/' + amount,
dataType: "json",
[...]
start and amount have to be defined outside the function, in a higher scope, so it's available by the ajax function. While amount will be more or less constant, start can be calculated.
One option would be, to increment it on the success function.
Another solution can be, to count the divs you already appended to your DOM.
The result could be something like:
var amount = 2;
var start = 0;
function callMoreData(){
$.ajax( {
type: "GET",
url: "/api/values/getnotice/" + start + '/' + amount,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
updateData(data);
start += amount;
},
error: function (x, e) {
alert('problem while fetching records!');
}
});
}
I recommend NOT to put it in the global namespace, but to put it in a own one.
Maybe you can use paging parameters to get your data in chunks of two items at a time. Let the server handle the work of figuring out how to break the response data into two items per page.
$.ajax({
type: "POST",
url: "/api/values/getnotice",
data: {
'PageSize': pageSize,
'Page': page
},
type: "GET",
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
updateData(data);
},
error: function (x, e) {
alert('problem while fetching records!');
}
});
Make a global variable such as
Var time_scrolled = 0; //in the beginning
when you receive scrolldown event your indexes at each request will be (time_scrolled*2) and (time_scrolled*2+1) then you increase time_scrolled by 1 as time_scrolled++;
Hope this will solve your problem.
Edited:
complete code
Var times_scrolled = 0; //in the beginning
Var global_data = [];
function callMoreData()
{ $.ajax( {
type: "GET",
url: "/api/values/getnotice",
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (data) {
global_data = data;
},
error: function (x, e) {
alert('problem while fetching records!');
} });}
callMoreData(); //fetch data at the time of loading since it won't miss at first scroll
function updateData(){
var initial = times_scrolled*2;
var final = initial+1;
for(var i=initial;i<data.length && i<=final;i++)
{
BindNotice(global_data[i]);
}
times_scrolled++;
}
function BindNotice(values)
{
...appending some div here with values...
}
// modify custom library code to:
$(".mainwrap .innnerwrap").mCustomScrollbar({
autoDraggerLength:true,
autoHideScrollbar:true,
scrollInertia:100,
advanced:{
updateOnBrowserResize: true,
updateOnContentResize: true,
autoScrollOnFocus: false
},
callbacks:{
whileScrolling:function(){WhileScrolling();},
onTotalScroll: function () {
updateData();
}
}
});
This is what I did to solve my problem. This is my ajax call
function callMoreData() {
var RoleCodes = $('#hiddenRoleCode').val();
$.ajax(
{
type: "GET",
url: "/api/alert/getalerts?RoleCode=" + RoleCodes + "&LastAlertDate=" + formattedDate,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function(data) {
$.each(data.data, function (index, value) {
update();
BindAlert(value);
});
},
error: function(x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
}

How can I make sure that other functions is run after this get function is fully completed and rendered?

I have this script that adds elements with data by a get json function.
$(document).ready(function() {
ADD.Listitem.get();
});
It basicly adds a bunch of html tags with data etc. The problem I have is following:
$(document).ready(function() {
ADD.Listitem.get();
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
-
get: function(web) {
AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null, AST.Listitem.renderListitem);
},
renderListitem: function(data) {
$("#Listitem-template").tmpl(data["ListItemResults"]).prependTo(".ListItem-section-template");
}
and here is the json get:
ADD.Utils.JSON.get = function (url, data, onSuccess) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
success: onSuccess,
error: ADD.Utils.JSON.error,
converters: { "text json": ADD.Utils.JSON.deserialize }
});
}
The array each loop is not running beacuse the get method is not finished with rendering the Listitem-section-item-title selector so it cant find the selector.
Is there any good solutions for this?
You could change your functions to return the promise given by $.ajax :
ADD.Utils.JSON.get = function (url, data) {
return $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
async: true,
url: url,
data: data,
cache: false,
dataType: "json",
converters: { "text json": ADD.Utils.JSON.deserialize }
}).fail(ADD.Utils.JSON.error);
}
get: function(web) {
return AST.Utils.JSON.get("/_vti_bin/AST/ListItem/ListitemService.svc/GetListItem", null).done(AST.Listitem.renderListitem);
},
So that you can do
$(document).ready(function() {
ADD.Listitems.get().done(function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Callback:
$(document).ready(function() {
ADD.Listitem.get(url,data,function(){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
});
});
Without callback:
If you cant get the get method to take a callback or return a promise then I think the best way will be to check when its done.
$(document).ready(function() {
ADD.Listitem.get();
var timer = setInterval(function(){
if ($("#thingWhichShouldExist").length>0){
var arr = [];
$(".Listitem-section-item-title").each(function() {
arr.push($(this.text()));
});
clearInterval(timer);
}
},50);
});
Retrieve the values and on success, call a function which will push the values into the array.
Also, arr.push($(this.text())); should be arr.push($(this).text());.

Categories

Resources