How to handle multiple AJAX behaviors in one HTTP request? - javascript

I am using jQuery. I have implemented a multipart web page where a list of links* are rendered and each link is periodically updated through AJAX HTTP requests. That is, on the page there are many links of which each one is "timer-triggered" through JavaScript so to perform a HTTP request to the URL pointed by the link itself and, on response success, to replace those links with the retrieved data (the updated links).
This implementation works but it is "performance less" in cases when the page contains many links: one AJAX request is executed per link resulting in many hits to the server. In order to solve that performance issue I thought to make the JavaScript code to execute a unique AJAX request that retrieves the whole set of links and then to replace DOM data.
However I do not know how to implement the "unique request" mostly due to the practice/technique that I have to use and since it is the first time I notice this kind of problem. What can I do? Should I implement a JavaScript handler for event-registration or what?
* In my case link elements are used (<a></a> HTML tags) but those can be anything associated with a URL.
Update after the jfriend00 answer
If the solution is to build a JSON array as jfriend00 describes in his answer then I should implement the page behavior so to update the JSON array dynamically. Since my HTML links are even rendered dynamically along with some JavaScript code then that JavaScript code could update the JSON array dynamically by "registering"/"unregistering" links. If this is a solution in my case, how can I implement it?
I render links as "partial templates" along with the JavaScript code which JavaScript makes those links to execute AJAX requests. HTML-JS code per each link (the mentioned "partial templates") looks like the following:
<script type="text/javascript">
(function() {
var link = $('#link_1')
...
}());
</script>

It seems like you can just send some JSON that is your array of links to request and then receive JSON back that is an object where each key is the requested link and the data is the server response for that particular link.
If the links you want to process look something like this:
<a class="myLink" href="xxx"></a>
It could look something like this:
function processLinks()
// assuming you can specify some CSS selector to select the links in your page that
// you want to target
// create an array of URLs for the ajax call
// and an index of arrays --> DOM objects so we know which DOM object goes
// with a given URL when processing the ajax results
var urlArray = [];
var urlIndex = {};
var urlArray = $(".templateLink").each(function() {
urlArray.push(this.href);
urlIndex[this.href] = this;
});
$.ajax({
url: "your ajax url here",
data: JSON.stringify(urlArray),
dataType: "json"
}).done(function(data) {
// assumes you get data back as {"url1": data1, "url2": data2, ...}
$.each(data, function(url, urlData) {
// get DOM object that goes with this URL
var domObj = urlIndex[url];
// apply urlData to domObj here
})
});
}
Updating my answer now that you've disclosed your "partial templates".
To process them all at once, change this type of structure which processes them one at a time:
<script>
(function() {
var link = $('#link_1')
...
}());
</script>
<a href="yyy" id="link_2></a>
<script>
(function() {
var link = $('#link_2')
...
}());
</script>
to this which finds them all in the DOM and process them all at once:
<script>
// process all the template links
$(document).ready(processLinks);
</script>

Related

Load data with AJAX only if it has not already been loaded?

I need to load data for my JavaScript app to use. I would like to load the following:
userlist JSON
milestones JSON
Tags JSON
user ACL permissions JSON
These 4 items of data from the server as JSON should be loaded using AJAX but only loaded once.
So I need code that will check to see if the data is loaded already and if it is, use it. If it is not loaded yet, it would make an AJAX request and load the data, and then use it.
I have multiple JavaScript files which need access to this data so I want to make sure that any of them can access it, and whichever once calls for it first will load it using AJAX and make it available for the other scripts to call it without making multiple repeat AJAX requests.
How could I go about this using JavaScript and jQuery?
A basic example would be super appreciated and useful. Thank you
If any of these are not set, load them using AJAX. After loading with AJAX, set these vars for the next caller to access them without a new AJAX request being made...
var userList = userJsonData;
var milestoneList = milestoneJsonData;
var tagList = tagJsonData;
var useAclPermissions = useAclPermissionsJsonData;
Just store the data in a global javascript variable, which is set to null, when your page loads. The first script which loads the data, stores it in the variable, all the other scripts try to access the content of the variable, and if not set, load it:
var milestoneData = null;
function getMilestoneData() {
if (milestoneData === null) {
//make the ajax request, and populate milestoneData variable
} else return milestoneData;
}
According to can i use you can check out localstorage aka webstorage. If you can use it, it might solve your issues. There is a jQuery plugin available. jstorage is an alternative, and has a really simple example at the bottom of the page. Hope this helps.

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

Refresh Part of Page (div)

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

Displaying data from a database using jQuery and Javascript

I'm trying to display specific parts of a Cloudant database. This database contains many separate documents, and each document contains a category called "results". I'm trying to display whatever is in results. Each document is identified by its own id. I tried using the get() method in jQuery, but unfortunately it is not running successfully.
function grabData(){
var url = 'https://cloudant.com/futon/document.html?acharya%2Ftoxtweet/ff558f75077e8c758523cd3bd8ffdf88';
$.get(url, function(data) {
$('.result').html(data);
alert("Data loaded: " + data);
});
}
grabData();
I'm not entirely sure where I went wrong...Should I consider using SQL instead of ajax?
I think your issue it this:
replace this:
grabData();
with this:
$(document).ready(function(){
grabData();
});
or more shortened:
$(function(){
grabData();
});
The URL you are using is returning an entire webpage.
Your jQuery code is looking for an element on the current page with a class name of result and trying to change it's inner HTML to the response from the URL.
You didn't provide any additional code to look at, but I would assume that is not what you were expecting it to do.
I assume you are wanting to parse through the entire url, but in your current code the page will be processed as a raw string and not a DOM object. So you would have to parse through that string with regular expressions, etc.

How can one incorporate JSON data with the returned HTML on the first request to the home page?

My scenario is this - the user asks for the home page and then the javascript code of the page executes an ajax GET request to the same server to get some object.
The server keeps the home page as a jade template.
So, right now it takes two roundtrips to load the home page:
GET the home page
GET the JSON object
I am OK with it, but just out of curiosity - what are my options to incorporate the object requested later into the initial GET request of the home page?
I see one way is to have a hidden html element, which inner HTML would be the string representation of the object. A bit awkward, but pretty simple on the server side, given that the home page jade template is preprocessed anyway.
What are my other options?
Please, note that I am perfectly aware that sparing this one roundtrip does not really matter. I am just curious about the techniques.
Another option is to always return a JSON object, then the HTML for your home page would be the value of some property on this object. This would probably require some changes on your client-side logic, though.
One more option: instead of a hidden HTML input/textarea containing a JSON string, the home page code could contain a script block where an object literal is declared as a variable. Something like this:
<script>
var myObj = ... // Your JSON string here.
// myObj will be an object literal, and you won't need
// to parse the JSON.
</script>
The initial GET request will retrieve just that document. You can have additional documents loaded defined as scripts at the bottom of your page, so you don't need to do a XHR, for the initial load.
For instance:
GET /index.html
//At the bottom you have a <script src="/somedata.js"></script>
GET /somedata.js
//here you define you var myObj = {}.... as suggested by bfavertto
Depending on which server side technology are you using, this could be for instance in MVC3
public partial class SomeDataController : BaseController
{
public virtual ContentResult SomeData()
{
var someObject = //GET the JSON
return Content("var myObj = " + someObject, "application/javascript");
}
}
You can embed the Json data inside a hidden tag in your HTML. At runtime, your javascript reads the data from this hidden tag instead of making a Json call (or make the call if this data is not available).
<!--the contents of this div will be filled at server side with a Json string-->
<div id="my-json-data" style="display:hidden">[...json data...]</div>
on document ready:
var jsonStr = document.getElementById( "my-json-data" ).innerHTML;

Categories

Resources