accessing object properties in javascript - javascript

I wrote this code and when I want to access object properties it keep saying undefined. can anyone point out my error.
function readXML()
{
var xml=new XMLHttpRequest();
xml.open('GET','index.json',false);
xml.send();
var xmlData=xml.responseText;
document.getElementById("demo").innerHTML =
xmlData.firstName + " " + xmlData.lastName;
}
the json file
{firstName:"John", lastName:"Doe", age:20}

I remembered reading about this because of trying to use it, you are missing a simple function called every state change for the request
Edit, corrected function
Realizing you have ,false) set for the async option, it has been deprecated and is no longer supported, so this function is mandatory.
xml.onreadystatechange = function()
{
if (xml.readyState == 4 && xml.status == 200)
{
var xmlData = JSON.parse(xml.responseText);
document.getElementById("demo").innerHTML = xmlData.firstName + " " + xmlData.lastName;
}
};
This code goes right above the xml.open() command.
This function is called on every change of the state of the request, you can also modify it to give an error if you do not receive a xml.status of 200, which means a successfully requested page.
This snippet was edited to fit your function, grabbed from an official website for documenting languages like PHP, JavaScript, JQueryJS, etc.
http://www.w3schools.com/json/json_http.asp
Edit no. 2
Discovered your json wasn't formatted properly, the values and keys must be encased by " or '. Here is what it should look like:
{"firstName":"John","lastName":"Smith"}
from that you can either use xmlData.firstName or xmlData["firstName"] they both do the same thing.
Next, the async parameter has been deprecated, and is completely asynchronous so you have to change your xml.open() to this:
xml.open('GET','index.json');
Finally for the onreadystatechange i modified it to fit your script, the edit is applied above in my previous one.
----- Want to see it live? -----
I have uploaded and corrected it to fit your function, it works and is fully function, with no errors processed, here is a link:
http://js.x10.bz/helpstack/35739016/main.html
Here is the link to the source code:
http://js.x10.bz/helpstack/35739016/main.txt
And finally, here is what the JSON file should look like:
http://js.x10.bz/helpstack/35739016/index.json

Related

Sharing Data Between Javascript Files

I have a script that generates a JSON formatted string. I want to use the data contained in this string in another script. I'm not sure where to even start. I've thought about running both scripts from the same directory and somehow outputting the JSON data into a text file and then loading it into the second script but this seems like more of a workaround than an actual solution. Is it possible to somehow call the second script from the first and pass it the data? Much like passing data between functions in a single script?
FWIW I have tried simply combining the functions the two scripts perform into one, but this has caused me countless headaches with no progress. For simplicity sake I'd prefer to keep the functions performed by each script separate (apart from the obvious data sharing requirement!).
Any advice or a point in the right direction would be greatly appreciated.
If JSON data is less than 5 mb then you can use localStorage to save the output in browser.
In first js file:
function fOne(){
var jsonStr = ''; //insert some json data here
localStorage.setItem("myJson", JSON.stringify(jsonStr)); //save data
}
In your second js file:
function fTwo(){
if (localStorage.getItem("myJson") !== null) {
var passedJson = localStorage.getItem("myJson"); //get saved data anytime
}
}
It is hard to say without some code to reference but maybe just a global variable with a check if its null.
var myJsonString = null;
function one () {
var jsonString = "[]";
myJsonString = jsonString;
}
function two () {
//string not set so bail
if (myJsonString === null) { return; }
}
So it actually depends what environment you are programming in. If its a web browser, all of the code is in the global space actually and is run in order. so if you have <script src="file1"> then <script src="file2"> in your html file, and you put x = 10 in the first file and use it in the second, you will have no problems. If you are using node.js, I can post a solution for that as well, just let me know.
(btw if you put x = 10 in the second file and reference it from the first it will throw an error)
There are ways of avoiding this, such as using a document.ready function or wrapping things in functions and then calling them at the end. You need to make sure that functions and variables are created before being used (this is a common mistake beginners make and are confused by)

Accessing a Javascript variable inside an HTML file

I'm doing a little bit of reverse engineering on the Rapportive API in Gmail.
I make this request
import requests
url ='https://api.linkedin.com/uas/js/xdrpc.html'
r = requests.get(url)
print r.text
The response is an empty HTML file that has a lot of Javascript in it. On line 3661, it sets the RequestHeader for the subsequent call to Rapportive:
ak.setRequestHeader("oauth_token", ae);
Is there a way I can request that page and then return ae?
I think you can try:
Get the page as you already does;
Remove all non-javascript elements from the response page;
Prepend a javascript (described below) in the page's javascript to override some code;
Execute it with eval('<code>');
Check if the token has been set correctly;
I'm proposing the following code to override the XMLHttpRequest.setRequestHeader functionality to be able to get the token:
// this will keep the token
var headerToken;
// create a backup method
XMLHttpRequest.prototype.setRequestHeaderBkp =
XMLHttpRequest.prototype.setRequestHeader;
// override the "setRequestHeader" method
XMLHttpRequest.prototype.setRequestHeader = function(key, val)
{
if ('oauth_token' === key)
headerToken = val;
this.setRequestHeaderBkp(key, val);
}
If you are just interested in retrieving the token can't you just do a regex match:
var str = '<script>var a = 1;...ak.setRequestHeader("oauth_token", ae);...</script>';
var token = str.match(/setRequestHeader\("oauth_token",\s*([^)]+)/)[1];
Although this assumes ae is the actual string value. If it's a variable this approach wouldn't work as easily.
Edit: If it's a variable you could do something like:
str.replace(/\w+\.setRequestHeader\([^,]+,\s*([^)]+)\s*\);/, 'oauthToken = \1';
Before running the JavaScript returned from the page, then the global oauthToken (notice the missing 'var') will contain the value of the token, assuming the the evaluation of the code is run in the same scope as the caller.

Cannot set property of undefined -- inserting text with javascript

I am currently trying to insert some text in a specific spot at a website, http://kawowii.com , however, I keep getting error messages. These error messages seem to originate from the section I am trying to select using javascript (variables txtClasses and styleClasses). The error messages are
Uncaught TypeError: Cannot set property 'textContent' of undefined
So, the variables seem to be undefined but I don't understand why. I have looked at the other answers and still cannot determine what is wrong.
Right now, I have
window.onload = function() {
var txtClasses = document.querySelectorAll("div.coord-control.leaflet-control");
txtClasses[0].textContent = "Server: UP Location:"
}
and I tried this
window.onload = function() {
var styleClasses = document.querySelectorAll(".coord-control leaflet-control");
function insertAfter1(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var brk = document.createElement("br");
insertAfter1(styleClasses[0], brk);
var div = document.createElement("div");
var textNode = document.createTextNode("Server: UP")
div.appendChild(textNode);
insertAfter1(brk, div);
}
My end goal is to change the website, kawowii.com , such that before Location :, it reads Server: UP using javascript.
I executed document.querySelectorAll("div.coord-control.leaflet-control"); on the website you provided, and it does in fact show an array with that element.
I think div.coord-control.leaflet-control is being inserted dynamically (perhaps after an AJAX request completes).
Therefore, you need to put your controlling logic inside the callback of the request:
whateverRequestIsInsertingThatElement.then(function() {
var txtClasses = document.querySelectorAll("div.coord-control.leaflet-control");
txtClasses[0].textContent = "Server: UP Location:"
});
I don't know if you're using promises or if the async method you're using provides a callback, but onload will happen in parallel with your async request, so you need to query for the dynamic element in the callback of the async request.
Not sure which API you're using to generate the map on your website, but usually any calls for location data will happen asynchronously (like the Google Maps API, for example). You can only manipulate dynamically generated DOM elements once the data has arrived.
Edit
You can see that the client is initially getting the configuration data from the route up/configuration. I would suggest looking for where that async call is being made in your source code, and then call querySelectorAll in its success handler.
I also see that in some of your sources, $.ajax is being called, so I assume somewhere in there, $.ajax is being called to the up/configuration route on your server.
So what I imagine happening is this:
You are querying your page for a your leaflet control but its returning an array of nothing. So when you try and access txtClasses[0] its undefined (since txtClasses.length == 0).
// this illustrates your problem
try {
// I am manually creating an empty array (your results)
var txtClasses = []
// this throws the error
txtClasses[0].bad = "throws an error";
} catch (e) {
// this just displays the error for you to see
document.getElementById("log").innerHTML += e.toString()
}
<div id="log"></div>
If you are expecting something back, you should check your selector is actually working (what I like to do is open up a web console and type my code right in there).
I noticed your selector changed in the first and second example too so make sure you read more about css selectors here.

javascript function not taking arguments

This question is probably more complex than I realize.
When the page loads, it checks for a cookie (usercookie). If it exists, it calls a function in an external .js file. This function is situated in a jquery file and does three things. It hides come stuff, sets a variable (userloggedin) to true, and displays a welcome message to the users. However, its acting very strange. In order for the function to work, I have to define it with a "new" before it like its an object. If I don't do that, it won't work at all. But if I use it, it refuses to take any arguments. Take a look.
Keep in mind that this is situated in a $(document).ready(function() {}
userlogged = new function($name)
{
userloggedin = true;
$('.socialicons').hide();
$('#signup').hide();
$('#login').hide();
document.getElementById('cookieelement').innerHTML = "Welcome back, " + $name + "!";
}
Here is how I call the function from the main document.
<script type="text/javascript" id="cookiescript">
//checks for the usercookie and gets the value as well
var query = true;
if (query === true)
{
cookievalue =
"Seth";
userlogged(cookievalue);
}
</script>
Some of this code was returned from a php query to mysql, but I know that code works fine.
So my question is, how do I create this universal function in the js file that I can call anytime a user logs in somehow (eg. cookie detected, form entry)?
You have to declare a parameter at the declaration part like
function functionname(parameter)
you need to change the method signature to accept a parameter
userlogged = new function($name)
{
userloggedin = true;
$('.socialicons').hide();
$('#signup').hide();
$('#login').hide();
document.getElementById('cookieelement').innerHTML = "Welcome back, " + $name + "!";
}

I want to request JSON inside of a WordPress page

For the last few hours I've been trying to set up this http://code.google.com/apis/books/docs/dynamic-links.html on a WordPress blog. Google's API sends back a JSON response (which is supposed to be "put" into _GBSBookInfo variable). However, that variable never is assigned so my javascript callback function explodes saying the variable doesn't exist. So far, all of my javascript is in the WordPress header.
I tried this outside of WordPress and it works fine.
This is the static page:
<script src="http://books.google.com/books?bibkeys=0307346609&jscmd=viewapi&callback=response_handler">
This is the handler:
function response_handler(data) {
var bookInfo = _GBSBookInfo["0307346609"]; // the var that doesn't exist
document.getElementById("test123").innerHTML = bookInfo.thumbnail_url;
}
Thanks for any help in advance, WordPress has been extremely frustrating by limiting so much! If I'm doing anything stupid please say so, I'm a new javascript programmer.
EDIT:
I've used firebug so far to identify the problem to be: the _GBSBookInfo variable never gets "created" or "exists". I'm not sure how javascript works at this level. Hopefully this helps.
ERRORS:
Error: _GBSBookInfo is not defined
Line: 79
Try replacing _GSBookInfo with data, like so:
function response_handler (data) {
var bookInfo = data["0307346609"];
document.getElementById("test123").innerHTML = bookInfo.thumbnail_url;
}
Based on your post, google returns this:
response_handler({
"0307346609": {
"bib_key":"0307346609",
....
"thumbnail_url":"http://bks2.books.google.com/books?somethumbnailstuff"
}
});
... so the above code should work for you.

Categories

Resources