I am trying to make a request across domains like that:
var script=document.createElement('script');
script.setAttribute('src',"http://www.example.com/wordpress/register/?callback=callbackF&ver=2.5&url="+encodeURIComponent(window.location.href));
script.setAttribute("type", "text/javascript");
script.setAttribute("id", "spark_grazit_script");
document.getElementById("spark_static_widget").parentNode.appendChild(script);
As the script will be created, it will be appended to the div that i have and there will be a request. At the end of the request:
function callbackF(data){
console.log('Response has finished'+data);
}
That function should be triggered at the end of the request. All I want is to get the callback function called.
I dont get a cross domain error. But I get this error:
Uncaught SyntaxError: Unexpected token :
Is there a way to achieve what I want without resorting to html5 or jsonp. Can I somehow still get a response with ajax?
UPDATE:
The response is a simple json object
This is the response:
{ "userid":"24645", "token":"40A164ECA4DE4A4F", "script":"<script type='text/javascript'>var dbnwid=16211; var dbnpid=23113; var dbnwebid=19459; var dbnlayout=21; var dbncolor='#000000'; var dbntitlefontsize='14'; var dbnbgcolortype=1; var dbnheader='You might enjoy reading:'; var dbnremindercolor=2; var dbn_protocol = (('https:' == document.location.protocol) ? 'https://' : 'http://'); </script>"}
Is there a way to achieve what I want without resorting to html5 or jsonp. Can I somehow still get a response with ajax?
You're not using ajax. You're doing JSONP (or something functionally identical).
The response from http://www.eya.com/wordpress/register/?callback=callbackF&ver=2.5&url= must be a valid script fragment. From your error message, it isn't. (What I get back when I try it is a 404 page, which would tend to be an invalid script.)
Update: Your response is a valid JSON object, but not a valid JavaScript fragment, because the opening { looks like the beginning of a block rather than the beginning of an object literal to the parser, because it doesn't appear where an expression is expected.
To make it work the way you describe (which is JSONP), the response must wrap that object in the call to the callback named in the URL, like this:
callbackF({ "userid":"24645", "token":"40A164ECA4DE4A4F", "script":"<script type='text/javascript'>var dbnwid=16211; var dbnpid=23113; var dbnwebid=19459; var dbnlayout=21; var dbncolor='#000000'; var dbntitlefontsize='14'; var dbnbgcolortype=1; var dbnheader='You might enjoy reading:'; var dbnremindercolor=2; var dbn_protocol = (('https:' == document.location.protocol) ? 'https://' : 'http://'); </script>"})
More about JSONP here.
Related
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
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>
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!
Hi i want to parse xml/rss from a live url like http://rss.news.yahoo.com/rss/entertainment using pure Java Script(not jquery). I have googled a lot. Nothing worked for me. can any one help with a working piece of code.
(You cannot have googled a lot.) Once you have worked around the Same Origin Policy, and if the resource is served with an XML MIME type (which it is in this case, text/xml), you can do the following:
var x = new XMLHttpRequest();
x.open("GET", "http://feed.example/", true);
x.onreadystatechange = function () {
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
// …
}
};
x.send(null);
(See also AJAX, and the XMLHttpRequest Level 2 specification [Working Draft] for other event-handler properties.)
In essence: No parsing necessary. If you then want to access the XML data, use the standard DOM Level 2+ Core or DOM Level 3 XPath methods, e.g.
/* DOM Level 2 Core */
var title = doc.getElementsByTagName("channel")[0].getElementsByTagName("title")[0].firstChild.nodeValue;
/* DOM Level 3 Core */
var title = doc.getElementsByTagName("channel")[0].getElementsByTagName("title")[0].textContent;
/* DOM Level 3 XPath (not using namespaces) */
var title = doc.evaluate('//channel/title/text()', doc, null, 0, null).iterateNext();
/* DOM Level 3 XPath (using namespaces) */
var namespaceResolver = (function () {
var prefixMap = {
media: "http://search.yahoo.com/mrss/",
ynews: "http://news.yahoo.com/rss/"
};
return function (prefix) {
return prefixMap[prefix] || null;
};
}());
var url = doc.evaluate('//media:content/#url', doc, namespaceResolver, 0, null).iterateNext();
(See also JSX:xpath.js for a convenient, namespace-aware DOM 3 XPath wrapper that does not use jQuery.)
However, if for some (wrong) reason the MIME type is not an XML MIME type, or if it is not recognized by the DOM implementation as such, you can use one of the parsers built into recent browsers to parse the responseText property value. See pradeek's answer for a solution that works in IE/MSXML. The following should work everywhere else:
var parser = new DOMParser();
var doc = parser.parseFromString(x.responseText, "text/xml");
Proceed as described above.
Use feature tests at runtime to determine the correct code branch for a given implementation. The simplest way is:
if (typeof DOMParser != "undefined")
{
var parser = new DOMParser();
// …
}
else if (typeof ActiveXObject != "undefined")
{
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
// …
}
See also DOMParser and HTML5: DOM Parsing and Serialization (Working Draft).
One big problem you might run into is that generally, you cannot get data cross domain. This is big issue with most rss feeds.
The common way to deal with loading data in javascript cross domain is calls JSONP. Basically, this means that the data you are retrieving is wrapped in a javascript callback function. You load the url with a script tag, and you define the function in your code. So when the script loads, it executes the function and passes the data to it as an argument.
The problem with most xml/rss feeds is that services that only provide xml tend not to provide JSONP wrapping capability.
Before you go any farther, check to see if your data source provides a json format and JSONP functionality. That will make this a lot easier.
Now, if your data source doesn't provide json and jsonp functionality, you have to get creative.
On relatively easy way to handle this is to use a proxy server. Your proxy runs somewhere under your control, and acts as a middleman to get your data. The server loads your xml, and then your javascript does the requests to it instead. If the proxy server runs on the same domain name then you can just use standard xhr(ajax) requests and you don't have to worry about cross-domain stuff.
Alternatively, your proxy server can wrap the data in a jsonp callback and you can use the method mentioned above.
If you are using jQuery, then xhr and jsonp requests are built-in methods and so make doing the coding very easy. Other common js libraries should also support these. If you are coding all of this from scratch, its a little more work but not terribly difficult.
Now, once you get your data hopefully its just json. Then there's no parsing needed.
However, if you end up having to stick with an xml/rss version, and if you're jQuery, you can simply use jQuery.parseXML http://api.jquery.com/jQuery.parseXML/.
better convert xml to json. http://jsontoxml.utilities-online.info/
after converting if you need to print json object check this tutorial
http://www.w3schools.com/json/json_eval.asp
Hit an interesting problem today when trying to upload an image file < 2MB using dojo.io.iframe.
My function to process the form is called, but before the form is posted to the server I am getting the following error:
TypeError: ifd.getElementsByTagName("textarea")[0] is undefined
My function that is used to action the post of the form is :
function uploadnewlogo(){
var logoDiv = dojo.byId('userlogo');
var logoMsg = dojo.byId('uploadmesg');
//prep the io frame to send logo data.
dojo.io.iframe.send({
url: "/users/profile/changelogo/",
method: "post",
handleAs: "text",
form: dojo.byId('logoUploadFrm'),
handle: function(data,ioArgs){
var response = dojo.fromJson(data);
if(response.status == 'success'){
//first clear the image
//dojo.style(logoDiv, "display", "none");
logoDiv.innerHTML = "";
//then we update the image
logoDiv.innerHTML = response.image;
}else if(response.status == 'error'){
logoMsg.innerHTML = data.mesg;
}else{
logoMsg.innerHTML = '<div class="error">Whoops! We can not process your image.</div>';
}
},
error: function(data, ioArgs){
logoMsg.innerHTML = '<div class="error">' + data + '</div>';
}
});
}
The form is very basic with just a File input component and a simple button that calls this bit of javascript and dojo.
I've got very similar code in my application that uploads word/pdf documents and that doesn't error, but for some reason this does.
Any ideas or pointers on what I should try to get this to work without errors?
Oh I'm using php and Zend framework for the backend if that has anything to do with it, but I doubt it as it's not even hitting the server before it fails.
Many thanks,
Grant
Another common reason for this error is the server isn't packaging the data correctly. This means even if you have set "handleAs: json" you have to send that json wrapped in some html. This is what it should look like:
<html>
<body>
<textarea>
{ payload: "my json payload here" }
</textarea>
</body>
</html>
Your error was saying it couldn't find the textarea in your return from the server. For more look at http://docs.dojocampus.org/dojo/io/iframe
Since the load handler of dojo.io.iframe.send() has been triggered, the request should have been sent to the server and response is back. I think the response from server is not correct. Maybe the server returns an error page.
Use Firebug to inspect current page's DOM and find the transporting iframe created by Dojo and check its content. Firebug can capture iframe I/O too, check its Net tab. You may find the root cause of this issue.
Did you respect the constraint written in the doc ?
IMPORTANT: For all values EXCEPT html and xml, The server response should be an HTML file with a textarea element. The response data should be inside the textarea element. Using an HTML document is the only reliable, cross-browser way this transport can know when the response has loaded. For the text/html (Or XML) mimetype, just return a normal HTML/XML document. In other words, your services for JSON and Text formats should return the data wrapped as the following: