How can I translate this curl script to an AJAX request in JavaScript?
curl -X POST
-d "grant_type=password&username=admin&password=Demo1234"
-u "<ClientID>:<ClientSecret> " http://<host>/url/to/auth
I will show an example in pure JavaScript
function sendData()
{
var formData = new FormData(); //create formData object to send data
formData.append("grant_type, "password"); //via append you add data
formData.append("username", "admin");
formData.append("password", "Demo1234");
var xmlHttp = new XMLHttpRequest(); //create "ajax/xhr" object
xmlHttp.onreadystatechange = function() //monitor status of response
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //if it's ok
{
console.log(xmlHttp.responseText); //then output data
}
}
xmlHttp.open("POST", "http://<host>/url/to/auth");
xmlHttp.setRequestHeader("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>");
xmlHttp.send(formData);
}
Your curl call uses three things:
Unprocessed data.
HTTP Authentication.
Templating? - Not sure.
This is what I best came up with:
$.ajax({
"url": "http://<host>/url/to/auth",
"data": "grant_type=password&username=admin&password=Demo1234",
"processData": false,
"beforeSend": function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>"));
}
});
Replace your <ClientID> and <ClientSecret> with the right values.
Here is how you can do it for any curl not just this one:
Get postman (https://www.getpostman.com/)
follow this to import your curl to postman: https://www.getpostman.com/docs/postman/collections/data_formats#importing-postman-data
follow this to generate a code snippet for the curl you just imported: https://www.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets
one of the code snippet exporters is jqueryAjax.
Related
I have trying to call ServiceNow API from a SharePoint hosted adding i'm working on using JavaScript with credential for the header. But when i try to run it during the run time the request gets an error. Any help regarding this would be highly appreciated.
var req = new XMLHttpRequest();
req.open('GET',Servicenow_URL, true);
req.setRequestHeader('Content-Type', 'application/json');
req.open("Authorization", "Basic " + btoa(Username + ":" + password));
req.withCredentials = true;
req.send();
alert("here1");
if (req.readyState === 4) {
if (req.status === 200) {
console.log(xhr.responseText);
var response = JSON.parse(req.responseText);
alert("here2");
} else {
console.error(req.statusText);
alert("error");
}
}
the developer tool from browser shows the error as "the server responded with a status of 501"
I'm hoping to extract one custom header response from a site using the Javascript code below:
<html>
<head>
<script>
var data = null;
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
//console.log(this.responseText);
}
});
var URL = "http://somesite.xml/records"
xhr.open("GET", URL);
xhr.setRequestHeader("authorization", "Basic itworks");
xhr.send(data);
var xrecords = xhr.getResponseHeader("X-Records");
console.log(xrecords);
</script>
</head>
Two questions:
1. What changes do I need to make to have the response pull the content of that custom header?
2. The content of the header is a number of records. How can ensure that the data type is a number?
EDIT: Turned out the issue I was having was because I wasn't using an async function. A snipped of my resolved code is below:
function selector(x){
function fooO(callback) {
function overdue (x){
return "tasks.json?responsible-party-ids="+x+"&filter=overdue";
}
return $.ajax({
url: 'https://' + company + '.site.com/' + overdue(x),
headers: {
"Authorization": "BASIC " + window.btoa(key)
}
})
}
My first post here.
I'm using droidscript and I have to include an header that contains a specific user and a password in order to retrieve a token. I'm having trouble because I don't know where to include those headers.
That's the code I'm using:
function btn_OnTouch(){
var url = "myurl";
SendRequest(url);
}
//Send an http get request.
function SendRequest(url){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
HandleReply(httpRequest);
};
httpRequest.open("GET", url, true);
httpRequest.send(null);
app.ShowProgress("Loading...");
}
//Handle the servers reply (a json object).
function HandleReply(httpRequest){
if (httpRequest.readyState == 4){
//If we got a valid response.
if (httpRequest.status == 200){
txt.SetText("Response: " + httpRequest.status + httpRequest.responseText);
}
//An error occurred
else
txt.SetText("Error: " + httpRequest.status + httpRequest.responseText);
}
app.HideProgress();
}
The told me I should probably include the headers like this, but I don't know where to put them in my code.
httpRequest.setRequestHeader(“username”, “myuser”);
httpRequest.setRequestHeader(“password”, “mypass”);
You need to do it just after calling the open method like this:-
httpRequest.open("GET", url, true);
httpRequest.setRequestHeader("username", "myuser");
httpRequest.setRequestHeader("password", "mypass");
httpRequest.send(null);
I can't seem to receive Javascript's HTTPRequest. I get this HTTP/1.1 200 OK
but I cannot seem to get the URL that I sent over. I just want the link that I am sending over on my webpage.
Here is my javascript:
jQuery(function($) {$("button").click(function(){
console.log(this.id);
document.getElementById("direction").innerHTML = this.id + " is pressed.";
newurl = 'index.php?btn='+ this.id+"?key="+user.key;
sendHttpRequest(newurl);
});
});
function sendHttpRequest(update){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log(xhttp.responseText);
}
}
xhttp.open("GET",update,true);
xhttp.send(null);
console.log(update);
}
ESP8266 in void loop:
WiFiClient client;
String url = "/index.php?";
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Request Sent");
String request = client.readStringUntil('\r');
Serial.println("headers received");
Serial.println(request);
You're only reading the first line of the response from the index.php script on the ESP, which will generally be the HTTP status code you are seeing, and nothing else (Unless there's some other code you haven't posted). You need to read the entire HTTP message to get the response, specifically the body - Assuming index.php uses the body to return the data you need. You can find a description of the HTTP message structure here: https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html
Hi so first time working with APIs like this. Anyways, I've been reading up on the GitHub API and came across this:
READMEs support custom media types for retrieving the raw content or rendered HTML.
src: https://developer.github.com/v3/repos/contents/#get-the-readme
Which I believe means that it is possible to retrieve an HTML formatted version of the contents of the README? If so how would I retrieve it using AJAX since the tutorials are all for curl. In the end I want to display a portion of it on my website and would be a lot easier if given in the html format rather then markdown.
The docs say something about: application/vnd.github.VERSION.html
I just don't necessarily know how to use it.
Thanks!
You have to set the Accept header of the HTTP request to application/vnd.github.html.
$.ajax({
url: 'https://api.github.com/repos/just95/toml.dart/readme',
headers: { 'Accept': 'application/vnd.github.html' }
}).done(function(data) {
alert(data);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
All you need to do is set the Accept header of your HTTPS request. Using cURL for example:
curl -i -H "Accept: application/vnd.github.v3.html" https://api.github.com/repos/github/developer.github.com/readme
In JavaScript,
var apiRoot = 'https://api.github.com';
var myUser = YOUR_USER_HERE;
var myRepo = YOUR_REPO_HERE;
var request = new XMLHttpRequest();
request.open('GET', apiRoot + '/repos/' + myUser + '/' + myRepo + '/readme');
request.setRequestHeader('Accept','application/vnd.github.v3.html');
/* add event listeners... */
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status === 200) {
document.body.innerHTML = request.response;
}
};
request.send();