Ajax Jquery CORS not working - javascript

Hi everyone i'am fighting and searching solutions about this from 3 days. I have a problem getting data from sharethis.com RESTapi. I am working with jQuery and Laravel 5.2. I want to get values from this json: http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com but i'am very frustated trying a lot of methods and functions. My actual code is this:
function setHeader(xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
}
$.ajax({
url: 'http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com',
type: 'GET',
beforeSend: setHeader,
contentType: 'application/json; charset=utf-8',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); }
});
This request always return "Failed!". I understand a little what CORS means but on practice i can't make it work. Any ideas? Thanks..

Maybe you actually don't understand CORS :)
These headers have to be present in the response, not in the request.
The server has to provide them.
The server has to agree.
The URL you provided doesn't have CORS headers so you can't fetch it via AJAX unless you modify the backend.

Run this code with XMLHttpRequest to get data
var url = "http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com";
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader(
'X-Custom-Header', 'value');
xhr.withCredentials = true;
xhr.onload = function () {
if (this.status === 200) {
console.log(xhr);
}
};
xhr.send();
And there is the function to check if the url support CORS
function createCORSRequest(method, url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
console.log("for chrome/fir");
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
console.log("ie");
} else {
// CORS not supported.
xhr = null;
console.log("not supported");
}
return xhr;
}
hope it helps, regards

Related

Javascript CORS "pre-flight"

I'm so desperate because I can't see the light in this endless darkness, the problem is, that there is no way to stop "pre-flight" options response from appearing and of course can't reach certain API, I've been looking and reading stuff about CORS but without luck.
This is the function in the API that should display an array:
function main_get() {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: SOME-KEY');
header('Access-Control-Max-Age: 1728000');
header("Content-Length: 0");
header("Content-Type: text/plain");
$array['results'] = array(
array(
"adId"=>"8847575",
"make"=>"SOMEMAKE",
"model"=>"Some model",
"year"=>"2008",
"version"=>"The version",
)
);
$this->response($array, 200);
}
I'm using Codeigniter and REST plugin for the API.
Note that the headers are included
This is the code for the request sample:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function makeCorsRequest() {
var url = 'http://*****/api/test';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader('SOME-KEY', 'dffs54f78v');
if (!xhr) {
document.getElementById("response").innerHTML = 'CORS not supported';
return;
}
xhr.onload = function () {
var text = xhr.responseText;
document.getElementById("response").innerHTML = text;
};
xhr.onerror = function () {
document.getElementById("response").innerHTML = 'Woops, there was an error making the request.';
};
xhr.send();
}
makeCorsRequest();
Got this code from some CORS tutorial in the internet.
And still can't get rid of this:
main.js:40 OPTIONS http://*****/api/test 404 (Not Found)
makeCorsRequest # main.js:40 (anonymous) # main.js:43 localhost/:1
Failed to load http://*****/api/test: Response for preflight has
invalid HTTP status code 404.
What am I doing wrong?
I know there may be an answer somewhere, but I've wasted 3 days at this thing and found nothing.
Thanks in advance

CORS no Acess-Control-Allow-Origin header

In my Javascript file I want to load xml data from this site: https://www.anime2you.de/feed/
But I always get a no Access-Control-Allow-Origin header despite using CORS. Did I misunderstand the concept / usage of CORS or is the website faulty?
My code:
var feeds = ["https://www.anime2you.de/feed/"];
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'https://www.anime2you.de/feed/';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
alert("success");
};
xhr.onerror = function() {
alert("fail");
};
xhr.send();
Thanks in advance
Nova
Have you set the header("Access-Control-Allow-Origin: *"); on the script you are requesting? https://www.anime2you.de/feed/ if you are using Access-Control-Allow-Origin with a wildcard then set the credentials to false in
xhr.withCredentials = false;
If you can set the domain name of the server making the request i.e
header("Access-Control-Allow-Origin: http://domain-where-js-sits");
then you can do:
xhr.withCredentials = true;
and set these other headers:
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Content-Type
An alternative is to use jsonp - this may not work for you as the response needs to be in json:
function response(data) {
edit the returned data here
}
var script = document.createElement('script');
script.src = 'https://www.anime2you.de/feed/?callback-response';
document.body.appendChild(script);

load array saved in text file into javascript

I would like to load a text file with an array like the one below so it is accessible within javascript, how can I do that via an ajax call to access the text file? This is the text file artists.txt:
["Fally ipupa","Radio & Weasel","P-Square feat. Don Jazzy","Mose Fanfan","Fally ipupa","Mercy Masika","Madilu System","Koffi Olomidé","DaVido","Luciano","Kanda Bongo Man","Franco","Franco","DJ Afrobeat","Oliver Mtukudzi","Sauti Sol","Alikiba","Aryon","Gramps Morgan","Buju Banton","Wailing Souls","Bob Marley & The Wailers","Don Carlos and Gold","Burning Spear","Peter Tosh","George Nooks","Richie Spice","Culture","Sanchez","Terry Linen","Archie Wonder","Jah Cure","Busy Signal","Romain Virgo","Junior Reid","Shaggy","Glen Washington","Ginjah","Lucky Dube","Bushman","Chronixx","Turbulence","Protoje","UB40","Franco","Rich Mavoko","Rose Muhando","Kanda Bongo Man","Diamond"," Davido","Tekno","Daddy Owen","Pépé Kallé","Busy Signal","Franco Et Le T.P. O.K. Jazz","Alice Kamande","Koffi Olomidé","Culture","Alikiba","Papa Wemba","Korede Bello","Madilu System","Reuben Kigame","Gloria Muliro"]
Just call it via ajax directly using GET request.
/**************************************************************************************************
Ajax
*/
// Set all of these parameters.
// type
// url
// callback
// data
Pub.ajax = function (config_ajax) {
var xhr = new win.XMLHttpRequest();
// post_json
if (config_ajax.type === 'post_json') {
xhr.open("POST", config_ajax.url, true);
xhr.setRequestHeader("Content-type", "application/json");
}
// post
if (config_ajax.type === 'post') {
xhr.open("POST", config_ajax.url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
// get
if (config_ajax.type === 'get') {
xhr.open('GET', config_ajax.url, true);
}
// post for form_data
if (config_ajax.type === 'multi') {
xhr.open("POST", config_ajax.url, true);
}
xhr.onload = completed;
xhr.send(config_ajax.data);
function completed () {
if (this.status === 200) {
config_ajax.callback(xhr.responseText);
} else {
throw new Error("xhr.status is " + this.status);
}
}
xhr.app_url = config_ajax.url;
Priv.createStatusBar(xhr);
return xhr;
};
In order to make it work through Ajax call,
Rename your file as artists.json
Set MIME type in your web server, as application/json for .Json extension. This would be already set in most of the webservers.
Then do an Ajax call, if you use library like jquery then it is pretty straight as follows
url=my site.com/artists.json;
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
This should automatically allow you to fetch and read the JSON file in your success method.

Need Help to solve ajax issue?

I create safari extension and i inject js in this extension. In this JS code i send ajax call which create following error in console. "Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers"
here is my code:
this function i copied from net to solve cross domain issue but its not working please help me to figure out this.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR has 'withCredentials' property only if it supports CORS
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") { // if IE use XDR
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var request = createCORSRequest("get", "https://www.karmora.com/list.xml");
if (request) {
// Define a callback function
request.onload = function () {
};
// Send request
request.send();
}
$.get('https://example.com', function (data) {
alert("Ajax call successfull");
});
Your problem is related with Same-origin_policy
If you have access to the server, add to Apache Web Server virtual host configuration the following settings:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"

X-Domain Post using XMLHttpRequest

I have the following block of code:
console.log(1);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://anothersite.com/deal-with-data.php');
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
console.log(2);
xhr.onreadystatechange = function () {
console.log(3);
if (this.status == 200 && this.readyState == 4) {
console.log(4);
xhr.send("formType="+thisFormType+
"&mediaCode="+3478+
"&car="+carID+
"&title="+$('#title').val()+
"&firstname="+$('#firstname').val()+
"&surname="+$('#lastname').val()+
"&tel="+$('#telephone').val()+
"&email="+$('#emailaddress').val()+
"&postcode="+$('#postcode').val()+
"&add1="+$('#add1').val()+
"&add2="+$('#add2').val()+
"&add3="+$('#add3').val()+
"&town="+""+
"&county="+""+
"&optin-post="+$('#optin-post').attr('checked')+
"&optin-tel="+$('#optin-tel').attr('checked')+
"&optin-email="+$('#optin-email').attr('checked')+
"&optin-sms="+$('#optin-sms').attr('checked')+
"&tarID="+targetID+
"&campID="+campaignID+
"&subID="+subjectID
);
console.log(5);
}
}
console.log(6);
So, everything fires except for the xhr.onreadystatechange - I never get the console.log(4) - I have enabled Access-Control-Allow-Origin in PHP and the htaccess as well as trying a veritable plethora of Javascript post functions.
The problem is, as a requirement, I need to post data from a form on a server that has no support for Server side languages - to another domain to handle the data.
Any ideas? It's driving me insane!
edit: I've also tried it with $.ajax
$.ajax({
url: 'http://anothersite.com/deal-with-data.php',
type: "post",
crossDomain: true,
data: {
"formType":thisFormType,
"mediaCode":3478,
"car":$('#car').val(),
"title":$('#title').val(),
"firstname":$('#firstname').val(),
"surname":$('#surname').val(),
"tel":$('#telephone').val(),
"email":$('#email').val(),
"postcode":$('#postcode').val(),
"add1":$('#add1').val(),
"add2":$('#add2').val(),
"add3":$('#add3').val(),
"town":"",
"county":"",
"optin-post":$('#opt-post').attr('checked'),
"optin-tel":$('#opt-tel').attr('checked'),
"optin-email":$('#opt-email').attr('checked'),
"optin-sms":$('#opt-sms').attr('checked'),
"tarID":targetID,
"campID":campaignID,
"subID":subjectID
},
beforeSend: function() {
$('#submit').val('Sending...').attr('disabled','disabled');
},
success: function(data) {
console.log("success call");
console.log(data);
},
error: function(err) {
console.log("error call");
console.log(err);
}
});
And now I've tried to enable it in httpd.conf as well: https://serverfault.com/a/378776/36601
You should not pass xhr.send inside xhr.onreadystatechange. Do something like the following:
var xhr = new XMLHttpRequest();
xhr.open('POST', 'myurl', true);
xhr.onload = function () {
if (xhr.status === 200 && xhr.readyState === 4) {
// do some cool stuff
console.log('You got a successfull request');
}
};
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send(); // pass your params here
You may need to set Access-Control-Allow-Methods: POST header also. Read more on https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Categories

Resources