Retrieve OData using AJAX in json format, with authentication - json

I need to convert this OData retrieval (using SAPUI5 libs):
var url = "http://someurl/SERVICE";
var username = "username";
var password = "password";
var oModel = new sap.ui.model.odata.ODataModel(url, true, username, password);
into an ajax call, without using SAPUI5 libraries, mantaining the authentication:
$.ajax({
url : "http://someurl/SERVICE?$format=json",
type: "GET", //or POST?
dataType: "json",
data : {username : "username", password: "password"},
success: function(){alert("ok")},
error: function(){alert("error")}
})
I googled a lot but I didn't find anything useful.. I don't know how can I do the authentication.
is it possible? Any idea?

Instead of setting "data:..."
you need to handle this in such way :
$.ajax({
url : "http://someurl/SERVICE?$format=json",
type: "GET", //or POST?
dataType: "jsonp",
xhrFields:
{
withCredentials: true
},
beforeSend: function (request)
{
request.setRequestHeader("Authorization", "Basic dG9tY2F0OnRvbWNhdA==");
},
success: function(){alert("ok")},
error: function(){alert("error")}
})
Where "dG9tY2F0OnRvbWNhdA==" is base64 encoded user and password.
And of course, this will work only for Basic authentication.
Or another option is to put user/password in the url directly :
$.ajax({
url : "http://user:password#someurl/SERVICE?$format=json",
type: "GET", //or POST?
dataType: "jsonp",
success: function(){alert("ok")},
error: function(){alert("error")}
})

Related

I can't make REST call to the localhost server for RESTful webservices

$.ajax({
url: "http://localhost:8080/speed-search-api/keys/getAll",
crossDomain : true,
dataType : "jsonp",
type : "GET",
success: function(data){
document.getElementById("demo").innerHTML = data[0].keyName;
}
});
When i am trying to make a call to localhost which has RESTful services, it doesn't display anything? I am wondering why? POSTMAN i can see the data.

posting json to express - invalid json

I am trying to post some json to a node server running express but it keeps telling me the json was invalid. But its not, its just a plain old object. Currently I get the error 'unexpected token i'
client:
$.ajax({
contentType: 'application/json',
type: "POST",
url: "/admin",
data: {id: '435ghgf545ft5345', allowed: true}
});
server:
var bodyParser = require('body-parser');
app.use(bodyParser({strict: false}));
app.post('/admin', function(request, response) {
console.log(request.body);
});
I have also tried putting bodyParser.json() as the second parameter in the post route and get the error 'invalid json at parse'. I cant figure out why.
This code may help you :
var jsondataResource = JSON.stringify({id: '435ghgf545ft5345', allowed: true});
$.ajax({
type: 'POST', //GET or POST or PUT or DELETE verb
async: false,
url: '/admin', // Location of the service
data: jsondataResource , //Data sent to server
contentType: 'application/json', // content type sent to server
dataType: 'json', //Expected data format from server
processdata: true, //True or False
crossDomain: true,
success: function (msg, textStatus, xmlHttp) {
result = msg;
},
error: ServiceFailed // When Service call fails
});
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
Type = null; Url = null; Data = null; ContentType = null; DataType = null; ProcessData = null;
}

Headers using ajax request

How to set headers using Ajax request? in below code
$.ajax({
type: type, //GET or POST or PUT or DELETE verb
url: requestURL, // Location of the service
// contentType: "application/x-www-form-urlencoded", // content type sent to server
dataType: "xml", //Expected data format from server
processData: false, //True or False
success: successCallback, //On Successfull service call
error: serviceFailed// When Service call fails
});
Request headers can be managed using beforeSend(jqXHR, settings) function and the setRequestHeader method, e.g.
$.ajax({
...
beforeSend : function(xhr) {
xhr.setRequestHeader('content-Type', 'application/x-www-form-urlencoded');
}
});

JSON data not parsing in node.js displays undefined in console

JSON data not parsing in node.js displays undefined in console..
Here is HTML code:
var jsonObjects = [{id:1, name:"amit"}];
jQuery.ajax({
url: 'http://localhost:8081',
type: "POST",
data: {"id":"1", "name":"amit"},
dataType: "json",
success: function(result) {
alert("done")
}
});
Here is Nodejs code:
http.createServer(function (request, response)
{
response.writeHead(200, {"Content-Type":"text/plain"});
var urlObj = JSON.stringify(response.data, true);
console.log(urlObj)
response.end();
}).listen(8081);
Try using GET method Instead of Post. Try this
var jsonObjects = [{id:1, name:"amit"}];
$.ajax({
type: 'GET',
url: 'http://localhost:8081',
data: {
jsonData: JSON.stringify(jsonObjects)
},
dataType: 'json',
complete: function(validationResponse) {
}
});
The data will be held in the request, not the response as it has come from the client request.
If you are using express to create your http server you will also need to tell it to use the bodyParser middle wear.

MVC2 JSON input

I have a problem with a simple VS2010 .NET 4.0 MVC2 application.
My controller action looks like this:
public JsonResult GetJson(string query)
I access the action with jQuery like so:
function getJson() {
var postdata = {};
postdata['query'] = $('#query').val();
$.ajax({
type: "POST",
url: '<%= Url.Action("GetJson") %>',
data: JSON.stringify(postdata),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
The action is executed upon the jQuery XHR request, but no matter what the "query" value is ALWAYS null. I can view the POST request/response in Firebug, and it shows the proper JSON string being sent to the action.
What could the problem be? It just seems like MVC is not parsing/deserializing the JSON input at all.
Thanks!
Please try this as it should work for you:
$.ajax({
type: "POST",
url: '<%= Url.Action("GetJson") %>',
data: {query: $('#query').val()},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
}
});