When sending GET through jQuerys load the variables are not available - javascript

I am using jQuery to GET the contents of a navigation file and load it into a div on part of my page.
I am supplying it a value containing the page name so I can update the "active" class on the navigation.
Here is the code I am using to show the GET information, this works flawlessly as when I pass it a variable from my browser (i.e header.html?page=foo) it works perfectly.
<script>
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var $_GET = getQueryParams(document.location.search);
alert($_GET["page"]);
</script>
As you can see at the moment it just shows an alert with the value.
When I am calling this page, It is as simple as:
<script>
$("#header").load("header.html?page=bar");
</script>
For the life of me I cannot understand why it is coming back as "undefined" when called from the .load, as I have used it many times before with GET variables.
Any input would be much appreciated,
Kris.

When Javascript is being run by .load, the document is the original document, not the page being loaded.
To pass parameters to the script being loaded, use a global variable.

Related

Storing a variable from an html document to display it in another

On the first page, the user is asked to select a name from a list (select/option tags) and click the "edit" button. User's choice is stored using the "option" variable and we redirect him/her to the next page.
When the body of the next page loads, it triggers the second function, which displays the option made previously as the main header of the page.
The problem is that, although onEdit() runs, displayOption() displays the variable as the empty string (as declared above the functions).
Why doesn't the second function "see" the alteration?
var option = "";
//"edit" button (onclick)
function onEdit() {
var selector = document.getElementById("selector");
option = selector.options[selector.selectedIndex].value;
window.location.href = "nextPage.html";
return false;
}
//"nextPage.html" body (onload)
function displayOption() {
var header = document.getElementById("header-main");
header.innerHTML = option;
}
Use local storage for that, it is easy to use and in this case highly appropriate.
See mdn docs
Example
on first page simply declare
localStorage.setItem('option', 'selectedOption');
on the second page get the var
var option = localStorage.getItem('option');
EDIT
as wendelin commented it is even more appropriate to use session storage, because it remove itself automatically.
The reason this doesn't work is that when nextPage.html loads, the entire script is re-evaluated, and option is now back to its default value of "".
You'll need another solution to persist the user's choice across refreshes. One of the more common approaches to something like this is to set the value as a query string parameter that can be read from within displayOption.

setting a variable in javascript to be used in another form

I have form with a Grid (telerik), i think the technology behind it doesnt matter. I let user click on a row in the grid. During the click I extract a value from the Grid with Javascript, like so:
function RadDrillDoubleClick(sender, eventArgs) {
var Code = eventArgs.getDataKeyValue("Status");
if (Code == "In Progress" || Code == "")
{
location.href = "Main1.aspx?mode=edit&DID=" + eventArgs.getDataKeyValue("D_ID");
}
else {
location.href = "Main1.aspx?mode=view&DID=" + eventArgs.getDataKeyValue("D_ID");
}
}
After user has clicked the grid, I call this JS function and send them to correct .aspx page with either VIEW or EDIT mode dependent directly on the Code.
What I'm trying to do is once I get to the Main1.aspx page, I want to be able to continue to hold the CODE value, because when users performs a certain action, I'll need to call a javascript function and use the actual CODE to determine what the user will be able to do.....
var Code = eventArgs.getDataKeyValue("Status");
is there any way I can somehow create like a GLOBAL Variable called
CodeValue
that I can pass around to another form without doing it in the URL?
When the browser navigates to a page, all current JavaScript is unloaded from the browser. This means any functions/variables, etc. will not be accessible on the new page unless you've persisted the value in some way.
Common ways of persisting the value include:
Add it to the query string of the URL the user is navigating to
Save the value to a cookie
Save the value to local/session storage
For your scenario, #1 is probably your best bet (keep in mind the user can have multiple browsers/tabs open to your site).
One way to get the value from URL is like this: on the page Main1.aspx, you add to your JavaScript a function that will run after page loads and that will get what it needs from the current URL
var globalValue; // variable that will receive the value from URL
window.onload = function() {
var thisURL = window.location.href;
globalValue = url.split("?").pop();
// this will store in globalValue everything that comes after the last "?"
// example: if the url is www.site.com/text?value, it will store string "value" to globalValue
};

Script executing before page load

I've finished off a script that runs on a page that contains a textarea where an email goes.
I'm doing a variety of things on this page, however one of these is to load an iframe, based on a selected number, then once the iframe loads grab the relevant details I need from this page.
I've written the code for this inside a function called frameLoaded and I'm setting this as the onload event, yet the script still runs in to an error where it can't find the .innerHTML of an element.
If I load the iframe and then execute this script it works fine, however if I try to load the iframe and execute the script together then it runs in to this error.
Here's the code I'm using:
//Getting text currently in the textarea
var selectedTxt = document.getElementById('txtEmailText').value;
//Converting it to a string - this is just for troubleshooting purposes that I've used two variables
var insertText = selectedTxt.toString();
//Loads in the highlighted purchase number
var purchaseNumber = window.getSelection();
purchaseNumber = purchaseNumber.toString();
//Declares global variables to hold the title and number
var purchaseTitle;
var purchaseNumber;
//Function to execute code to grab title and number once the frame has loaded
function frameLoaded() {
var iframe = document.getElementById('purchaseIframe');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
purchaseTitle = innerDoc.getElementById('listingTitle');
purchaseNumber = innerDoc.getElementById('auctionSoldIdDisplay');
}
//Checks to see if a purchase number has been selected
if(purchaseNumber.length > 0){
var purchaseIframe = document.createElement('iframe');
purchaseIframe.src = 'http://www.mysite.co.nz/Admin/Listing/PurchaseDisplay.aspx?asid=' + purchaseNumber + '&submit1=++GO++';
purchaseIframe.setAttribute("height","1000");
purchaseIframe.setAttribute("width","100%");
purchaseIframe.setAttribute("id","purchaseIframe");
purchaseIframe.setAttribute("onload", "frameLoaded();");
void(document.body.appendChild(purchaseIframe));
}
//Converting the value in the title to readable text
purchaseTitle = purchaseTitle.innerHTML;
//Placing the values in to the format I need
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
//Placing the values in to the string to go back in to the email textarea
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
//Pasting the variable in to the textarea
document.getElementById('txtEmailText').value = insertText;
Am I doing something wrong here or using the wrong event as it seems to me that maybe it's trying to grab the values before the iframe has fully loaded, hence the error when I'm generating the iframe at the same time.
Please note that I cannot use JQuery
window.onload = function() is your answer.
Note in the example below, the first instance of document.getElementById('mydiv') returns null because the page (DOM) was not yet loaded and therefore neither was the div.
The second instance is fired on the windows.onload which means all the page content is present and can therefore be found.
<script type='text/javascript'>
console.log("Page not ready:" + document.getElementById('mydiv'));
window.onload = function() {
console.log("Page ready:" + document.getElementById('mydiv'));
}
</script>
<div id="mydiv">
</div>

Get input value and insert into table on different page

How would I do the question asked above. I have tried .append() in javascript but can you get data from one html file and insert it into another?? Some please help.
If the page you are receiving the data was created by your js then do it like this.
var childPage = window.open("somepage.html");
The child page would need a global function to receive data, then just call it.
childPage.passData(dataToPass);
If the page to receive the data is the parent, and the input is on the child do like this.
window.parent.someFunction(dataToPass);
Your respective functions would then have to take said data and do the work fro there.
the functions do have to be on the global scope of each page.
Your should wrap the inputs in a<form> whose action attribute is set to the url of the page in which you want to display the values, as shown below:
<form action='url to second page' method='get'>
<input name='name' value='something' />
<button>Submit</button>
</form>
In the second html page, You can retrieve the request parameters by calling the js function given in this answer when it is loaded:
For example,
<html>
<head>
<title>b.html</title>
<script>
function load() {
var params = getRequests();
console.log(params['name']);
}
function getRequests() {
var s1 = location.search.substring(1, location.search.length).split('&'),
r = {}, s2, i;
for (i = 0; i < s1.length; i += 1) {
s2 = s1[i].split('=');
r[decodeURIComponent(s2[0]).toLowerCase()] = decodeURIComponent(s2[1]);
}
return r;
};
</script>
</head>
<body onload='load();'></body>
</html>
The function getRequests() returns an object containing all request parameters with the name of input element as key value. So if your first html page contains an input with name='test', the following code :
var params= getRequests();
var value =params['name'];
will give you the value of test input in second html page. Then you can use DOM API methods such as document.getElementById() to target the table elements in which you want to display the value, and set it's innerText.
can you get data from one html file and insert it into another?
Try .load()
$("#mydivid").load("/myotherpage.html");
To get a specific part of that page
$("#mydivid").load("/myotherpage.html #dividonotherpage");
We can also do something after it has loaded
$("#mydivid").load("/myotherpage.html", function() {
$("#mydivid").show();
/* like grab the values of attributes .. */
});
https://api.jquery.com/load/
edit: / reading #QBM5, I see you might be referring to 'data' as local client side user input from another window. Disregard this answer if so, as this will not pick up changes that are not set as part of the original delivered markup.

copying data from one page to another using phantomJS

I am trying to copy some data from one processed web page into a new one that I want to export. The background is that I need to scrape parts of a page and need to build a new page with parts of the original page.
The problem seems that phantomJs includeJs() and evaluate() methods are sandboxed and I can't see a proper way to import DOM from one page to another.
I have some test code that looks like this, with page being the original and out the new page:
....
var title = page.evaluate(function() {
return title = document.getElementById('fooo').innerHTML;
});
console.log('page title:' + title);
//fs.write('c:/Temp/title.js', "var title = '" + title + "';", 'w');
var out = new WebPage;
out.viewportSize = page.viewportSize;
out.content = '<html><head></head><body><div id="wrapper"></div><p>done</p></body></html>';
out.includeJs('c:/Temp/title.js', function() {
var p = document.createElement('p');
p.appendChild(document.createTextNode(title));
document.getElementById('wrapper').appendChild(p);
});
...
The function in your last includeJs call here won't work - as you note, it's sandboxed, and that means that closures won't work, so title won't be defined. A method of passing variables to page.evaluate is noted as a feature request, but isn't available as of PhantomJS v.1.4.1.
The general way I get around this is by using the Function constructor, which allows you to create a function using a string:
var myVar = {some:"values", I:"want to pass into my page"},
test = new Function("window.myVar = " + JSON.stringify(myVar));
page.evaluate(test);
Now you can evaluate a function like the one you have, referencing myVar in the sandbox, and your data will be available in the client scope.

Categories