I want to make a little web page which calculates stuff, based on various data from another site. Let's say for an online browser game.
I would like to have it take some specific details from the web pages on the game, but I don't even know where to start.
Is this doable with javascript (if not I would like to know with what language it is)? Could anyone give me a general of guideline of how this can be done?
You can use a combination of AJAX and XMLHTTPRequest, but these are subject to the same origin policy.
Of course, it would make it a lot easier if the external site can send back data in JavaScript Object Notation format (JSON) for readability.
There is a similar question asked here for how to obtain the contents of an external site using XMLHTTPRequest here: How to specify an external website for XMLHTTPRequest
There is another similar question on using XMLHTTPRequest and JSON: Cross-domain JSON request?
I have a standard function for using AJAX to get information dynamically. I use PHP as my listener. Your listener would have to be able to accept variables from the URL, like PHP $_GET[].
In the example below, your listener named "source_url.php" would have to check the values received in $_GET[field] and then simply print/echo the result.
JAVASCRIPT:
function get_(url, func)
{
var http;
try { http = new XMLHttpRequest(); } catch (e) { try { http = new ActiveXObject(\"Msxml2.XMLHTTP\"); } catch (e) { try { http = new ActiveXObject(\"Microsoft.XMLHTTP\"); } catch (e) { alert(\"Your browser broke!\"); return false; } } }
http.open(\"GET\", url, true);
http.onreadystatechange = function() { if(http.readyState == 4) { func(http); } }
http.send(null);
}
function get_info(fieldname)
{
get_("source_url.php?field=" + fieldname, showResult)
}
function showResult(h)
{
alert("The result is: " + h.responseText);
}
HTML
<button onClick='get_info("name");'>Get the ship Name</button>
<button onClick='get_info("reg");'>Get the Registration Number</button>
<button onClick='get_info("capt");'>Who is the Captain?</button>
PHP
<?php
if ($_GET[field] == "name") { print "U.S.S. Enterprise"; }
if ($_GET[field] == "reg") { print "NCC - 1701"; }
if ($_GET[field] == "capt") { print "Jean Luc Picard"; }
?>
I use this all the time, though I have created a more advanced version with authentication security. This is where you should start if you are just learning how AJAX works.
Related
I'm trying to write a JavaScript function that gets a foreign url, and attempts to verify its existence within 'tmOut' msecs. If verified within this timeframe, it should call a 'callback' function with this url as an argument.
Here is the function:
function chkUrl(url, tmOut, callback) {
var abortChk = false;
var abortTmr = setTimeout(function(){abortChk = true;}, tmOut);
var x = new XMLHttpRequest();
x.onreadystatechange = function() {
if (x.readyState == 4) {
if (x.status < 400 && !abortChk) {
clearTimeout(abortTmr);
callback(url);
}
}
};
x.open('GET', url, true);
x.send(null);
}
Problem is because of cross-domain calls (probably) I get x.status=0 regardless of the url existence.
Is there a way to overcome/workaround the problem (without the users having to modify any default browser settings)? Alternatively, is there a way to achieve the same functionality otherwise?
Is this function "reentrant"? (can I call it safely several times for different urls at once?)
Is there a way to overcome/workaround the problem
Client side? Only if the sites you are making the request to use CORS to grant you permission (which seems unlikely given the context).
Perform your test from your server instead of directly from the browser.
Is this function "reentrant"? (can I call it safely several times for different urls at once?)
Yes. You aren't creating any globals.
First off, thanks for taking the time to read.
I'm trying to delve into ASP.NET MVC at the moment, however i currently have no wish to use any type of JavaScript framework, so please, don't tell me how much easier it would be etc, in your answer.
I currently have a Javascript function that successfully makes an AJAX call, however i am struggling to understand why no values are being returned from the request.
The function is as follows.
function ajaxRequestUser(num) {
var ajax;
try {
ajax = new XMLHttpRequest();
} catch(e) {
try {
ajax = new ActiveXObject(Msxml2.XMLHTTP);
} catch(e){
alert('old browser');
}
}
ajax.readystatechange = function () {
if (ajax.readyState == 4) {
var queryResult = ajax.responseText;
if (!queryResult) {
alert('No Information.');
} else {
alert(queryResult);
}
}
}
var requestString = "?user="+num;
ajax.open("GET", "/Users/GetUser" + requestString, true);
ajax.send(null);
}
The function is called via a separate function that simply does some UI modifications to allow for the display of the data.
The alerts are there at this point, because i was not receiving any data back from the call and i was testing to see if that part of the code was being hit at all (Don't go into the differences between Synchronous and Asynchronous.). No matter how long i waited the data being returned was not being returned, after breaking through the actual server side c#, i saw the data being sent back, but it was just never being received. Is there something in the code that was done wrong? Or am i going about receiving the inbound data in the wrong way?
I have found the issue related to my code, and it is solely an error based around the declaration of my ajax.event where the event is onreadystatechange as opposed to readystatechange
I have found a geocoder website that will give me some data that I need as a variable in my javascript code: http://geocoder.us/service/csv/geocode?zip=95472. the website returns only the content: 38.393314, -122.83666, Sebastopol, CA, 95472. I need pull this information from the website and put it into a string.
abc = "38.393314, -122.83666, Sebastopol, CA, 95472"
How can I accomplish this?
You can use AJAX:
var req = new XMLHttpRequest(); //Create an AJAX object
req.open('GET','http://geocoder.us/service/csv/geocode?zip=95472',true); //Location and method
req.send(); //Send
req.onreadystatechange = function() { //When it's ready
if (this.readyState === 4) { //... which is code 4
console.log(this.responseText); //Then you have the responseText
}
}
This only works when the request is from the same domain, tho (for security purposes). If you want it to work on any domain, you'll have to use a proxy.
You should use Javascript to make an ajax request to that URL and it will return the information you want in a format you specify, usually JSON. Depending on what Javascript libraries you are/aren't using, there's different ways you could do that -- probably the most common would be to use jQuery to make your request. Here's info on that API:
https://api.jquery.com/jQuery.get/
I have a html page using javascript that gives the user the option to read and use his own text files from his PC. But I want to have an example file on the server that the user can open via a click on a button.
I have no idea what is the best way to open a server file. I googled a bit. (I'm new to html and javascript, so maybe my understanding of the following is incorrect!). I found that javascript is client based and it is not very straightforward to open a server file. It looks like it is easiest to use an iframe (?).
So I'm trying (first test is simply to open it onload of the webpage) the following. With kgr.bss on the same directory on the server as my html page:
<IFRAME SRC="kgr.bss" ID="myframe" onLoad="readFile();"> </IFRAME>
and (with file_inhoud, lines defined elsewhere)
function readFile() {
func="readFile=";
debug2("0");
var x=document.getElementById("myframe");
debug2("1");
var doc = x.contentDocument ? x.contentDocument : (x.contentWindow.document || x.document);
debug2("1a"+doc);
var file_inhoud=doc.document.body;
debug2("2:");
lines = file_inhoud.split("\n");
debug2("3");
fileloaded();
debug2("4");
}
Debug function shows:
readFile=0//readFile=1//readFile=1a[object HTMLDocument]//
So statement that stops the program is:
var file_inhoud=doc.document.body;
What is wrong? What is correct (or best) way to read this file?
Note: I see that the file is read and displayed in the frame.
Thanks!
Your best bet, since the file is on your server is to retrieve it via "ajax". This stands for Asynchronous JavaScript And XML, but the XML part is completely optional, it can be used with all sorts of content types (including plain text). (For that matter, the asynchronous part is optional as well, but it's best to stick with that.)
Here's a basic example of requesting text file data using ajax:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange;
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
You'd call that like this:
getFileFromServer("path/to/file", function(text) {
if (text === null) {
// An error occurred
}
else {
// `text` is the file text
}
});
However, the above is somewhat simplified. It would work with modern browsers, but not some older ones, where you have to work around some issues.
Update: You said in a comment below that you're using jQuery. If so, you can use its ajax function and get the benefit of jQuery's workarounds for some browser inconsistencies:
$.ajax({
type: "GET",
url: "path/to/file",
success: function(text) {
// `text` is the file text
},
error: function() {
// An error occurred
}
});
Side note:
I found that javascript is client based...
No. This is a myth. JavaScript is just a programming language. It can be used in browsers, on servers, on your workstation, etc. In fact, JavaScript was originally developed for server-side use.
These days, the most common use (and your use-case) is indeed in web browsers, client-side, but JavaScript is not limited to the client in the general case. And it's having a major resurgence on the server and elsewhere, in fact.
The usual way to retrieve a text file (or any other server side resource) is to use AJAX. Here is an example of how you could alert the contents of a text file:
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange = function(){alert(xhr.responseText);};
xhr.open("GET","kgr.bss"); //assuming kgr.bss is plaintext
xhr.send();
The problem with your ultimate goal however is that it has traditionally not been possible to use javascript to access the client file system. However, the new HTML5 file API is changing this. You can read up on it here.
I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.
How can I get the contains of this JSON file in an object in JavaScript?
This is for example my JSON file located at ../json/main.json:
{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
and i want to use it in my table.js file like this:
for (var i in mainStore)
{
document.write('<tr class="columnHeaders">');
document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
document.write('<td >'+ mainStore[i]['description'] + '</td>');
document.write('</tr>');
}
Here's an example that doesn't require jQuery:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
XHR can be used to open files, but then you're basically making it hard on yourself because jQuery makes this a lot easier for you. $.getJSON() makes this so easy to do. I'd rather want to call a single line than trying to get a whole code block working, but that's up to you...
Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script.
If he can't properly profile native VS jQuery, he shouldn't even be programming native code.
Being afraid means he doesn't know what he is doing. If you plan to go for performance, you actually need to know how to see how to make certain pieces of code faster. If you are only just thinking that jQuery is slow, then you are walking into the wrong roads...
JSON has nothing to do with jQuery.
There is nothing wrong with the code you have now.
To store the variable mainStore, it is a variable in that json.
You should store that json to a variable:
var myJSON = {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]};
var mainStore = myJSON.mainStore;
//.. rest of your code.
I understand that by "reading a json file" you mean making the request to the url that returns json content. If so, then can you explain why you don't want to use jQuery for this purpose? It has $.ajax function that is perfectly suitable for this and covers the browsers' differences.
If you want to read the file then you have to do it server-side, e.g. php and provide it somehow to the dom (there are different methods) so js can use it. Reading file from disk with js is not possible.
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText)
}
};
xhttp.open("GET", "./user.json");
xhttp.send();
}
Naming using the linux filename structure
You can store the responseText to a variable or whatever you want to do with it