I've racked my brain over this and I cant seem to figure out the solution so ask humbly for your assistance please. I'm using the restlet client on chrome which uses a cURL command to GET json from a server. I need to convert this curl command over to AJAX, and I'll provide as much code as I'm allowed to. Could you please help me by converting this over to jQuery's Ajax?
cURL Command:
curl -i -L -X GET \
-H "Authorization:Basic base64username:base64password" \
'https://internalserverurl'
Here's what I have for my jQuery AJAX Method:
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
function getData() {
$.ajax({
url: "https://internalurl",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("username:password"));
},
type: 'GET',
dataType: 'json',
contentType: 'application/json',
processData: false,
success: function (data) {
alert(JSON.stringify(data));
console.log(data);
},
error: function (data) {
var strBuilder = [];
for(key in data){
if (data.hasOwnProperty(key)) {
strBuilder.push(key + ":" + data[key] + "<br><br>");
}
}
alert(strBuilder.join(""));
$('#errordiv').html(strBuilder);
}
});
}
Thank you all for your assistance.
I said it in the comments, but you can use the $.ajax function and set your headers in the beforeSend block.
$.ajax({
url: 'https://internalserverurl',
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('Authorization':'Basic base64username:base64password');
}
Related
So I am trying to shorten an URL with the new V4 Bitly API, but I am getting an JSON error.
My code:
$(function() {
$(".createBitly").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
var accessToken = "xxx";
var params = {
"long_url" : encodeURIComponent(url)
};
$.ajax({
url: "https://api-ssl.bitly.com/v4/bitlinks",
cache: false,
dataType: "json",
method: "POST",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
},
data: params
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.error(data);
});
});
});
Results: a 422 http error;
"{"message":"UNPROCESSABLE_ENTITY","resource":"bitlinks","description":"The JSON value provided is invalid."}"
But running it with CURL does work though: How to shorten URL using PHP Bitly v4?
What am I doing wrong? Is it not possible with jQuery only?
TIA.
I had made this edit from your code above and its working well.
1) JSON.stringify before sending request (convert your request to JSON format).
2) No need for encodeURIComponent().
$(function() {
$(".createBitly").on("click", function(e) {
e.preventDefault();
var url = $(this).attr("href");
var accessToken = "token";
var params = {
"long_url" : url
};
$.ajax({
url: "https://api-ssl.bitly.com/v4/shorten",
cache: false,
dataType: "json",
method: "POST",
contentType: "application/json",
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + accessToken);
},
data: JSON.stringify(params)
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
});
});
I am trying to send a request using ajax to a server which is protected by basic authentication with the following code:
$('document').ready(function(){
$.ajax({
url: "https://somesite.com/somefolder",
type: "POST",
dataType: 'jsonp',
beforeSend: function(xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa('myusername' + ":" + 'mypassword'));
},
success: function(data){
console.log('SUCCESS!');
},
error: function () {
console.log("error");
}
});
});
So I provide the credentials in the beforeSend so my expectation would be that there would be no credential popup from the browser since I already provided the credentials but unfortunately when i run this code I get the popup to enter my credentials. I want to the code to provide these credentials.
Similar to this question, example using headers:
$.ajax({
url: "https://somesite.com/somefolder",
type: "POST",
dataType: 'jsonp',
headers: {"Authorization": "Basic " + btoa('myusername' + ":" + 'mypassword')},
success: function(data){
console.log('SUCCESS!');
},
error: function () {
console.log("error");
}
});
I have a rest API which has some nice JSON I want. I want to be able to call the API from a script within some HTML and pull out the JSON thats relevant to me.
What would be my best approach?
Something like the below using ajax? but i can't find a nice working example.
I have a token for my API so its vital I can use this. A curl command would be perfect, alas I cant do that. Eventually what I do will be used in a chrome extension.
jQuery.ajax( {
url: 'https://my-api.com/rest/v2/users/'
type: 'GET',
data: { content: 'testing test' },
beforeSend : function( xhr ) {
xhr.setRequestHeader( "Authorization", "BEARER " + xxxxxxxxx );
},
success: function( response ) {
// response
}
} );
Try this
var myJson;
$.ajax( {
url: 'https://my-api.com/rest/v2/users/'
type: 'GET',
data: { content: 'testing test' },
headers: { 'Authorization' = 'Bearer ' + token },
success: function( response ) {
myJson = response;
}
} );
Here there is the official explanation of the getJSON() method with some examples
https://api.jquery.com/jQuery.getJSON/
var authorizationToken = "xxxxxxx";
function xRequest(endpoint, method, options) {
$.ajax($.extend({}, {
type: method,
dataType: "json",
url: "https://api.xxxx.com/" + endpoint,
headers: {
"Authorization": "Token token=" + authorizationToken,
"Accept": "application/vnd.xxxxxx+json;version=2"
}
},
options));
}
This works
I've done a new database with a user interface (with Javascript code) and Iam trying to connect the UI with TFS API to get some informations and save it in my Databas
but i have challenge in establishing this connectioin with Javascript
can anyone help me please??
If you want to do this via a javascript client, you could use the invoke as follows:
var self = this;
self.tasksURI = 'https://<SERVER>/tfs/<COLLECTION>/<PROJECT>/_apis/build/builds?api-version=2.0';
self.username = "<USERNAME>"; //basic username so no domain here.
self.password = "<PASSWORD>";
self.ajax = function (uri, method, data) {
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: JSON.stringify(data),
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa(self.username + ":" + self.password));
},
error: function (jqXHR) {
console.log("ajax error " + jqXHR.status);
}
};
return $.ajax(request);
}
self.ajax(self.tasksURI, 'GET').done(function (data) {
alert(data);
});
More details please refer this similar question in SO: TFS 2015 REST API Authentication
I have a REST API and I am wanting to invoke it from my ajax javascript client.
I make the call and nothing happends. My mobile browser just indicates 'busy'.
No error is returned.
This is my code behind:
[HttpPost]
[Route("Services/Image/Validate")]
public byte Validate(string KeyCode)
{
return 1;
}
this is my JavaScript client:
$("#btnValidate").click(function () {
try {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
fail: function (a) {
$("#error").html(objRequest);
}
});
}
catch (ex)
{
$("#error").html(ex);
}
return false;
});
The catch function with throw an error only when the HTTP request fails. In Order to know wha'ts going wrong in the server side code you need to use the error function in the ajax request,
You also mentioned that the browser does nothing and this might happen due to
jQuery plugin not included in the page (check console for $ is not defined)
Add the jquery plugin above your javascript
If your server side code is on a different domain enable CORS
$("#btnValidate").click(function () {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
error: function (e) {
console.log(e.responseText); //Acutal error
console.log(e); //Get the entire error details
}
});
});
The settings object you are sending to $.Ajax() does not expect a fail parameter. Maybe you are confusing promises?
Anyway, it should probably be error.
eg.
$("#btnValidate").click(function () {
try {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
error: function ( jqXHR, textStatus, errorThrown) {
$("#error").html(textStatus);
}
});
}
catch (ex)
{
$("#error").html(ex);
}
return false;
});
Also, I'm not sure if you should have the data property as a string but maybe this is how you want it.
All documentation on this is HERE