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);
}
Related
I have two AJAX calls, one in native JavaScript and another with JQuery, which call a PHP Script. The JQuery one is working, but the JavaScript one not. Here goes the code:
JQuery:
$.ajax({
url: "/Tests/index.php",
method: "POST",
data: {'Id': "2"}
});
Native JavaScript:
var Data = {Id: "2"};
XHR = new XMLHttpRequest();
XHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(XHR.responseText);
}
}
XHR.open("POST", "/Tests/index.php", true);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.send(JSON.stringify(Data));
PHP Script:
echo var_dump($_POST);
The one with JQuery returns 2, but the JavaScript one, doesn't return anything. All the data is seen through the console of the web browser.
Try this code:
var Data = {"Id": "2"};
var XHR = new XMLHttpRequest(); // declared XHR var
XHR.open("POST", "/Tests/index.php", true);
XHR.setRequestHeader("Content-Type", "application/json");
XHR.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(XHR.responseText);
}
}
XHR.send(Data); // sending data without converting to string
Reference: https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
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
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.
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
$('#show_mess').click(function (){
$('#dropdown_mess').slideToggle("slow");
$('#arrow_mess').slideToggle("slow");
$('#arrow_not').hide("slow");
$('#dropdown_not').hide("slow");
function recall(){ setTimeout(function () {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "http://localhost/ajax/mess_data.php", true);
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('dropdown_mess').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send();
document.getElementById('dropdown_mess').innerHTML = "<img class='non_auto' id='ajax_loading' src='img/ajax_loading.gif'></img>";
recall();
}, 2000);
};
recall();
});
this function works fine but when each ajax call is done i need to colse and re-oper chrome in order to work, works fine in firefox
You are already using Jquery so why don't you try it's ajax function like below
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
....
});
You can find more information on the manual