Accessing JSON parsed object (works with trace but not without...) - javascript

I'm facing a weird problem after parsing a JSON file. I access the data and can use it only if I use "trace" at the right place ! When I comment the trace line I get "undefined"... Is it a problem of execution order of my code or maybe a problem passing the string argument ?
Thanks in advance for looking for a solution, this problem is very frustrating!!
Here is my code :
//index.js
var language={};
var resourceManager = {};
$(document).ready(function(){
loading();
});
function loading() {
$.ajaxSetup({'beforeSend': function(xhr){
if (xhr.overrideMimeType)
xhr.overrideMimeType("text/plain");
}
});
$.getJSON("json/lang_french.json", function(data) {
language = data;
});
setTitle();
}
function setTitle()
{
var title = resourceManager.getString("welcome");
var query = document.getElementById('title');
query.textContent = title;
}
resourceManager.getString = function(str)
{
//alert(str);//if I uncomment this line, the whole code works...
return language[str];//when the "alert" is commented, return undefined !!!
};
Here is the JSON file : lang_french.json
{
"welcome" : "Bienvenue",
"goodbye" : "Au revoir"
}
and the HTML file, index.html
<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="index.js"></script>
</head>
<body>
<div id="title">
</div>
</body>
</html>

I'm not 100%, but I'd guess that what is happening is that the asynchronous $.getJSON call hasn't completed by the time it gets to "return language[str]" (AKA a race condition). Putting the "alert" in must give it enough time to complete the call.
Try putting "setTitle" in the callback for $.getJSON eg:
$.getJSON("json/lang_french.json", function(data) {
language = data;
setTitle();
});
That means it will wait to make that call until language is actually set, rather than being the empty object {}.

Related

Calling Rest API from Javascript File: Data Return Issue

Hi i have created a javascript file where i make a call to rest api and get data.
I want to return the data to the calling function from html page but the way the call works, i am not been able to.
HTML:
<html>
<head>
<title></title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js" />
<script src="jquery-G5API-1.0.0.js" />
<script type="text/javascript">
function JSFile() {
var result = GetStatus(123456);
alert('HTML: '+ result);
}
</script>
</head>
<body>
<input id="Button1" type="button" value="JSFile" onclick="JSFile()" />
</body>
</html>
query-G5API-1.0.0.js:
function GetStatus(token) {
var url = 'some/url';
var result = '';
$.getJSON(url,function(data)
{
//alert(JSON.stringify(data));
})
.always(function(xhr, status) {
alert( "finished: " + JSON.stringify(xhr));
result = JSON.stringify(xhr);
});
alert('Returning result: ' + result);
return result;
}
The sequence in which alerts are being called:
Returning result: empty_string
HTML: empty_string
Finished: json_data
Any suggestions on how to return json data from .js file to calling function in html file will be highly appreciated.
You'll need to resolve the promise to get your expected result. Check out the
jQuery deferred object api and observe the (simplified) following...
function GetG5Status3(token) {
return $.getJSON('some/url')
}
function JSFile() {
GetG5Status(123456).done(function(response) {
console.log(response);
});
}
JSFiddle Link - simplified demo
Also, I am not seeing any usage of token

the string str is always empty although it is filled with data from the.geojson file any idea?

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#p1").load("reporting/data.geojson").toString();
var str = document.getElementById("p1").innerHTML;
document.getElementById("p2").innerHTML = str;
});
</script>
</head>
<body>
<div id="div1">
<h2>try</h2>
</div>
<p id="p1"></p>
<p id="p2"></p>
</body>
</html>
this is the code, p1 clearly shows on the screen but my actual problem is that i cant fill the string with it, "maybe the load function is the last to act i dont know" kinda new on this. I need to put the .geojson text in a string, or any other way to extract the coordinates would save me the trouble of string eddting. thank you iij advance
You need to use the callback of load to get the data from #p1.
The load method is asynchronous, so the code does not wait for the data to load and executes the next statement.
$(document).ready(function() {
$("#p1").load("reporting/data.geojson", function() {
var str = document.getElementById("p1").innerHTML;
document.getElementById("p2").innerHTML = str;
});
});
As you're using jQuery, you can use html()
$(document).ready(function () {
$("#p1").load("reporting/data.geojson", function () {
$('#p2').html($('#p1').html());
});
});

get value of body onload javascript with PhantomJS

Is there a solution to get the "foo bar" in JS (with jQuery ?) in this code ?
<!DOCTYPE html>
<html>
<body role="application" onload="foo bar">
<div>...</div>
</body>
</html>
I'am using PhantomJS in my script.
EDIT: "foo bar" is an example. It's juste the value I would get.
EDIT 2: my code (wich don't work) is http://paste.awesom.eu/nca&ln.
EDIT 3: PROBLEM(S) AND SOLUTION
After many hours I find many problems and solutions.
First, the website is only accesible in https and I can't include jQuery file from non https url. That's why I have include the jQuery file from the website.
I have debug this with this code :
page.onConsoleMessage = function(msg) {
console.log(msg);
};
Then, I need to change my user agent because the website has a whitelist.
page.settings.userAgent = 'Mozilla/5.0 (X11; Linux x86_64; rv:25.0) Gecko/20100101 Firefox/25.0';
Finaly the code is:
page.open(url, function(status) {
if ( status === "success" ) {
page.includeJs(url_js_file, function() {
page.evaluate(function() {
console.log("> " + $("body").attr("onload"));
});
phantom.exit();
});
}
});
Thank you for comments and anwers.
It looks like you are not returning your variable out of evaluate.
To do that you must
var bodyonload = page.evaluate(function (s) {
return document.body.getAttribute('onload');
}, 'bodyonload');
You were very close to having it.
Here is your code where it returns an object rather than just a variable. I figured it could be useful.
page.open(url, function (status) {
if (status !== 'success') {
console.log('FAILED: ' + status);
} else {
var result = page.evaluate(function (s) {
var result = {
bodyOnLoad: document.body.getAttribute('onload'),
documentTitle: document.title
};
return result;
}, 'result');
console.log(result.bodyOnLoad);
}
phantom.exit();
});
Hope that helps
Edit:
Looked at it some more and perhaps there is a problem with your reference to jquery in page.injectJs(), is jquery in the same directory?
There should be no space between function name, It should like <body role="application" onload="foobar()"> instead of <body role="application" onload="foo bar">
In between HTML head tag,
<script>
function foobar(){
alert('Am loaded');
}
</script>
Try:
document.body.getAttribute("onload")
If you want to get the actual, literal value of onload, use $('body').attr('onload'). This will return the value of any attribute, for any element (assuming jQuery is being used). If not using jQuery, document.body.getAttribute("onload") should do the trick.
Keep in mind that since PhantomJS technically runs outside of the targeted page's DOM, you need to wrap any DOM scripts in page.evaluate:
page.evaluate(function () {
// put your $('body').attr('onload') bit here.
});
This worked for me for returning the value in onload.
<!DOCTYPE html>
<html>
<body role="application" onload="foo bar">
<div>...</div>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
console.log($("body").attr("onload"));
</script>
</body>
</html>

JavaScript to read content between <a> tags

Below is my html page:
<html>
<head>
<title>My Cat website</title>
</head>
<script type="text/javascript" src="script12.js"></script>
<body>
<h1>
My_first_cat_website
</h1>
</body>
</html>
Below is my JavaScript:
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
alert(ans);
if(ans<10)
{
alert(ans);
}
var newans=ans.subString(0,9)+"...";
}
Here my code is not going into if block. My requirement is if var "ans" length is above 10 then append it with ... else throw an alert directly. Can anyone help me?
Here is Solution using data property
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
if(ans.length<10)
{
alert("hmmm.. its less then 10!");
}
var newans= ans.substring(0,9)+"...";
document.getElementsByTagName('a')[0].firstChild.data = newans;
}
Here is it live view you wise to check example: http://jsbin.com/obeleh
I have never heard of the data property on a DOM element. Thanks to you, I learned it's a property on textNode elements (the same as nodeValue).
Also, using getElementsByTagName when the ID is available is unperformant.
subString doesn't work, it is substring. The case is important for methods as javascript is case sensitive (like most programming languages).
The other thing you're missing is an else. In your code, the var newans... will always be ran.
Here is something working:
window.onload = function() {
var ans = document.getElementById( 'message' ).textContent;
if ( ans.length < 10 ) {
alert( ans );
}
else {
var newans = ans.substring( 0, 9 ) + '...';
}
}

Reading Excel file from JavaScript

I have following code for reading excel in javascript :
<html>
<head>
<script type="text/javascript">
function readData(x,y)
{
var excel = new ActiveXObject("Excel.Application");
alert(excel);
var excel_file = excel.Workbooks.Open("D:\File1.xlsx");
Excel.Visible = true;
alert(excel_file);
var excel_sheet = excel_file.Worksheets("DEPT INC UPDATE");
alert(excel_sheet);
var data = excel_sheet.Cells(x,y).Value;
alert(data);
return data;
}
</script>
</head>
<body>
<input type="button" value="SimpleButton" onclick="readData(2,3);" />
</body>
</html>
But dunno where it is going wrong ??
your input element is a submit button, but is not inside a form. When readData returns the data, nothing ever makes any use of it. and as to the rest, i dunno. you don't say where it's going wrong. does it show any one alert box?
i think there is an error in giving the path. Use double backward slashes instead of single.
In your case..
D:\File1.xlsx
Hope this might be helpful..:)

Categories