Get data ajax from file local to server in pure javascript - javascript

I want to get data ajax from file local to server.
I'm writting in Js as follow:
var UrlDetails = 'http://192.xxx.x.xxx:7000';
function createCORSRequest(method, url, asynch) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
xhr.setRequestHeader('MEDIBOX', 'login');
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url, asynch);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
function getDoLogin(e, callback) {
var url = UrlDetails + '/api/loginGET?username=' + e.id + '&password=' + e.password + '&f=json';
var xhr = createCORSRequest('GET', url, true);
if (xhr) {
xhr.onreadystatechange = function () {
try {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
xhr.status === 403 ? modalShow() : errorServer(xhr.status);
}
}
}
catch (e) {
alert('Caught Exception: ' + e.description);
}
};
xhr.send();
}
}
I call function getDoLogin(e, f); And I get a error from Chrome: XMLHttpRequest cannot load http://192.xxx.x.xxx:7000/api/loginGET?username=1&password=1&f=json. Response for preflight has invalid HTTP status code 405
It's only running with Jquery:
function getDoLoginJQuery(e) {
return $.Deferred(function (d) {
$.ajax({
type: 'get',
url: UrlDetails +'/loginGET?username=' + e.id + '&password=' + e.password + '&f=json',
cache: 'false',
dataType: 'json'
}).done(function (a, b) {
d.resolve(a)
}).fail(function (a, b, c) {
d.reject(a, b, c);
})
})
}
I don't know how to write in JS to run exactly.
(I'm sorry. My English is not good.)

Try to remove setRequestHeader, like this:
function createCORSRequest(method, url, asynch) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
// xhr.setRequestHeader('MEDIBOX', 'login');
// xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url, asynch);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
Good luck.

Related

AJAX with promise

How to use promises (ES6) and .then method in order to this code will work?
getGif: function (searchingText, callback) {
var url = GIPHY_API_URL + '/v1/gifs/random?api_key=' + GIPHY_PUB_KEY + '&tag=' + searchingText;
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function () {
if (xhr.status === 200) {
var data = JSON.parse(xhr.responseText).data;
var gif = {
url: data.fixed_width_downsampled_url,
sourceUrl: data.url
};
callback(gif);
}
};
xhr.send();
},
Using Promise-Based XHR your code looks like:
getGif = function (searchingText) {
return new Promise((resolve, reject)=>{
var url = GIPHY_API_URL + '/v1/gifs/random?api_key=' + GIPHY_PUB_KEY + '&tag=' + searchingText;
var xhr = new XMLHttpRequest();
// Setup our listener to process compeleted requests
xhr.onreadystatechange = function () {
// Only run if the request is complete
if (xhr.readyState !== 4) return;
// Process the response
if (xhr.status >= 200 && xhr.status < 300) {
// If successful
var data = JSON.parse(xhr.responseText).data;
var gif = {
url: data.fixed_width_downsampled_url,
sourceUrl: data.url
};
resolve(gif);
} else {
// If failed
reject({
status: request.status,
statusText: request.statusText
});
}
};
xhr.open('GET', url);
xhr.send();
});
}
Need to invoke method depends on signature of function.
getGif(searchText).then((response)=>{
console.log(response);
}, (error)=> {
console.log(error);
})

Javascript function onload never called

I wish to get a json file with a get request from a webservice, and I have a "cross origin request", so I check "withCredentials", and then I use the onload function to display the content of the json on the console.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
console.log("withCredentials is true");
xhr.onload = function() {
console.log('ok');
if (xhr.status >= 200 && xhr.status < 400) {
data.forEach(card => {
console.log(card.nameEnglish1);
})
} else {
console.log('error');
}
};
xhr.onerror = function() {
console.log('There was an error!');
};
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', 'http://192.168.42.176:8080/batch-recup-mtg-0.0.1-SNAPSHOT/mtg/cards/search?setCode=AKH');
if (!xhr) {
throw new Error('CORS not supported');
}
But nothing happen, my onload function is never called, and I don't have any error. I'm sure that the webservice is working because I tried it in my browser. Do you have any idea why the onload function is never called?
EDIT : console.log("withCredentials is true"); is displayed, but console.log('ok'); isn't
You need to
xhr.send();
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
console.log("withCredentials is true");
xhr.onload = function() {
console.log('ok');
if (xhr.status >= 200 && xhr.status < 400) {
data.forEach(card => {
console.log(card.nameEnglish1);
})
} else {
console.log('error');
}
};
xhr.onerror = function() {
console.log('There was an error!');
};
// added send call here:
xhr.send();
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', 'http://google.com/');
if (!xhr) {
throw new Error('CORS not supported');
}

How to grab inner text of a classname given a URL - Javascript

I have an ajax GET request here
Get('https://www.ratemyprofessors.com/ShowRatings.jsp?tid=282380', function(err, data){
});
function Get(url, callback) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.open('GET', url, true);
xhr.send();
};
And I want to grab the first 3 elements of the class name "grade" and grab their inner text. How can I do this within the first Get function in the above code?
Your response type is a text, not a json. Below you can see work example.
Get('https://www.ratemyprofessors.com/ShowRatings.jsp?tid=282380', function(err, data) {
let dom = document.createElement('html');
dom.innerHTML = data;
let elements = Array.from(dom.getElementsByClassName('grade'));
elements.length = 3; // if you're need only 3 first elements.
console.log(elements);
});
function Get(url, callback, responseType = 'text') { // you can manually set type.
var xhr = new XMLHttpRequest();
xhr.responseType = 'text';
xhr.onload = function() {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.open('GET', url, true);
xhr.send();
};

Return POST AJAX value in Javascript

I'm trying to make a Javascript function that gets two arguments, an URL and a data, posts it to a PHP and returns the server's response without jQuery or any library. (Source)
function post(URL, data) {
return new Promise(function(resolve, reject) {
var req = new XMLHttpRequest();
req.open('POST', URL, true);
req.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
req.onload = function() {
if (req.status == 200) {
resolve(req.response);
} else {
reject(Error(req.statusText));
}
};
req.onerror = function() {
reject(Error('Network Error'));
};
req.send(data);
});
}
<?php
if ( isset($_POST['data']) ) {
echo json_encode(array("Hey {$_POST['data']}" ));
} else {
echo json_encode(array("Error"));
}
?>
So far so good, here's how I'm handling it.
function handle(URL, data) {
post(URL, data).then(function(response) {
return response;
}, function(error) {
return error;
});
}
However, this always returns undefined. Interestingly, if I try to console.log(response) it works fine.
I want to be able to do such things like alert(handle(URL, data));
Is this impossible? If yes how could I get around it?
I ended up reworking my script to use callback instead.
var AJAX = {
get: function(a, b) {
var c = new XMLHttpRequest();
c.onreadystatechange = function() {
if (c.readyState == 4 && c.status == 200) {
b(c.responseText);
}
};
c.open('GET', a, true);
c.send();
},
post: function(a, b, d) {
var c = new XMLHttpRequest();
c.onreadystatechange = function() {
if (c.readyState == 4 && c.status == 200) {
d(c.responseText);
}
};
c.open('POST', a, true);
c.setRequestHeader('Content-type',
'application/x-www-form-urlencoded');
c.send(b);
}
};
This is how you call it: AJAX.get('text.txt', function doSomething(what){console.log(what)});

Run one ajax after another one

I'm working on the project where I (sadly) cannot use jQuery. And I need to do something which is simple in jQuery but I cannot do it in pure JavaScript. So, I need to run one ajax request using a response form another one. In jQuery it will look like:
$.get("date.php", "", function(data) {
var date=data;
$("#date").load("doku.php?id="+date.replace(" ", "_")+" #to_display", function() {
$(document.createElement("strong")).html(""+date+":").prependTo($(this));
});
});
And this is my code in pure JS which isn't working:
if (window.XMLHttpRequest)
{
ObiektXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
ObiektXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if(ObiektXMLHttp)
{
ObiektXMLHttp.open("GET", "date.php");
ObiektXMLHttp.onreadystatechange = function()
{
if (ObiektXMLHttp.readyState == 4)
{
var date = ObiektXMLHttp.responseText;
if (window.XMLHttpRequest)
{
ObiektXMLHttp = new XMLHttpRequest();
} else if (window.ActiveXObject)
{
ObiektXMLHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
ObiektXMLHttp.open("GET", "doku.php?id="+date.replace(" ", "_"));
ObiektXMLHttp.onreadystatechange = function()
{
if (ObiektXMLHttp.readyState == 4)
{
alert(ObiektXMLHttp.responseText);
}
}
}
}
ObiektXMLHttp.send(null);
}
What am I doing worng?
You forgot to call ObiektXMLHttp.send(null); on second case:
//....
ObiektXMLHttp.open("GET", "doku.php?id="+date.replace(" ", "_"));
ObiektXMLHttp.onreadystatechange = function() {
if (ObiektXMLHttp.readyState == 4)
{
alert(ObiektXMLHttp.responseText);
}
};
//Here
ObiektXMLHttp.send(null);
How about something like this (naive prototype):
// xhr object def
var xhr = {
obj: function() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
throw new Error("can't init xhr object");
},
get: function(url, fn) {
var xhr = this.obj();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
fn(xhr.responseText);
}
};
xhr.open("GET", url);
xhr.send(null);
}
};
// implementation
xhr.get("date.php", function(data){
xhr.get("doku.php?id=" + data.replace(" ", "_"), function(data){
alert(data);
});
});
It's not clear what you got wrong (can you tell us?), but I'd suggest to rely on some helper function like this:
function xhrGet(url, callback) {
if (window.XMLHttpRequest)
var xhr = new XMLHttpRequest();
else if (window.ActiveXObject)
var xhr = new ActiveXObject("Microsoft.XMLHTTP");
if (!xhr) return;
xhr.open("GET", url);
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) return;
if (typeof callback === "function") callback(xhr);
};
xhr.send(null);
return xhr;
}
So all you have to do is to use this function:
xhrGet("date.php", function(x1) {
xhrGet("doku.php?id=" + date.replace(" ", "_"), function(x2) {
// do stuff
// x1 and x2 are respectively the XHR object of the two requests
});
});

Categories