How to make a GET Request in XMLHttpRequest? - javascript

I'd like to make this GET request to GitHub API: https://developer.github.com/v3/repos/#list-all-public-repositories
I have no idea how to do this however. I've done some curling, but this is the first time I'll be using HTTP and API requests.
I've tried some online tutorials, but they don't exactly show how to make a specific GET request.
Here's what I have so far:
function reqListener () {
console.log(this.responseText);
}
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://api.github.com/");
oReq.send();
Instead of a JSON with Repository information from GitHub, I'm getting the following:
{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}","commit_search_url":"https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following{/target}","gists_url":"https://api.github.com/gists{/gist_id}","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}","organization_url":"https://api.github.com/orgs/{org}","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/{owner}/{repo}","repository_search_url":"https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}","current_user_repositories_url":"https://api.github.com/user/repos{?type,page,per_page,sort}","starred_url":"https://api.github.com/user/starred{/owner}{/repo}","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/{user}","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/{user}/repos{?type,page,per_page,sort}","user_search_url":"https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"}
Edit: I've been able to get the first page, but I'd like to keep iterating through the pages. I don't understand the docs on how to do this. So far my code is this:
<script type="text/javascript">
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if(xhr.readyState == 4)
{
if(xhr.status == 200)
{
console.log("Something went right!");
var json_results = JSON.parse(xhr.responseText);
json_length = Object.keys(json_results).length
var str = "";
for(var i = 0; i < json_length; i++)
{
str += JSON.stringify(json_results[i].description) + "\n";
}
document.getElementById('api-content').textContent = str;
}
else if(xhr.status == 404)
{
console.log("404 NOT FOUND!");
}
else
{
console.log("Something went wrong!");
}
}
};
xhr.open("get", "https://api.github.com/repositories", true);
xhr.send();
</script>

Try this:
function reqListener (response) {
console.log(response);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://api.github.com/repositories");
oReq.send();
Please refer to the documentation for proper usage of Github API.

XMLHttpRequest get works fine here, it is the URL which you are making the request.
Check github api docs to get the link and params required for what you need.
https://developer.github.com/v3/

Making a GET request to https://api.github.com/ does NOT give you result of: a JSON with Repository information from GitHub. You'll get a page showing a JSON of URLs to the relevant pages / information.
solution:
Instead of a JSON with Repository information from GitHub, I'm getting the following:
{"current_user_url":"https://api.github.com/user","current_user_authorizations_html_url":"https://github.com/settings/connections/applications{/client_id}","authorizations_url":"https://api.github.com/authorizations","code_search_url":"https://api.github.com/search/code?q={query}{&page,per_page,sort,order}","commit_search_url":"https://api.github.com/search/commits?q={query}{&page,per_page,sort,order}","emails_url":"https://api.github.com/user/emails","emojis_url":"https://api.github.com/emojis","events_url":"https://api.github.com/events","feeds_url":"https://api.github.com/feeds","followers_url":"https://api.github.com/user/followers","following_url":"https://api.github.com/user/following{/target}","gists_url":"https://api.github.com/gists{/gist_id}","hub_url":"https://api.github.com/hub","issue_search_url":"https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}","issues_url":"https://api.github.com/issues","keys_url":"https://api.github.com/user/keys","notifications_url":"https://api.github.com/notifications","organization_repositories_url":"https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}","organization_url":"https://api.github.com/orgs/{org}","public_gists_url":"https://api.github.com/gists/public","rate_limit_url":"https://api.github.com/rate_limit","repository_url":"https://api.github.com/repos/{owner}/{repo}","repository_search_url":"https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}","current_user_repositories_url":"https://api.github.com/user/repos{?type,page,per_page,sort}","starred_url":"https://api.github.com/user/starred{/owner}{/repo}","starred_gists_url":"https://api.github.com/gists/starred","team_url":"https://api.github.com/teams","user_url":"https://api.github.com/users/{user}","user_organizations_url":"https://api.github.com/user/orgs","user_repositories_url":"https://api.github.com/users/{user}/repos{?type,page,per_page,sort}","user_search_url":"https://api.github.com/search/users?q={query}{&page,per_page,sort,order}"}
Decide which "Repository information" you want and get it from the above (JSON) listed URLs.
For example: (if Github user is: VCone)
"user_url": "https://api.github.com/users/{user}" means go to URL: https://api.github.com/users/VCone.
"user_repositories_url": "https://api.github.com/users/{user}/repos{?type,page,per_page,sort}" means go to URL: https://api.github.com/users/VCone/repos.
or can be https://api.github.com/users/VCone/repos?type=xxxx,sort=xxxx,page=xxxx
etc.

Related

How to call REST service using JavaScript?

Using the code I found from one of the StackOverflow postings, I'm trying to call a REST service GET method. However, when the code runs it is not putting the GET format correctly in the URL.
Here's the code:
<!DOCTYPE html>
<script>
function UserAction(json)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (this.readyState == 4 && this.status == 200)
{
alert(this.responseText);
}
};
xhttp.open("GET", "http://localhost:8080/isJsonValid/json", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(json);
}
</script>
<form>
<button type="submit" onclick="UserAction(json)">Check if JSON Valid</button>
<label for="json">JSON:</label>
<input type="text" id="json" name="json"><br><br>
</form>
</html>
The expected format of this GET REST service would be:
http://localhost:8080/isJsonValid/json
(where json in the line above is the actual JSON sent as a parameter.)
Yet, what is shown in the URL line includes the project, directory and the URL has the ?name=value syntax.
Since the GET doesn't match the simple http://localhost:8080/isJsonValid/json format, I get a 404 error.
I realize there's something obvious I'm missing.
Thanks to all for suggestions.
If you need to send data you need to either send it as a query param or as the body. If you want to send it as a body need to use POST type. Below is the example of POST type.
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'https://ghibliapi.herokuapp.com/films', true)
request.onload = function() {
// Begin accessing JSON data here
var data = JSON.parse(this.response)
if (request.status >= 200 && request.status < 400) {
data.forEach(movie => {
console.log(movie.title)
})
} else {
console.log('error')
}
}
// Send request
request.send()
For post Request. As I don't have any API with me I have used get API URL.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log(this.responseText)
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://ghibliapi.herokuapp.com/films", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
Thanks all for the great input and help!
The best solution for me was to just use, as suggested, a POST. The GET was always putting the "?" in the URL even if I concatenated it, That "?" isn't how the REST service interprets the GET parameters so it wouldn't work that way. In the REST framework I'm using, GET parameters are just concatenated with one or more "/" as separators in the URL.
Appreciate all the terrific help here on SO. :)

How to load a json file with javascript locally without Jquery?

I'm creating a website to progress in javascript and I have a little problem, every ways I try, my browser doesn't want to load my json file.
I tried many codes i found on internet but none of them work (or I don't know how to make them work). Finally i fond this one which is quite easy to understand but yhis one too doesn't work and always return an error message.
function loadJSON(path,success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 1) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path , true);
xhr.send();
}
function test()
{
loadJSON('test.json', function(data) { console.log(data); }, function(xhr) { console.error(xhr); });
}
I run the test function but everytimes, the console return me an error. Someone have an idea to solve my problem ?
status is the HTTP response code.
200 means the request has been successful. The status will most likely never be 1.
Here is a list of HTTP codes
As a solution, I suggest using the fetch API, which is the modern way to query files.
Here are some examples on how to use it
If you really want to use AJAX, use this :
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
// Success!
var resp = this.response;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();
Source : You Might Not Need jQuery

XMLHttpRequest Not Sending

This is part of the code for the extension:
let url = "https://mywebsite.com/data.php";
function newRequest() {
var client = new XMLHttpRequest();
client.open("POST", url, true);
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send("status=true");
console.log(client.status);
}
newRequest();
Which also logs 0 in the console. I've been following the documentation here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest, trying countless tweaks, and there aren't any errors in the console. Not really sure what the issue could be.
The PHP on my server definitely works since I was able to POST the data successfully from a local html file.
Since the AJAX request is asynchronous, you need to handle it through a callback onreadystatechange.
The code should be like this
let url = "https://mywebsite.com/data.php";
function newRequest() {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
console.log(this.readyState) // should be 4
console.log(this.status) // should be 200 OK
console.log(this.responseText) // response return from request
};
client.open("POST", url, true);
client.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
client.send("status=true");
console.log(client.status);
}
newRequest();
Hope this helps.
For More Info: https://www.w3schools.com/js/js_ajax_http_response.asp

Cross Domain access to USPS API

I am trying to make a CORS request to USPS website with jquery, I have gotten it to work on my work pc, with internet explorer only for some reason. and I get a CORS error on the newer version of IE and also Firefox and Chrome.
In a question I wasn't allowed to comment on due to not having a rep, they suggested sending it to a server first then making the request instead of from the browser, Can somebody explain this to me? How can I host a server with javascript, I simply need to use this API to get tracking information and this stupid CORS restriction is a pain in my rear every time I try to do something like this.
Please help.
function sendTrackingRequest(x) {
var requestURL = "http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML="
var request = new XMLHttpRequest();
request.open( "GET", requestURL + trackNumberToBeTracked, true);
// various sanitizations should be employed on the backend when dealing with user input
request.responseType = "text/xml";
request.setRequestHeader( "Content-Type", "xml" );
request.addEventListener( "readystatechange", function() {
if ( request.readyState == 4 ) {
if ( request.status == 200 ) {
// process response
var trackingStatus = request.response
showResult(trackingStatus);
console.log(trackNumberToBeTracked);
} else {
alert("error")
}
}
}, false );
request.send();
}
});
Okay everyone.
Please bear with me I have made a huge beginner mistake and figured out what was wrong with Slakes help.
So in my code, I had a function with a similar name which was a .response not defined. I got this error after I listened to the first helper who said a contenttype was not necesarry for a Get request which he was right after further research.
After i removed all the bad functions which i was testing, I finally got my response to work. here is my code
$(document).ready(function() {
$('#trackButton').click(function() {
var enteredNumber = $('#trackingNumbers').value;
var trackNumberToBeTracked = '<TrackRequest USERID="648FOOTL0638"> <TrackID ID="9405510200839104436417"></TrackID></TrackRequest>'
sendTrackingRequest();
function sendTrackingRequest(x) {
var requestURL = "http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML="
var request = new XMLHttpRequest();
request.open( "GET", requestURL + trackNumberToBeTracked, true);
// various sanitizations should be employed on the backend when dealing with user input
request.addEventListener( "readystatechange", function() {
if ( request.readyState == 4 ) {
if ( request.status == 200 ) {
// process response
var trackingStatus = request.response
alert(trackingStatus);
console.log(trackNumberToBeTracked);
} else {
alert("error")
}
}
}, false );
request.send();
}
});
Here is the code that was below it, giving me the error after I took out set header type (which solved my CORS issue as POST requests are not allowed on the api)
function showResult(request) {
var xmlDoc = request.response.documentElement;
removeWhitespace(xmlDoc);
var outputResult = $("#BodyRows");
var rowData = xmlDoc.$("#Employee");
addTableRowsFromXmlDoc(rowData,outputResult);
};
});

Navigate to URL with custom request headers in JavaScript

Question just like the title.
In command line, we can type:
curl -H "header_name: header_value" "http://example"
to navigate to http://example with a custom request header as shown above.
Q: If I need to write a JavaScript to do the same thing, how should I do?
var url = 'https://example';
var myRequest = new XMLHttpRequest();
myRequest.open('GET', url ,false);
myRequest.setRequestHeader('header-name','header-value');
myRequest.send();
I tried this code, there is no syntax error but the page didn't change. Hence, I don't really know if I modified the request header(s).
Here is how you can handle this:
var req = new XMLHttpRequest();
req.open('GET', 'http://example', true); //true means request will be async
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
//update your page here
//req.responseText - is your result html or whatever you send as a response
else
alert("Error loading page\n");
}
};
req.setRequestHeader('header_name', 'header_value');
req.send();

Categories