I developed an web application in asp.net. In this application I have used jquery ajax for some pages. In this application, when I make two ajax call asynchronously that would not do as I expected. what is happening is even the second ajax call finishes I can see the result when the maximum time out ajax call finished. I mean I can see the both results in the same time, not one by one.
for an example. I have 3 pages
main.aspx - for make two ajax request.
totalCount.aspx - to find the total count.
(max it takes 7 seconds to return, as corresponding table contains 300k records)
rowCount.aspx - to find the row details. (max it takes 5 seconds to return result).
due to this scene, I have planed to make asyn call in jquery ajax in asp.net.
here is my code:
function getResult() {
getTotalCount();
getRows();
}
// it takes max 7 seconds to complete
// as it take 7 seconds it should display second.( I mean after the rows dispaying)
// but displaying both at the same time after the max time consuming ajax call completed.
function getTotalCount() {
$.ajax({
type : "POST",
async : true,
url : "totalCount.aspx?data1=" + document.getElementById("data").value,
success : function(responseText) {
$("#totalCount").attr("value", responseText);
}
})
}
// it takes max 5 seconds to complete.
// after finished, this should display first.( i mean before total count displays)
// but displaying both at the same time after the max time consuming ajax call completed.
function getRows() {
$.ajax({
type : "POST",
url : "getrows.aspx?data1=" + document.getElementById("data").value,
async : true,
success : function(responseText) {
$("#getRows").attr("value", responseText);
}
});
}
I would like to know, If there is any possible to make asyn call in jquery ajax in asp.net.
I searched in net, I got some points that says we cannot do this in asp.net
ref link: http://www.mail-archive.com/jquery-en#googlegroups.com/msg55125.html
if we can do this in asp.net How to do that?
I'm not a asp.net developer but in general ajax terms I can explain this issue as given below
As ajax stands it is asynchronous, so you to expect the two request in some particular oder will not be wise.
The timings given by will be the time taken by the db server to execute some queries but there are more to the request like network traffic etc, so your assumption that 1 request will return before other is not correct.
The .NET session state will cause all requests for a particular session to be queued up.
If session state is not required, you can disable it.
Related
I would like to create a page that will allow the IT guys to select some servers from a list and an operation to perform on the them and then click go. Then have the textarea on the page update with the status of each operation as it completes. Each server maintenance task can take a minute or two. They would like to see updates on the page as each server completes the selected task.
Not sure which technologies to use on the front-end. The back-end is not a problem at all. I can easily take the full list of servers, perform the operation on each server then return the full list, with the result from each server. However, no one wants to wait for all the servers to complete before getting updates.
Normally I would use ajax to update a portion of a page but that is just for a single call/response. I think if I use a javascript loop to call a php script via ajax for each server, then the javascript loop will block the UI updates until the javascript function completes.
Any ideas?
Jquery has a method to perform an asynchronous HTTP Ajax request (http://api.jquery.com/jquery.ajax). Create a recursive javascript function to make the ajax call. Once you get the list of servers and desired operation selected by the user on the UI, call the RecursiveAjax function. With each result, call another function to update the UI.
function RecursiveAjax(serverArray, currentIndex, operation)
{
var operationResult = "";
$.ajax({
type: "GET"
url: "ServerOperation.php",
data: {Operation: operation, Server: serverArray[currentIndex]},
success: function (result) {
operationResult = JSON.stringify(result);
UpdateUI(operationResult);
}
});
var nextIndex = currentIndex + 1;
if(nextIndex < serverArray.length) {
RecursiveAjax(serverArray, nextIndex, operation);
}
}
You can use two technologies for this.
1- websocket https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_client_applications
2- push notification https://developers.google.com/web/fundamentals/engage-and-retain/push-notifications/
In websocket the browser tab has to stay open. In push notification not. Websocket supports many browsers, push notification is only chrome and chromium.
Objective: Parse JSON from an API where results are listed across multiple pages.
I am new to JSON and to working with data in general. I want to know how to write a function that will update the url, outputting the results for each page, and stopping when it reaches one that is empty.
This problem here is from a Shopify url displaying JSON data used for trivial purposes and not part of a real application.
https://shopicruit.myshopify.com/admin/orders.json?page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6
Each page had 5O objects. I'm making an $.ajax request to the url but the url has page=1 as a query,
$.ajax({
url:"https://shopicruit.myshopify.com/admin/orders.json?page=1&access_token=c32313df0d0ef512ca64d5b336a0d7c6",
method:'get',
dataType:'JSON'
}).done(function(response){
so the response I am only getting back is only for The results of page one (obviously). I know there are more pages b/c if I manually put a 2 in place of the 1 I can see different data. This goes on for multiple pages. I have tried removing the page option, setting it to all and any and these just display page 1.I thought maybe leaving the page option out would cure the problem but it does not.
How do I get all the pages of data with an ajax call?
Is it a function that takes the $.ajaxcall inside of it, that adds page++ and makes a new call for each page? I still don't know how to write that sadly.
The shopify API docs do give some examples on how to display "all data" but I tried to use what they suggested and it did not work so I'm not sure that it's applicable to the problem, but just in case it is–
https://help.shopify.com/api/reference/order
Here is a simplistic answer - this will get pages until there's clearly no more data - i.e. once a page returns less than limit orders
function getAllData(page) {
return $.ajax({
url:"https://shopicruit.myshopify.com/admin/orders.json?page=" + (page || 1) + "&limit=250&access_token=c32313df0d0ef512ca64d5b336a0d7c6",
method:'get',
dataType:'JSON'
}).then(function(response){
if (page && response.orders.length == 250) {
return getAllData(page + 1)
.then(function (more) {
return response.orders.concat(more)
})
}
return response.orders;
});
}
getAllData(1).then(function(orders) {
// orders is an array of orders
});
Note I've used 250 for limit to get 250 at a time
I say this is simplistic because, it does get all the data, however, you need to wait until all the data is retrieved before you can use it - this may take too long for your "user experience" - but this should get you to a place you can start
There's logic in the code such that if page is 0, only the first page will be retrieved regardless of how many items are in it - so you could do something like
getAllData().then(function(page1data) {
// do something with page 1
}).then(function() {
return getAllData(2); // start at page 2
}).then(function(restOfData) {
// do something with restOfData, pages 2+
});
One thing I'm not sure of is
.then(function(response){
you may need to change this to
.then(function(r){
var response = r[0];
I'm not 100% certain of jQuery's .then callback arguments
Here is a 'hypothetical' situation.
Let's say I have :
a websocket who tell's me to send a ajax on a url like http://localhost/Whatever every 10 sec.
The ajax call on http://localhost/Whatever will take 45 seconde to reply (exagerate number for the situation).
I wonder how will the browser react? in my mind 3 case:
(good one): Browser is really smart : He understand we ajax
the same url so he won't stack ajax call until the current call
finished.
Browser understand we ajax the same url and make an abort() on the
Ajax 1st call and start a new one (if the browser really does that, it
would be rubbish in my mind).
(worst case): Browser send a ajax on the url each time websocket ask
him to and wait for the answer. Moreover, I suppose there will be a
problem with limitation of parralel ajax request? (i wonder how the
browser if this case happens ?)
So, Which case will happen and why ?
The answer is case 3.
The browser will send all requests in the order you make them. Generally speaking a computer will carry out your instructions in the order your issue them. If you want or need special behavior such as throttling the rate of the requests or not sending the subsequent requests until prior ones have finished you will need to implement that your self.
Imho, this pseudocode might help you.
var requestLock = false;
function pollFromSocket() {
if (someCondition) {
sendRequest();
}
}
function sendRequest() {
if (requestLock) {
return;
}
requestLock = true;
$.get('/whatever')
.done(function(response) {
// process response
})
.always(function() {
requestLock = false;
});
}
This below is displaying Total racers on my website but its not updating live. I need to referesh the page to grab the new number from the database, so what's the simple way of updating it live with jquery/javascript without refreshing the page? Thanks a lot for taking the time to check my question and possibly answer.
<div id="stats">
<div id="racers">
<span><?=number_format($racers, 0, ' ', ' ')?></span>
RACERS
</div>
</div>
Jquery Ajax:
$.post('page.php', {
postVariable : value
}, function(data) {
//do something with data retrieved from php script
});
You set 'page.php' to a script that gets the data you want and echoes it.
You then retrieve what was echoed in the callback function(data);
So data will be the variable containing the value you need. You put this script in a
javascript function and call it when you need to make a request for information on the back-end.
If you have questions let me know. If you need more information on the ajax request you can find it here as well: api.jquery.com/jquery.post/
What you need to do this is the following:
1. Have an action in a controller that outputs the total number of racers
For example:
class Data extends CI_Controller {
public function GetTotalRacers() {
// This is dummy data. You need to replace this code with the correct
// number of racers retrieved from the database
echo 14;
}
}
Take note of where this action is. I'm assuming codeigniter will make the path something like /Data/GetTotalRacers in this case (that depends on how your route rules are configured).
2. Use JavaScript to ask the server for the data and display the result on the page
I recommend you have a method that runs every X number of seconds to refresh the total number of racers. To achieve this, you can use setInterval. Within the setInterval's function have an ajax call to your action. Finally, display the value that's returned from the server:
setInterval(function() {
$.ajax({
// Replace the url value with the correct url to access your action
url: '/Data/GetTotalRacers',
cache: false
})
.done(function( totalRacers ) {
$("#racers span").text(totalRacers);
});
}, 60000); // ex. Update every 60000ms
Note: I've never used codeigniter, but hopefully this description will help set you on the right path.
I use Jquery-ajax calls to post information to a page and display the returned info. The problem I encounter is the following:
When a user makes the first ajax call everything seems normal. When a user does not reload the page and makes the same request for a second time the post-call is made 2 times and the get-call as well. The 3th time there are 4post+4get requests. 4th time 8Post/8Gets. And so on.. until the browser (firefox latest v.) freezes for a while.
I'm a beginning programmer and I don't know what the cause might be. I don't know where to look inside my code. Prehaps you guys can give me a hint. My other ajax requests are fine and only post+get once.
Firebug log:
This is a piece of my code:
$(document).ready(function() {
$('#datepicker').change(function()
{
sendDate($('#datepicker').val());
});
});
function sendDate(str)
{
$.ajax(
{
type: "POST",
url: "manage_processor.php",
data: { chosendate: str },
success: function(data)
{
$('#printdiv').html(data);
}
});
}
Hope anyone can shine some light on this situation.
If I might venture a guess, I suspect the returned data contains a script tag referencing your javascript file. This would explain the GET request you are seeing. Every time the request data is put into #printdiv your script is loaded again and an identical javascript handler would be bound to the same event. This would explain the number of handlers doubling after every request.
Quick test: put console.log( 'script loaded' ); at the top of manage_functions.js. If I'm right it will log after every request.