Getting my ajax in order - javascript

I've never been good with JavaScript or jquery but my latest project has demanded that I get better. I'm trying to create a widget for a website. This widget uses ajax to access json data from another domain. This widget may have multiple instances on the same page, each with different settings.
I'm using JQuery to find all of the elements with a particular class which will identify where the widgets need to go. I'm using custom data- attributes to store the settings for each widget in what will be the container .
The problem I am having is this;
Because ajax request are asynchronous the results are coming in an effectively random order. The code Ihave so far is
<script>
var currentContainer;
$(document).ready(function(){
$($(".container")).each(function( index ){
currentContainer = this;
var url =
"http://example.com/json.php?iid="+$(this).data("owner_id")+
"&iid="+$(this).data("item_id")+
"&l="+$(this).data("layout")+
"&callback=?";
var request = $.get(url,function(data){
console.log(data)
display(data.oid,data.iid,data.l);
},"jsonp");
});
});
function display(oid,iid,l){
$(currentContainer).html("Owner Id = "+oid+" Item Id = "+iid+" Layout = "+l);
}
And in the body....
<div class="container" data-owner_id="George" data-item_id="car" data-layout="tidy">-</div>
<div class="container" data-owner_id="tim" data-item_id="computer" data-layout="allovertheplace">-</div>
<div class="container" data-owner_id="dee" data-item_id="hammer" data-layout="effingmess">-</div>
The result I get is random data in the last only. Any ideas much appreciated!

Don't use global variable in this case. Pass the currentContainer to the display function as an argument.
var currentContainer = this;
...
var request = $.get(url,function(data){
console.log(data)
display(currentContainer, data.oid,data.iid,data.l);
},"jsonp");
...
function display(currentcontainer, oid, iid, l) {
...

The problem is in the line:
$(currentContainer).html("Owner Id = "+oid+" Item Id = "+iid+" Layout = "+l);
When you loop through the divs with class container ($($(".container")).each), you're assigning currentContainer to the div you're working on. So at the end, currentContainerrefers to the last element with a class container.
In display, you want to select the div to act on using its data attribute. You can make this type of selection using jQuery's attribute selectors $("[attribute='val']")

Related

How to handle multiple AJAX behaviors in one HTTP request?

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>

How to get JavaScript variable from ajax loaded page with jQuery?

I'm developing userscript for one webpage (aka browser plugin). I need to update one global Javascript variable (lets call it gVariable (it is an array)) with the one I get with ajax request.
In ajax request I'm requesting for the same page I'm on. But just want to "extract" that one global variable and replace current one with the one downloaded.
This is something I have now (not working).
function LoadNewItemList() {
$.get(window.location, function (data) {
var $data = $(data);
unsafeWindow.gVariable = data.gVariable; //I'm getting 'undefined'
});
}
JS test:
http://jsfiddle.net/ywVKT/15/
Looking at your fiddle, there are mainly 4 tags. i.e.
"title" , "link" , "ul" , "script". That's why you need to use index as 3, since the script tag contains the variable name and value.
Try this and it would work.
$('#variableHere').text(data2[3].innerText);
it will return you following o/p: var gVariable = 0; gVariable = 5
Now you can use regex/substring function to extract the vairable name and value..
I found solution:
unsafeWindow.gVariable = 0;
var $script = $data.filter('script:contains("var gVariable")').first();
eval($script.text());
unsafeWindow.gVariable = gVariable;

Best way to assign a javascript object to html element

I'm getting a javascript object via ajax. I need to attach this object to a div in order to be recovered later, for example, on a click event.
If instead of an object I had a variable I would push it into the html tags like this:
'<div variable="'+value+'"></div>';
And I would recover its value like this:
var value= $(this).attr('variable')
Could you suggest me a good approach to do that with objects?
Thank you very much!
The easiest way is to do this:
<div id="myDiv">...</div>
In javascript
var myDiv = document.getElmentById('myDiv');
myDiv._variable = variable;
You can recover this later if you want, simply using the same myDiv variable, or, again, with document.getElementById() or any other DOM method that returns the element.
var variable = myDiv._variable;
The downside of doing it this way is that you can't specify, in the server, or from the markup, which object you want to attach to the element.
If use JQuery you could use the data storrage functionallity
See data documentation of JQuery
//To store value or obj:
$("#myDivId").data("myKey", valueVar);
//Later to load:
var fetchValue = $("#myDivId").data("myKey");
Using a template engine would be the best approach, dividing logic from view, and that way you can parse full object properties to an html.
in this example i use jQuery & UnderscoreJs template engine.
javascript part:
$(document).ready(function(){
var user = { name:"Ofer", age:"29" }
var markup = _.template($("#userTemplate").html(), user);
$('#userContainer').html(markup);
});
html part(goes inside body)
<div id="userContainer">
</div>
<script id="userTemplate" type="text/template">
<fieldset>
<legend>User</legend>
Name: <%= name %><br>
Age: <%= age %> <br>
</fieldset>
</script>
The function _.template($("#userTemplate").html(), user); can be called from within the complete callback function of the ajax, passing the data from the results to the function (user variable would be the data)
Using https://api.jquery.com/prop/
yourObj = [];
//now fill your object with your data
$row = $("td.yourClass")
$row.prop("dataObj", yourObj );

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>

Using jQuery on AJAX response data

I'm looking to use jQuery to determine if the current page has changed upstream, and if so, perform some action.
I want to do this by using jQuery selectors over the data returned by an AJAX call (for the purposes of this question, my "page has changed" metric will be "has the content of first <h1> changed").
Thus I find myself wanting to use jQuery selectors over the HTML returned by an AJAX get(). The "best" "solution" I've found thus far is appending the data to some hidden div, and using a selector over that, as below:
var old_title = $('h1').html();
$.get(url, function(data) {
$('#hidden_temporary_storage').append(data);
var new_title = $('#hidden_temporary_storage h1').html();
if (new_title !== old_title) {
do_something();
}
});
This feels so very wrong - I'd be nesting html / head / body tags, and there would be id collisions et cetera.
I have no control over the upstream page, so I can't just "get the data in a more convenient format" alas.
You can do:
var x = $('<div>'+data+'</div>').find('h1').html();
// use x as you like
i.e. you don't need to append the returned data to your page to be able to get properties and values from HTML elements defined within it. This way there would be no id collisions, multiple head/body tags etc.
I think your best bet here is to use an iFrame.
And then use jQuery on the content of that iFrame.
var old_title = $('h1').html();
$.get(url, function(data) {
$('<iframe id="tmpContent"></iframe>').appendTo("html");
$('#tmpContent').contents().find('html').html(data);
var new_title = $('#tmpContent').contents().find('h1').html();
if (new_title !== old_title) {
do_something();
}
$('#tmpContent').remove();
});

Categories

Resources