I am using jQuery load() to load a partial page into a div. I want to pass url parameters to the partial page like so
<div id='partial'></div>
<script>
$('#partial').load('child_page.html?key=1');
</script>
How do I access these parameters from inside the child page? I tried the following in the child page, but the issue is that the window.location is not giving me child_page.html?key=1 but is giving me the root page url.
<script>
var url = window.location;
//code to parse the url to extract the parameters goes here
</script>
It is not possible for the "child page" to have its own DOM and scripting context, because it was simply retrieved as a string (via AJAX) and inserted into the parent page. Therefore it does not have its own window.location. Everything is added to the DOM of the parent page, and scripts are executed in the context of the parent page.
If you want to share variables between your parent page and the new script loaded with load, you can attach the variable to window and then access it in the script of the "child page".
For example:
// parent page
window.sharedVariable = "Hello World!";
$('#partial').load(url);
// child page
var v = window.sharedVariable;
Working demo (child page)
Update:
Here is an alternate method to support multiple partials, using data attributes to share the variables.
// parent page
$('#partial_1').load(url).data("param", "111");
$('#partial_2').load(url).data("param", "222");
$('#partial_3').load(url).data("param", "333");
// child page
var scriptTag = document.scripts[document.scripts.length - 1];
var parentTag = scriptTag.parentNode;
var param = $(parentTag).data("param");
Basically, we set the data we want to share in the partial's div. And then in the "child page", we find the current running script tag, then the parent tag would be the div that has the data in it.
Working demo (child page)
This takes a slightly different course, but achieves the result you're looking for just as well. You can use the HTML5 History API and do something like this:
history.replaceState(null, null, '?key=1');
var test = $('#partial').load('two.html');
Then from two.html, the window.location.search call will give you ?key=1 and you can parse the query string from there..
How to access URL parameters sent to div via jQuery load()
Edit, Updated
Note, original Question does not appear to include description of script element expected , to run, within returned html from call to .load()
Try utilizing beforeSend to set settings url at jqxhr object , access jqxhr object within .load() complete callback
var url = "https://gist.githubusercontent.com/anonymous/4e9213856be834b88f90/raw/1d90ab5df79e6ee081db2ff8b94806ef27cbd422/abc.html";
$.ajaxSetup({
beforeSend: function(jqxhr, settings) {
jqxhr.params = settings.url
}
});
function loadComplete(data, textStatus, jqxhr) {
$(this).find("h1")
.html(function(_, html) {
return html + " My param is " + jqxhr.params.split("?")[1]
});
};
$("#partial_1").load(url + "?111", loadComplete);
$("#partial_2").load(url + "?222", loadComplete);
$("#partial_3").load(url).load(url + "?333", loadComplete);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="partial_1"></div>
<div id="partial_2"></div>
<div id="partial_3"></div>
jsfiddle http://jsfiddle.net/L9kumjmo/5/
Related
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 pass a parameter to the child window from parent window in Java Script by using window.open.
Please give me any idea.
You can use query string to pass parameters, That's a better approach.
Regarding your requirement of passing parameters by using window.open. You can access some elements and global variables but there value cannot be retained. eg: when you execute the following code
popupWindow = window.open(url,'popUpWindow','height=500,width=500');
popupWindow.alert("test");
you will see an alert when new window is opened. But the data will load after that alert only. So even you are able to set value of any global variable in child javascript, but the value cannot be retained because page loads after window is opened, so data gets refreshed.
I originally tried this:
parent window:
var parms = {arg1: "arg1", arg2:"arg2"};
var handle = window.open(url);
// stringifyed to make sure the child window does
//not try to access object by reference from child to parent.
handle.window.parameters = JSON.stringify(parms);
child window:
$(document).ready(function(){
var args = JSON.parse( window.parameters);
// and so on.
});
The problem was that the value was occasionally being set before the child window was ready so when the child window was ready, it would be undefined.
So Instead, I used sessionStorage (note: this will not work cross domain.)
Parent:
// the user can cause more than one child window so I give storage a unique id.
var parms = JSON.stringify({arg1: "arg1", arg2:"arg2"});
var storageId = "parms" + String(Date.now());
sessionStorage.setItem(storageId, parms);
window.open(url + "?sid=" + storageId);
This on the child:
$(document).ready(function(){
var prmstr = window.location.search.split("=");
var sid = prmstr[1];
var args = JSON.parse(sessionStorage.getItem(sid));
sessionStorage.removeItem(sid);
// and so on
});
When you creating html for child window make a hidden field in html and get in child window.
What kind of parameter? I mean, what's the parameter for?
For example, you could add a GET value in the url:
window.open("http://example.com/script.php?KEY=value")
And then you would have in your (in PHP) $_GET['KEY'] that 'value'
Pass the value as query string
try folowing
window.open("url.php?param=value¶m2=value2");
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>
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();
});
I have an ajax form that I would like to submit, and the response contains two divs, one containing html content and the other containing dynamic javascript in a script tag.
I'm submitting the form and receiving the response ok, but I can't seem to get the javascript to evaluate. I've put an alert inside but it never fires. This is the code I am using to submit the form:
$("#categoryFormSubmit").live("click", function(event){
event.preventDefault();
var action = this.form.action + '?_eventName=' + this.name + 'Ajax';
var params = $(this.form).serialize();
var xhr = $.post(action, params, function(response) {
var responseDom = $(response);
var contentData = $('#content', responseDom).html();
var javascriptData = $('#javascript', responseDom).html();
$('#content').html(contentData);
$('#javascript').html(javascriptData);
}, 'html');
});
In the response I am trying to convert the response data to a DOM object and parse out the content and the javascript, and insert them into the existing dom. The content replacement works fine, but nothing seems to be working with the javascript. I can't get it to evaluate. How should I be doing this? I imagine I shouldn't be trying to insert it into the DOM like I am.
There is no need to manually parse the response and separately add the HTML and JS to your page. jQuery will detect scripts inside of markup you attempt to add to the DOM and will handle the proper addition and execution of them.