Using multiple ajax calls in one javascript function - javascript

Thanks in advance for any help.
Is it bad practice and/or inefficient to use multiple $.ajax calls in one javascript function? I've been working on one and have a simple testing environment set up on my computer (apache server with php/mysql), and I've noticed that the server will crash (and restart) if I have multiple ajax calls.
I have two ajax calls currently: one passes 4 pieces of data to the php file and returns about 3 lines of code (pulling info from my sql database), the other simply gets the total rows from the table I'm working with and assigns that number to a javascript variable.
Is it just that my basic testing setup is too weak, or am I doing something wrong? See below for the two ajax calls I'm using:
$.ajax({
type: "GET",
url: "myURLhere.php",
cache: false,
data: {img : imageNumber, cap : imageNumber, width : dWidth, height : dHeight},
})
.done(function(htmlpic) {
$("#leftOne").html(htmlpic);
});
$.ajax({
type: "GET",
url: "myotherURLhere.php",
cache: false,
success: function(data) {
lastImage = data
}
})

Short answer: two ajax request on a page is absolutely fine.
Longer answer:
You have to find the balance between minimalising the number of ajax calls to the backend reducing the traffic and communication overhead; and still maintaining a maintainable architecture (so do not pass dozens of parameters in one call to retrieve everything - maybe only if you do it in a well designed way to collect every parameter to send)
Also most likely there's something wrong with your backend setup, try looking into webserver logs

Related

Ajax call stops after a certain amount of PHP loops (2 minutes)

I have a button that checks a lot (300+) posts for a specific value and other things (about 20 if, else's). Somehow the ajax call of the button stops after looping about 73 times/2mins.
It doesn't loop this ajax call, there's a PHP loop in the function it's referring to.
Is there any way to extend this? This is what I currently have:
$.ajax({
url: ajaxurl + "?action=updatefield",
type: 'post',
data: dataString,
success: function(data) {
console.log("SUCCESS!");
$("#myResponse").html("<h4>Response: </h4><hr>" + data);
},
error: function(data) {
console.log("FAILURE");
},
timeout: 600000 // (this is what I tried, but it doesn't seem to work)
});
Perhaps this is the answer for my problem, but not my question: Browser Timeouts
Is there a way to extend this time, or is there another way?
So let me get this right... you have ONE Ajax call that triggers a PHP loop, and it's the PHP loop that times out?
It could be:
An HTTP timeout (this can be increased in the Apache config, but it's not recommended)
An HTTP body size overflow (again this can be increased in the Apache config, but it's not recommended)
A server-side limit on the maximum execution time of a PHP script (this can be changed in php.ini, but guess what... it's not recommended!)
Ultimately you are not doing this right. You should be calling the PHP script every so often (for example every second) by putting the Ajax call in a JS setInterval(1000); The PHP script itself should be quick and to the point.
I have tracked down the issue by enabling PHP errors. Besides fixing common errors, I found the issue.
Allowed memory size of 134217728 bytes exhausted
I'm currently trying to clean up my code and remove any unnecessary requests to increase speed and efficiency. Thanks for all the answers.

Nested AJAX requests without a callback success function

After reading this thread jQuery Ajax Request inside Ajax Request
Hi everyone I need to have explanations about such a situation.
I've just been working on the code of a former member of my development team and found many parts of the code where he makes asynchronous ajax calls within other ajax calls.
My question is: can anyone explain the advantages and disadvantages of this practice and whether it is a good or bad practice?
Here is an example of code:
// first ajax (starting ajax call)
$.ajax({
url: "script1.php",
type: "POST",
data: {paramFisrtAjax: "first-ajax"},
success: function(response) {
alert(response);
}
});
script1.php
<script>
// second ajax
$.ajax({
url: "script2.php",
type: "POST",
data: {paramFirstAjax: "<?= $_POST['paramFisrtAjax'] ?>", paramSecondAjax: "second-ajax"},
success: function(response) {
alert(response);
}
});
</script>
<?php
// some operations on database server
echo "page2 operations with param: paramFirstAjax-> {$_POST['paramFirstAjax']}";
?>
script2.php
<?php
// some operations on database server
echo "page3 operations with params: firstParam -> {$_POST['paramFisrtAjax']} and secondParam-> {$_POST['paramSecondAjax']}";
?>
Something tells me it's not a good thing becouse i think the correct way is use the callback function success.
Like this: jquery nested ajax calls formatting
There is an advantage and a disadvantage here.
The Advantages are:
1) You make an async call, making the request a lot faster. You do not wait for the callback function, thus do not wait for your response which might take time to return. You do everything on the background rather then 'straight forward'.
This is understandable when you call multiple methods and you do not want the delay in waiting for the callback.
2) You are able to fetch a far greater amount data through your call while minimizing the need of the end client to wait.
This is useful when you have a big amount of data to display and you want to make it with minimal effort.
The Disadvantages:
1) Error handling is a pain. If something fails within the inner calls, it takes time to detect were the failure occurred and on which method.
When waiting for the callback, you can detect right away where the error occurred, as it will return a response of success or error,
2) if there is a mismatch on the data, it is hard to track back and see where the missing part took place, you will have to go through each request one by one to detect and use developer tools and/or fiddler as well, since those are async calls at the end.
3) it is easy to put too much effort on the client, since maintaining this kind of technique might result in calling multiple methods that will work together at the same time, thus creating overload on the client, locks on the threads or DB when working with server side code and more.
This explained, you can now decide for yourself with which type of method you would like to continue further in your code.

Continuous AJAX requests increasing resource count and size

I need to perform semi-continuous AJAX requests to display data based on the latest entry into a DB. This all works fine with a setInterval() but now I notice the continuously increasing number of resources and size in the Web Inspector (see image). I imagine that this may become an issue if the app is open for long periods of time? Or is the size displayed (1) merely network activity? How could I prevent this? I have set the jQuery ajax cache to false.
Update:
Did not post any code because there's nothing special there. Just a basic jQuery ajax function, php script that queries DB based on data from the ajax function and echoes it back in a response.
So is the number of KB in the Web Inspector (1) network traffic or cached?
$(document).ready(function(){
setInterval(refresh, 2000);
})
function refresh(){
$.ajax({
type: "POST",
cache: false,
url: "../update.php",
data: dataString,
success: function(msg){
if(msg2 == 'same'){
// do nothing
}else{
$('#result').html(msg);
}
}
})
}

Access-Control-Allow-Origin header is not present on the requested resource

DISCLAIMER: This question is a question about question. So that makes this question a meta question. It does not have any connection to the previously asked questions. If you find any resemblance, lemme tell you one thing- it's purely coincidental.
I want to make an AJAX request from my web page. I have been trying to do this, but none of the methods worked perfectly. The only post that I found something close to reality is this.
I tried various other methods from SO & other similar sites, but all of those posts said only one thing to me.
"No 'Access-Control-Allow-Origin' header is present on the requested resource."
I know now you are gonna mark this question as duplicate since there are loads of questions similar to this. Now..Lemme tell ya' one thing. I tried every piece of sh*t I found in SO, but none of 'em gave me the result that I was looking for. It's not because they all are wrong. It because I ain't got no knowlegde on how to use 'em. Then finally...I settled on the link I provided above. It's easy..but I need to know certain things about the code.This is the first time I am hearing the beautifully sodding acronym- CORS. So, if anyone can help me understand the questions I raise, Up votes for all of ya'. I wanna resolve this son-of-a-b*tch question before I celebrate my birthday for the third time this year. I will tell ya' what all I have-in form of resources & questions.
1) A rotten server located at Elizabeth town.
2) I need to access it.
3) I am planning to make a HTTP GET request.
4) I have a url. (eg. http://whereismyweed.com)
5) I store it into a JavaScript variable. var stoner='http://whereismyweed.com'
6) I have a HTML div tag in my webpage. (<div id="myprecious"></div>)
7) I wanna display the response I get from the server inside of 'myprecious' div.
8) And last but not the least... my AJAX function. (Courtesy: some website I visited)
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); },
beforeSend: setHeader
});
What is 'myData'?? What does it contain. How can I get the response for this request? What is 'setHeader'?? Does it have any significance??? How can I display the response inside myprecious div? What changes should I make in the function? Is this function correct?
Too many question, Right???? Well...I need only one common answer for it?
Your function is correct.Follow below steps do achieve your goal-
//for getting response modify your code like
success:function(response){
alert(response);
$('#myprecious').html(response); //myprecious is id of div
}
// myData variable is jSon object which contains request parameter has to send.Eg.
var myData = {'first_name':'Foo','last_name':'Bar'} // now on server first_name and last_name treated as request parameter.
// If server not required any special headers to validate request 'setHeader' does not require. by default $.ajax will take care of it. you can remove it.
/// final code looks like
$.ajax({
url: stoner,
data: myData,
type: 'GET',
crossDomain: true, // enable this
dataType: 'jsonp',
success: function(response ) { $('#myprecious').html(response);
},
error: function() { alert('Failed!'); }
});

Why jQuery ajax added same cookie in my request header multiple times?

I have been trapped in this on for many hours, wondering if you have could help me out or provide me some suggestion?
Long story short,
I have a asp.net web api application, In one of my page, I am trying to load some data from web api and add them into few dropdown lists.
Anyway, I use jQuery ajax when the page loads
$(document).ready(function () {
//Fires when page loads
LoadMachines();
LoadMachieGroups();
LoadPrinterServer();
LoadSavePreference();
});
Each of the functions does the similar job, for example
function LoadMachieGroups() {
console.log("Before group " + document.cookie);
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "/api/Machine/MachineGroups",
//data: "{}",
success: function (response) {
OnMachinesGroupLoadSuccess(response);
}
});
console.log("after group " + document.cookie);
}
The issue is that, we the code runs to the third (LoadPrinterServer) and fourth function (LoadSavePreference). The request header passed the same cookies (DoxMachineId) with different values three times. (Please see the picture), which then cause the trouble in my c# code to find the correct result.
My questions are:
1.) Why could same cookie added in the header multiple times? Is this because of multiple ajax calls?
2.) How to solve the problem? For example: remove the cookies?
Thanks guys in advanced.
Since I stumbled over the same (or pretty similar) problem and could not find a solution elsewhere, here comes my self-found-after-severe-frustration-solution:
When I sent the set-cookie header to the client, I missed to set its path argument to / (the root) on the server side. The client interpreted this as to set the path of the cookie to the parent of the leaf of its current target-path. In my case, that meant /api (since it has been an ajax-call to /api/create).
So, the client ended up with storing one instance of the cookie per path (in my case, for each api-call, there was an instance of the cookie stored at the client-side, as well as one cookie for the root-path that has been set by loading resources).
Whenever the client sent a request to the server later on, it attached all of the cookie-instances (with their respective values) to this request that matched the current target-path (again, in my case, whenever the client requested /api/create it attached the cookie-instance of the path / as well as the instance of the path /api which means the same cookie with two different values).

Categories

Resources