load array saved in text file into javascript - 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.

Related

Ajax Jquery CORS not working

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

how to make a request to other domain using javascript only

I have to make a request to my project URL from the other websites. I created a script file which will be loaded to other websites. The script should make a request to my project specific URL on window load. I have learned about jquery ajax JSON request.
$.ajax({
type: "GET",
url: "http://saskatchewan.univ-ubs.fr:8080/SASStoredProcess/do?_username=DARTIES3-2012&_password=P#ssw0rd&_program=%2FUtilisateurs%2FDARTIES3-2012%2FMon+dossier%2Fanalyse_dc&annee=2012&ind=V&_action=execute",
dataType: "jsonp",
}).success( function( data ) {
$( 'div.ajax-field' ).html( data );
});
But my script will be run on different sites so, I want to make it using javascript only.
You can use functions provided by the hosting environment through javascript:
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return xmlHttp.responseText;
}
However, synchronous requests are discouraged, so you might want to use this instead:
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}

Signature does not match s3 GET object

I have an image in the amazon s3 which has ACL of autherized-users. I'm trying to retrieve that image with GET method. The javascript method (in angular js) looks like this
(In the following example, response contains the necessary data such as authHeader)
var uri = 'https://sample.s3.amazonaws.com/sample/image.jpg';
var postParams = response.data;
var xhr = new XMLHttpRequest();
xhr.addEventListener("load", downloadComplete, false);
xhr.addEventListener("error", downloadFailed, false);
xhr.addEventListener("abort", downloadCanceled, false);
function downloadComplete(e) {
var xhr = e.srcElement || e.target;
if(xhr.status === 200) { //success status
}
else {
}
}
function downloadFailed(e) {
debugger;
}
function downloadCanceled(e) {
debugger;
}
xhr.open('GET', uri, true);
xhr.setRequestHeader('Authorization', postParams.authHeader);
xhr.setRequestHeader('x-amz-content-sha256', postParams.payloadHash);
xhr.setRequestHeader('Host', "sample.s3.amazonaws.com");
xhr.setRequestHeader('x-amz-date', postParams.date);
xhr.send();
But I get a 403 exception which says SignatureDoesNotMatch. Is there anything i'm doing wrong? I'm quite sure that the values i'm providing are correct.
Thanks in advance

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

Convert ajax function to jquery

I would like to convert this ajax function to a jquery function but im not sure how it would be done in jquery
function ajax_posta() {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "javas.php";
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function () {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById('status').innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send("num=" + (--num)); // Actually execute the request
document.getElementById('status').innerHTML = "<img src = 'loading.gif' height = '30' width = '30'>";
}
$(document).ready(function()
{
$('.eventer.button').click(function () {
var self = this;
$.post('javas.php', function (data) {
$(self).parent('div').find('.status').html(data);
})
});
}
)
;
</script>
You're pretty much there
$.ajax('javas.php', {
success: function(response) {
$(".status").html(response);
},
data: "num=" + (--num)
});
If these are the only two pieces of data you need to send to your request, you could just use $.post, but the advantage here is that if you ever want to specify more options, like contentType, all you'd have to do is add it to the existing options object.

Categories

Resources