Send and receive data to and from another domain - javascript

I'm trying to write a plugin. I can not use any libraries or frameworks.
At any website (domain) I would like to start a script from my own domain.
For example:
In the code of the website under domain A I put a code starting the script from domain B
<script src="http://domain-b.com/myscript.js" type="text/javascript"></script>
The code of JavaScript (myscript.js)
type = 'GET';
url = 'http://domain-b.com/echojson.php';
data = ‘var1=1&var2=2’;
_http = new XMLHttpRequest();
_http.open(type, url + '?callback=jsonp123' + '&' + data, true);
_http.onreadystatechange = function() {
alert(‘Get data: ’ + _http.responseText);
}
_http.send(null);
Script from http://domain-b.com/echojson.php always gives the answer:
jsonp123({answer:”answer string”});
But in a JavaScript console I see an error (200) and AJAX doesn’t get anything.

Script loaders like LAB, yep/nope or Frame.js were designed to get around the same-origin policy. They load a script file, so the requested file would have to look like:
response = {answer:”answer string”};

If you use your code like you have posted it here, it does not work, because you are using apostrophs for the data variable!

Related

JavaScript XMLHttpRequest send fails

I try to make an AJAX requestin Chrome using the following code:
var url = "http://" + document.domain + "/status_data.lua?resetsessiontimeout=false";
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
Using WireShark is see that send doesn't send anything... There is no GET emitted.
But if I add an & at the end of the URL:
var url = "http://" + document.domain + "/status_data.lua?resetsessiontimeout=false&";
^
then send will emit the GET request.
Is this expected?
I'm going to guess a couple of common errors people (and I) have made.
Did you create an instance of xmlhttp? In otherwords, do you have a line before your code above that has "var xmlhttp = new XMLHttpRequest();" (case sensitive)
Are you testing this through a file (like C:/test.html) or on a webserver (like Apache or jboss)? If you do the former, you'll get a Cross Point Origin error and doing the latter will fix it.
Are you sure the server code is not looking for additional variables after resetsessiontimeout? Because the '&' is used to delimit additional variables. Although I'm pretty sure it was unneeded to end a variable.
Like if I wanted to send an error string with that url. I can do
resetsessiontimeout=false&errmsg=test

How to run url from ".js" file?

Enviroment: Visual Studio 2012, MVC4, Razor, Internet Application.
I'm working with eBay API and I want to show the search results (JSON).
I have a view page with code...
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push('<tr><td>' + '<img src="' + pic + '" border="0">' + '</td>' +
'<td>' + title + '</td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("results").innerHTML = html.join("");
}
</script>
This line in ".js" file:
var url = "http://ebay.com?..."
How can I execute this url from ".js" file automatically, when I openning this View Page? (This url sending request to Ebay server and receiving data, which will be showed on this View Page.)
I will change a question a little...
If I'm running this code from the View page, everything works fine:
<script src=http://ebay.com?... </script>
How can I receive this part("http://ebay.com?..." as a variable) from ".js" file? Is it possible?
If you just want to send the request, you could add an image to the DOM with that as the src, for instance.
If you want to receive data from the request, you're going to have to do an AJAX call. This is handled quite differently in different browsers, so here's a good idea to use a framework, such as jQuery.
Since the URL is on a different domain than yours, however, you won't be able to access it with a regular AJAX request. You'd have to refer to what is called a JSONP request. This requires that the document you're fetched is formatted in a specific manner to allow this. If it isn't, JavaScript simply won't allow this interaction, due to the Same-Origin Policy.
JSONP requires that the remote document has the following format:
someCallbackFunction(javaScriptObjectWithData);
If it does, you'd be able to include a script file to the DOM with that URL as the src, the content of the document, once fetched, will be immediately executed in your browser. You should by then have specified a callback function with a name matching the callback being made in the document (this is usually something you can specify with through querystrings in the original request).
If none of these options are available for you, because of the format of the remote document, then you're going to have to request the document from server side. If you don't have access to a serverside environment yourself, in order to do this, there is the option of using somebody elses server. Yahoo's custom query language – YQL – can be used for querying the content of remote documents, and YQL is available through JSONP, so you could possibly relay your request through them.
See this post on using YQL with JSONP
Update, now that you've added more data, eBay API is available for JSONP, and I think that's the solution you're looking for.
Resolved...
<script src="/Scripts/ebay.js" type="text/javascript"></script>
<script>
s = document.createElement( 'script' );
s.src = url;
document.body.appendChild( s );
</script>

JavaScript: How to open a returned file via AJAX

This is similar to: How to open a file using JavaScript?
Goal: to retrieve/open a file on an image's double click
function getFile(filename){
// setting mime this way is for example only
var mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
jQuery.ajax({ url : 'get_file.pl',
data : {filename:filename},
success : function(data){
var win = window.open('','title');
win.document.open(mime);
win.document.write(data);
win.document.close();
}
});
}
jQuery('#imgID').dblclick(function(){
getFile('someFile.docx');
});
I'm doing this off the top of my head, but I think the above would work for text files, but not binary. Is there a plugin that does this properly? The ideal would be to open the file in the browser (or application), rather than download, but I doubt that is a dream. If the file must be downloaded with the save/open dialog, that's fine.
Edit:
One piece of information that I forgot to mention is that I'd like this to be a POST request. This is partly why I was looking at AJAX to begin with. I've seen workarounds that have created forms/iframes to do something similar, but I was looking for a better handler of the returned info.
Seems to me there's no reason to do this via AJAX. Just open the new window to get_file.pl?filename=... and let the browser handle it. If the user has a plugin capable of handling the Content-Type sent by get_file.pl, the file will display; otherwise, it should download like any other file.
function getFile(filename) {
window.open('get_file.pl?filename=' + filename,'title');
}
jQuery('#imgID').dblclick(function() {
getFile('someFile.docx');
});
Edit: If you want to POST to your script, you can do it with some <form> hackery:
function getFile(filename) {
var win = 'w' + Math.floor(Math.random() * 10000000000000);
window.open('', win,'width=250,height=100');
var f = $('<form></form>')
.attr({target: win, method:'post', action: 'get_file.pl'})
.appendTo(document.body);
var i = $('<input>')
.attr({type:'hidden',name:'filename',value:filename})
.appendTo(f);
f[0].submit();
f.remove();
}
Of course, this is somewhat silly since it is impossible to hide your data from "prying eyes" with developer tools. If your filename really is sensitive, issue access tokens to the client, and look up the data in your sever script.

Loading external JSON file as a javascript variable

I thought this question would be trivial but I just can't seem to find an answer.
A website (different origin, no control over it) is making available some JSON files. I want some variables of my script to grab the content of those files. I don't care whether it is done synchrnously or not. How would you go ?
using JSONP consist of using your url, with parameters, and add a script file to your page
www.example.com/process?value=1&callback=Func
add the script to your page.
var url = "www.example.com/process?value=1&callback=Func";
var script = document.createElement('script');
script.type= ' text/javascript';
script.src = url;
document.getElementsByTagName("body")[0].appendChild(script);
now you can use the call back function or access the variables that were added from this script.
UPDATE
At the end of your jsonp script you can call your call back function
Ex: php
<?php
if (isset($_GET['callback'])) {
echo $_GET['callback']."();";
// Func(); // will call your function and use your variables.
}
If the remote host does not supply JSONP or CORS, then you will need to place a server-side component on your own domain which fetches the JSON for you and serves it locally.

HTML/Javascript - Get text from online file

I have info that Shoutcast outputs as an html file.
The html file looks like this: http://216.118.106.247:443/7.html.
Is there any way to get the last item in that list/array into Javascript as a string?
I want to output the song info in a html file, I assume that once I get it into JS as a string that I can use the document.write() function to output the code...
Thanks!
If you look at http://code.google.com/chrome/extensions/xhr.html, you'll need to set up cross-origin requests and then you should be able to use the XMLHttpRequest to fetch the data.
EDITED:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = process;
xhr.open("GET", "http://216.118.106.247:443/7.html", true);
xhr.send();
function process()
{
if (xhr.readyState == 4) {
var resp = JSON.parse(xhr.responseText);
// resp now has the text and you can process it.
alert(resp);
}
}
Take a look at XMLHttpRequest aka Ajax requests.
There are a ton of libraries that make "Ajax" easy. Try this one:
http://www.prototypejs.org/api/ajax/request
There are limitations with what you can retrieve using ajax. Due to security issues your browser will not let javascript running on yourwebsite.com perform ajax requests to mywebsite.com.
Look up cross site scripting.
There are several methods out there for you to use. But make sure files are in the same server or folder.
Using XMLHttpRequest: http://www.javascripter.net/faq/xmlhttpr.htm
Using FileSystemObject: http://msdn.microsoft.com/en-us/library/czxefwt8(v=VS.85).aspx
Using a "helper" Java applet that reads a file or URL for your script
var fileContent='';
var theLocation='';
function readFileViaApplet(n) {
document.f1.t1.value='Reading in progress...';
document.ReadURL.readFile(theLocation);
setTimeout("showFileContent()",100);
}
function showFileContent() {
if (document.ReadURL.finished==0) {
setTimeout("showFileContent()",100);
return;
}
fileContent=document.ReadURL.fileContent;
document.form1.textarea1.value=fileContent;
}
Some other source to reference: http://www.c-point.com/JavaScript/articles/file_access_with_JavaScript.htm (many examples).
Just write a javascript file (js file) and include with the script tags.
This file will have your data like that.
<script type="text/javascript" src="data.js" >
where data.js can be..
var data[];
data[0]="something";
e.t.c
In your page (the one that calls data.js) the array data will be accessible.

Categories