Possible to load data into a javascript file? - javascript

I have a fly out javascript menu that is initialized using the onload event. All of the data inside the menu right now is hard coded but needs to be dynamic and will come from my database. Is there a way to build this javascript file with my database values? Is this possible? I'm a total noob to JS so please spell things out for me.
Maybe an example of what I'm thinking will help. This is part of my JQuery file after I have my serialized array. How do I get the array into the menu from here?
if(data.success == 0) {
// error
} else {
// my array that needs to be exported into the JS file.
}
This is the other file that I'm talking about that needs to be built with the data from the database.
function create_menu()
{
document.write(
'<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' +
'<td class="td" valign="top">' +
'<h3>Test</h3>' +
'<ul>' +
'<li>afd</li>' +
'<li>fsg</li>' +
'<li>sfg</li>' +
'<li>fsg</li>' +
'</ul>' +
'</td></tr></table>');
}

One option would be to build the JavaScript file dynamically on the server when a request comes in from the browser using one of the various server-side scripting languages. The downside to this method is that that browsers may cache the file and, therefore, may operate with stale data.
The other option is to use a static JavaScript file and use an AJAX call to get the latest menu options and then render them into the page's DOM. This would be better than the first option since you wouldn't have the caching concerns.
The third method is to dynamically generate the markup for the page and not worry about requesting a menu via JavaScript. This is the best option in my book. I wouldn't want to wait for the navigational elements of a page to be requested via JavaScript when it's something simple that should already be part of the page.

You need to use AJAX.
You can load the contents from back-end into a JavaScript array and use that. This is how dynamic data is fetched from the server without a page refresh.
Hope this helps.

JSON is a data format which can be executed using eval(). Create some JSON which represents whatever format you've hard-coded and evaluate it like in Wikipedia's example
This is only okay if you trust the source of the JSON, in this case you're generating it yourself so it should be okay.
example, json_menu.php returns the text:
create_menu( { "menus" : ["afd", "fsg", "sfg", "fsg"] } );
And you execute it like this by evaluating it:
function create_menu(JSONData)
{
var s = '<table cellpadding="0" cellspaceing="0" border="0" style="width:98%"><tr>' +
'<td class="td" valign="top">'
// loop through each one
for(var menu in JSONData.menus)
s = s + '<li>' + menu + '</li>';
s = s + '</ul></td></tr></table>';
// write it out
document.write(s);
}
// this gets called somewhere in your OnLoad
function yourOnLoader()
{
var ajaxRequest = new ajaxObject('http://your-site.com/json_menu.php');
ajaxRequest.callback = function (responseText) { eval(responseText); }
ajaxRequest.update();
}

Related

javascript - Getting a JSON array

So I have a stock website that I want to be able to obtain the JSON information from either Google's API or Yahoo's API website. I am currently just testing so that is why I used a replacement function for my console log to print it onto a text box for my testing atm. I can not seem to get this to work correctly, I have looked on other pure JS script, but I am currently stump, I have read past posts, but they're very similar in answers, and I have tried implementing.
It works with a fully JSON string, with just {}, where I can just access the inner elements. However, even accessing it, what I believe to be the correct way, it does not seem to work. And I tried with other API with a different method and it worked fine.... Anyone can explain? And I also tried using $.getJSON
$.get("http://d.yimg.com/aq/autoc?query=y&region=US&lang=en-US", function(data) {
var dropDownHTML;
var stock = data.ResultSet.Result;
for (var i = 0, len = stock.length ;i<len;i++){
dropDownHTML += '<option value="' + stock[i].symbol + '">' + stock[i].name + '</option>';
}
document.getElementById("options").innerHTML = dropDownHTML;
});
</script>
</div>
The problem is simply that the website you are scraping from has specifically blocked HTTP requests. You'll need to connect with HTTPS instead:
https://mysafeinfo.com/api/data?list=englishmonarchs&format=json
Also, you're returning a large array of objects from your scrape -- you'd need to loop through, and log the contents of each object individually:
for (var i = 0; i < data.length; i++) {
console.log(data);
}
I've created a Fiddle showing a working scrape here.
Hope this helps! :)

Appending to a dropdown list in Jade using Ajax

I'm trying to add entries to a dropdown list which I have defined in my .jade file as below.
extends layout
block content
script(src='http://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js')
script(src='/javascripts/addsystem.js')
h1= title
p Testing
select#allSystems
And my Ajax method looks like the following:
var select = $('#allSystems');
console.log("Runing script")
$.ajax({
url: '/submit/getAllSystems',
dataType:'JSON',
success:function(data){
$.each(test.system, function(key, val) {
select.append('<option id="' + val.id + '">' + val.name + '</option>');
})
}
});
The Ajax script is located the JS file which is included in the Jade file. (Jquery is also included in the Jade file).
Everything seems to be working fine, except for the append. I.e. the console logs show good data all the way and when printing the select object in the Ajax script the browser recognizes it as a HTML element.
When printing the running "console.log(select);", Firefox console shows the following:
Object { context: HTMLDocument → submit, selector: "#allSystems" }
Any idea what I'm doing wrong?
Jade is a templating language that has to be compiled and executed with the data in order to render HTML. JQuery will not automatically do that for you, which is why your commented-out attempt at select.append failed.
Building the HTML yourself works (though it makes some ugly code and I still dislike string concatenations). However, when you did that you changed to .appendTo, which is going to try and take your select object and append it to the option, which I don't think is what you want.
give this a shot:
select.append('<option id="' + val.id + '">' + val.name + '</option>');
If that doesn't work, then there's something up with your selector that gets you the select variable.
* EDIT *
I notice in your Jade that you are loading your scripts before the rest of the DOM. IF the contents of addsystem.js are as you describe, then you're fetching the data and trying to append it to a DOM node that doesn't exist yet. Try wrapping it like so:
$(function(){ /** your code **/ })
Which is a shorthands to jQuery's methods for doing stuff after the DOM is fully loaded.

using jstl in Javascript

in my jsp page I have:
<form:select path="index" id="sIndex" onchange="showDetails()">
<form:options items="${smth}" itemLabel="name" itemValue="index"/>
</form:select>
And in my javascript function:
*function showDetails() {
var sIndex=document.getElementById("sIndex");
var index=sIndex[sIndex.selectedIndex].value;
var name = '${smth[index].name}';
var address = '${smth[index].address}';
var message = "<table><tr><td>Name:</td><td>" + name + "</td></tr>";
message = message + "<tr><td>Address:</td><td>" + address + "</td></tr>"
message = message + "</table>"
document.getElementById("candDetails").innerHTML = message;
}*
And it doesn't takes the index in ${}, but if I use alert(index) it recognize it.
Java/JSP/JSTL runs at the server side, produces HTML/CSS/JS output and sends it to the client. HTML/CSS/JS runs at the client side, not at the server side as you apparently expected. Open the page in your browser and do a 'view source'. Do you see it?
Javascript only sees the HTML DOM tree in the client side and can access it. You need to get the name and address from the HTML DOM tree. You already have the name in the option element, but the address is nowhere available. You could use JSTL to generate a Javascript array variable so that the Javascript code can use it further.
To learn more about the wall between Java/JSP and Javascript you may find this article useful.
The EL expressions (the code between ${}) are evaluated at runtime of the JSP servlet, not once the page has been rendered in the browser, which is when your JavaScript is being called.
View the generated source of the page and you will probably see the problem.

Best way to get server values into JavaScript in .NET MVC?

Using ASP.NET MVC + jQuery:
I need to use some values owned by the server in my client-side JavaScript.
Right now, I've temporarily got a script tag in the actual view like this:
<script>
var savePath = '<%= Url.Action("Save") %>';
</script>
But I want to move it into something cleaner and more maintainable. I'm thinking of something along the lines of creating a JavaScript controller/action and returning a JSON object that would contain all the data I need, then using the view as the src for a script tag.
Any other ideas?
This actually depends. For simple inliners, the line above works just fine. If you need a LOT of server data in the JavaScript, your view approach may work. However you'll get the same result if you just render partial view that outputs the required JavaScript.
There's a problem with this, since you may end up mixing server data with JavaScript. The best approach would be to minimize server data to absolute minimum, and pass it to JavaScript functions instead of mixing with JavaScript code. That is, not
function func() {
var path = '<%= Url.Action("my") %>';
$(".selector").append("<img src='" + path + "' />");
}
but
function AppendImageToSelector(path) {
$(".selector").append("<img src='" + path + "' />");
}
function func() {
var path = '<%= Url.Action("my") %>';
AppendImageToSelector(path);
}
This makes the code cleaner and easier to understand, helps to move JavaScript out to separate .js files, helps to re-use JavaScript when needed, and so on.
If you need a lot of server-related URLs in JavaScript, you may want to create global (in master page) function like
function url(relative) {
return '<%= Url.Content("~") %>' + relative;
}
and use it from JavaScript scripts. This technique is questionable, though; for example it doesn't use MVC routing rules so URLs may not be out of sync; etc.
I know this is not applicable in all cases but when I need to pass an Url to a client script (as in your example) it is often to ajaxify some anchor or button I already have in the DOM:
<%= Html.ActionLink("Save data", "save") %>
and in my script:
$('a').click(function() {
$.get(this.href);
return false;
});
Stephen Walther - ASP.NET MVC Tip #45 – Use Client View Data

Trying to use jQuery to display JSON text data

I know very little (none) JavaScript, or much about using API's. However I would like to display some hotel reviews on my webiste made available over the qype.com API. However I'm struggling with being able to manage this.
This is the code I have so far:
$(document).ready( function() {
$.getJSON( "http://api.yelp.com/business_review_search?term=hilton%20metropole&location=B26%203QJ&ywsid=APIKEY Removed",
function(data) {
$.each( data.businesses, function(i,businesses) {
content = '<p>' + businesses.reviews.text_excerpt + '</p>';
content = '<p>' + businesses.reviews.date + '</p>';
$(content).appendTo("#review");
} );
}
);
} );
I have a div in the body called review where I want to display the text.
Any advice greatly received.
JSON can be found at http://api.yelp.com/business_review_search?term=hilton%20metropole&location=B26%203QJ&ywsid=lOoGGbkYpVmTvxHlWGT2Lw
Also, I have multiple businesses on the same page, how would I make use of this multiple times on the same page, but output the data in different locations?
Update: Ah, I see your error now. businesses.reviews is an array (each business can have more than one review) so you have to loop over each business and each business' reviews.
i had to change some things to get it to run in my test bed, but you can see a sample of this code running here: http://bit.ly/4mTxPp
yelp currently support JSONP calls so you can change your code to:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function showData(data) {
$.each(data.businesses, function(i,business){
// extra loop
$.each(business.reviews, function(i,review){
var content = '<p>' + review.text_excerpt + '</p>';
content += '<p>' +review.date + '</p>';
$(content).appendTo('#review');
});
});
}
$(document).ready(function(){
// note the use of the "callback" parameter
writeScriptTag( "http://api.yelp.com/business_review_search?"+
"term=hilton%20metropole"+
"&location=B26%203QJ"+
"&ywsid=lOoGGbkYpVmTvxHlWGT2Lw"+
"&callback=showData"); // <- callback
});
function writeScriptTag(path) {
var fileref = document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", path);
document.body.appendChild(fileref);
}
</script>
Do you get an error in Firebug using this code? What happens exactly?
I expect this problem is caused by the fact that you're trying to do a cross-domain request which is not allowed. Normally you'll want to do this kind of data gathering on your back-end, but you can use an alternative such as JSONP to do the same.
Take a look at jQuery's documentation on this stuff and it should be clear what's going on.
Also, as a side note: In your callback you have content = which is ok but not ideal. Assigning to content like this will create a variable in the global scope which you do not want. In this case it probably wont cause an issue but say you have 2 of these requests going at once, the second assignment could easily step on the first causing hard-to-debug weirdness. Best to just always create variables with var.
If data.businesses is an array, I would assume that data.businesses[x].reviews is also an array. This code loops the businesses as well as the reviews for each business. It also gets rid of the content variable by appending straight to the #review div.
$.each(data.businesses, function(i,business){
$.each(business.reveiws, function(r,review){
$("#review").append(
'<p>' + review.text_excerpt + '</p>'
).append(
'<p>' + review.date + '</p>'
);
});
});
I think you can specify JSONP with your $.getJSON method by adding "callback=?" to the url parameters.
As of jQuery 1.2, you can load JSON
data located on another domain if you
specify a JSONP callback, which can be
done like so: "myurl?callback=?"
$.getJSON("http://api.yelp.com/business_review_search?term=hilton%20metropole&location=B26%203QJ&ywsid=APIKEY Removed&callback=?",
function(data){
...
});
The problem is that you are making a cross domain request, which is not allowed for security purposes. Either you will have to make a proxy script on your domain (like for example in php) and call yelp from that or fetch the data completely on the server side.
I assume you must be experiencing part of your data (which you are supposed to see) disappearing. I think you must edit your code to:
content = '<p>' + businesses.reviews.text_excerpt + '</p>';
content += '<p>' + businesses.reviews.date + '</p>';
Hope this helps...

Categories