So I'm trying to get an outside script to complete a login request using XMLHTTPRequest.
The error I'm getting is XMLHttpRequest cannot load http:///.php. Origin http://* is not allowed by Access-Control-Allow-Origin.
Now I've grown quite familiar with this post:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
And from what I understand I need to request it as a JSONP object. The problem with that, is I'm using an XMLHTTPRequest and cannot use the jQuery library to do that.
Here's my code from the html page I'm trying to execute the script from:
<html>
<head>
<meta http-equiv="Access-Control-Allow-Origin" content="*">
<script language = "javascript" type="text/javascript" src="jquery-1.7.2.js">
</script>
<script language = "javascript" type="text/javascript" src="main.js">
</script>
<script type="text/javascript">
function show_prompt()
{
var name=prompt("User Name");
var password =prompt("Password");
var loginWorked = false;
if (name!=null && name!="") loginWorked = init(name,password);
if(loginWorked == true){
window.location = "Toolbar.html"
}
}
</script>
</head>
<body>
<input type="button" onclick="show_prompt()" value="Login" />
</body>
</html>
And the code from my main file:
The init function:
function init(username,password){
//Initializes the toolbar.
init.user = username;
init.pass = password;
init.pass_hashed = sha256(init.pass);
var key = fetchKey(username);
init.pass_hashed += key;
init.pass_hashed = sha256(init.pass_hashed);
var loginParams = "login=1&pwd=" + init.pass_hashed + "&uname=" + init.user + "&LastKey=" + getKey();
loginReqReturn = send_request("http://data.nova-initia.com/login2.php","POST", loginParams);
if(loginReqReturn.responseText != "Error: Login Incorrect "){
return true;
}
else return false;
}
And the sendRequest method:
function send_request(theURL, theMethod, theParams)
{
var theReq = new XMLHttpRequest();
theReq.overrideMimeType("application/json");
theReq.open(theMethod,theURL,false);
if(typeof(theParams) === "string")
{
theReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
else
{
theReq.setRequestHeader("Content-type", "application/json");
theParams = JSON.stringify(theParams);
}
if(_key) theReq.setRequestHeader("X-NOVA-INITIA-LASTKEY", _key);
if(theParams)
{
theReq.send(theParams);
}
setKey(theReq);
return theReq;
}
Not the most efficient code, but it at least works when I execute it in a non-HTML context (I'm working on a toolbar for Google Chrome, but need the html overlay to work). Any help is much appreciated.
I'm not sure what your exact question is, but if you know that using JSONP is the solution that you can do that without using jQuery. Here's how it works: http://en.wikipedia.org/wiki/JSONP
If this is for a Google Chrome Extension, you can request permissions for cross-origin XMLHttpRequest requests within the extension's manifest:
{
...
"permissions": [
"http://data.nova-initia.com/"
],
...
}
Related
My goal is to do a simple get request and display the data to an HTML page.
So first I set up the request in node.js to test it. With node, the data showed up correctly when I ran it with console.log(response).
The problem comes when I try to display the data to the page. Basically, nothing shows up when I try document.getElementByID('demo').innerHTML = response;
I even tried to just use an alert but to no avail.
I am obviously doing something wrong but I am not familiar enough with JavaScript to know.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="demo"></p>
<script>
//causes error in html. Required for node.
// var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
var theURL = 'https://XXXXXX..';
var client = new HttpClient();
let thisReply = null;
client.get(theURL, function(response) {
// var response1 = JSON.parse(response);
// alert(response1);
// console.log(response);
document.getElementById('demo').innerHTML = response;
});
</script>
</body>
</html>
Assuming this is not an issue with the document not finding the element you are looking for, you could try .innerText = response or wrapping your innerHTML elem in some HTML element: <p>${response}</p> I would be sure to also log out that element in addition to the api response to be sure you're grabbing the right thing.
#PrerakSola and #Abdullah Danyal answered the question in the main post comments.
"I checked that and I saw a console error that said Access to XMLHttpRequest at 'APILINK' from origin 'http://...' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource"
ANSWER: "You need to enable CORS on your API server. If you are using node along with express, refer to : expressjs.com/en/resources/middleware/cors.html"
In the console it's giving me the error "Uncaught SyntaxError: Unexpected token : ", but if I access direct SoundCloud URL in my browser then it's giving valid JSON. Earlier this code was working fine and today this issue started.
<html>
<head>
<script src="https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"></script>
</head>
<body>
<h2>hellooo</h2>
</body>
</html>
Update:
Below is the actual code for which I am asking the question, above html I just created for example.
SoundCloud.prototype._jsonp = function (url, callback) {
var target = document.getElementsByTagName('script')[0] || document.head;
var script = document.createElement('script');
var id = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[id] = function (data) {
if (script.parentNode) {
script.parentNode.removeChild(script);
}
window[id] = function () {};
callback(data);
};
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + id;
target.parentNode.insertBefore(script, target);
};
I got the reason of issue, earlier soundcloud were responding response in jsonp but now they are providing JSON even I passed JsonP callback function. I had to make ajax request to fix it.
I used following code to fix it.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback( JSON.parse(this.responseText) );
}
};
xhttp.open("GET", url, true);
xhttp.send();
The following script tag expects JavaScript code in the source and not JSON.
<script src="file.js"></script>
I suppose that you want to use this externally produced json...
A way to "get" it is using an asynchronous ajax request like $.get(url,callback);
Calling it as a script will sure fail...
Because it's not a script.
Try to run the snippet!
var url = "https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"
var json;
$.get(url,function(result){
json = result;
// show in console
console.log(JSON.stringify(json));
// Now using it...
$("#json_usage").html(json.tag_list+" and all the "+json.permalink);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<!--script src="https://api.soundcloud.com/resolve.json?url=https://api.soundcloud.com/tracks/251912676/?secret_token=s-EkyTy&client_id=08f79801a998c381762ec5b15e4914d5"></script-->
</head>
<body>
<h2>hellooo <span id="json_usage"></span> !</h2>
</body>
</html>
In the above, the resulting json is placed in the json variable and then console logged.
Sorry you've been having trouble with JSONP responses from the SoundCloud API. This was due to a bug that made it into production in the last few days. We've just deployed a fix, and so this endpoint will now be returning valid JSONP responses rather than just JSON, if you specify a callback parameter. Sorry for the confusion!
This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 8 years ago.
I referenced code from tutorials on w3schools.com. I don't know what I could be doing wrong, but when I test the site, I get no output. None whatsoever. I'll post the code below.
<!DOCTYPE html>
<html>
<body>
<p id="par1"></p>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://xproshowcasex.api.channel.livestream.com/2.0/livestatus.json?callback=status";
xmlhttp.onreadystatechange=function() {
//readyState 4: request finished and response is ready
//status 200: "OK"
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
//var 'url' is defined above
xmlhttp.open("GET", url, true);
xmlhttp.send();
function status(response) {
var arr = JSON.parse(response);
if (arr.isLive = true) {
document.getElementById("par1").innerHTML = "live";
} else {
document.getElementById("par1").innerHTML = "offline";
}
}
</script>
</body>
</html>
I checked the console log on chrome and is gave me this error:
XMLHttpRequest cannot load http://xproshowcasex.api.channel.livestream.com/2.0/livestatus.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I have looked on the forums for livestream as well as other places and no one can offer me a solid solution. Hopefully someone here can. Thanks for the help!
--Edit--
I have searched this site and have not found a solution for my problem. If anyone knows where there may be a solution, please post a link, but as far as I know, there is none. As we all know, different code has different problems, so i would appreciate an answer rather than a [Duplicate] marking.
<!DOCTYPE html>
<html>
<head>
<meat charset="utf-8">
<title>test</title>
<script src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<!--Livestream status script-->
<!-- CAN BE PLACED IN BODY -->
<script type="text/javascript">
$(document).ready(function () {
function getCrossDomainJson(url, callback) {
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?callback=?",
data: {
q: 'select * from xml where url="' + url + '"',
format: "json"
},
dataType: "jsonp",
success: callback
});
}
/*INSERT STREAM NAME INBETWEEN 'x' eg. http://xSTREAMNAMEx.channel-api.livestream-api.com/2.0/getstream*/
getCrossDomainJson("http://xhellgateospreyx.channel-api.livestream-api.com/2.0/getstream", function(data) {
console.dir(data);
if (data && data.query && data.query.results && data.query.results.channel) {
var statusTest = data.query.results.channel.isLive;
if (statusTest == "true") {
document.getElementById("par1").innerHTML = "online";
}
else {
document.getElementById("par2").innerHTML = "offline";
}
}
});
});
</script>
<!-- end of script -->
<body>
//par1 will change to online if stream is online; par2 will remain as unaffected
//par2 will change to offline if stream is offline; par1 will remain as unaffected
//I separated the p tags for testing purposes, but they can be combined
//if you do so, change the id in the if/else statements
<p id="par1">unaffected</p>
<p id="par2">unaffected</p>
</body>
</html>
If you want more than one stream status, select the code from 'getCrossDomainJson' down to the first '});' and paste in between the two '});' and replace the stream name and the tag in 'getElementById'. Thanks to everyone who helped me with this problem! Hope this helps someone else.
I am learning this stuff so my code might not be pretty... but would appreciate some help :)
I have not written the following code but got it from somewhere else off the web:
function text_xml()
{
realXmlUrl="http://jumac.com/del_me_fruits.xml";
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/xml');
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML;
}
function response_xml()
{
if (self.http_request.readyState == 4)
{
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(http_request.responseText);
}
}
function getFruits(xml) {
var fruits = xml.getElementsByTagName("fruits")[0];
if (fruits) {
var fruitsNodes = fruits.childNodes;
if (fruitsNodes) {
for (var i = 0; i < fruitsNodes.length; i++) {
var name = fruitsNodes[i].getAttribute("name");
var colour = fruitsNodes[i].getAttribute("colour");
alert("Fruit " + name + " is coloured " + colour);
}
}
}
}
And the error I am getting is:
Error: xml.getElementsByTagName is not a function
What am I doing wrong?
responseText is a string, not an XML. Are you looking for responseXML?
Update
If your script is loaded from a different domain than the XML document you're loading (http://jumac.com/del_me_fruits.xml), then XMLHttpRequest will act differently depedning on the browser.
On IE 8, it will pop up a warning window complaining that "The page is accessing information that is not under its control. This poses a security risk. Do you want to continue?" if you click yes, then it will work correctly (i.e., the XML will load and the alerts for the fruits will be displayed).
On Chrome 12, however, it doesn't pop anything and it will say that "XMLHttpRequest cannot load http://jumac.com/del_me_fruits.xml. Origin http://localhost:54671 is not allowed by Access-Control-Allow-Origin." Because of this error, the responseXML property of the request object will be null and you'll see the error you have.
There are other questions regarding cross-domain XMLHttpRequest where you may find how to solve your issues, such as Cross-site XMLHttpRequest and http://code.google.com/chrome/extensions/xhr.html.
<body>
<script type="text/javascript">
function text_xml() {
realXmlUrl = "http://jumac.com/del_me_fruits.xml";
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML; // this doesn't have anything
}
function response_xml() {
if (self.http_request.readyState == 4) {
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(http_request.responseXML);
}
}
function getFruits(xml) {
var fruits = xml.getElementsByTagName("fruits")[0];
if (fruits) {
var fruitsNodes = fruits.childNodes;
if (fruitsNodes) {
for (var i = 0; i < fruitsNodes.length; i++) {
var name = fruitsNodes[i].getAttribute("name");
var colour = fruitsNodes[i].getAttribute("colour");
alert("Fruit " + name + " is coloured " + colour);
}
}
}
}
</script>
<input type="button" value="Click me" onclick="text_xml();" />
<p><div id="ex"></div></p>
</body>
I usually love using a dictionary when working with any kind of transferring data across servers.
MkNxGn.pro provides a sleek way to make XML HTTP requests via MkNxGn Proquest.
Load Proquest, This can be separate from the code<script src="https://mknxgn.pro/scripts/Proquest_Proquest-v1.0.js"></script>
<script>
Proquest("POST",
URL_HERE,
DATA,<br>
HEADERS,
RType,
Ignore JSON errors,
Callback);
</script>
That way you could easily write:
<script>
Proquest("GET", "http://jumac.com/del_me_fruits.xml", Skip, {'Content-type': 'text/xml'}, 'response', false, function(resp) {
resp.overrideMimeType('text/xml'); //Looks like you want it to be XML if its not.
document.getElementById("ex").appendChild(document.createTextNode(" Done!"));
getFruits(resp.responseXML);
});
</script>
ignoring jason's edit to rewrite it better.
Consider using a javascript libary like jquery.
jquery ajax is pretty much self explaining and you don't have to mess with brower compatibility. http://jquery.com/
I'd like to load/insert an external html page into my web page. Example :
<b>Hello this is my webpage</b>
You can see here an interresting information :
XXXX
Hope you enjoyed
the XXXX should be replaced by a small script (the smaller as possible) that load a page like http://www.mySite.com/myPageToInsert.html
I found the following code with jquery :
<script>$("#testLoad").load("http://www.mySite.com/myPageToInsert.html");</script>
<div id="testLoad"></div>
I would like the same without using an external javascript library as jquery...
There are 2 solutions for this (2 that I know at least):
Iframe -> this one is not so recommended
Send an ajax request to the desired page.
Here is a small script:
<script type="text/javascript">
function createRequestObject() {
var obj;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(req) {
var http = createRequestObject();
http.open('get', req);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if (http.readyState == 4) {
var response = http.responseText;
document.getElementById('setADivWithAnIDWhereYouWantIt').innerHTML=response;
}
}
sendReq('yourpage');
//previously </script> was not visible
</script>
Would an iframe fit the bill?
<b>Hello this is my webpage</b>
You can see here an interresting information :
<iframe id="extFrame" src="http://www.mySite.com/myPageToInsert.html"></iframe>
Hope you enjoyed
You can set the src attribute of your iframe element using plain old javascript to switch out the page for another
I think what you are looking for are in the Jquery source code.
you can see more details here $(document).ready equivalent without jQuery