Not able to get external API data through JQuery - json

I am trying to get external REST API data through JQuery, but it returs undefined. But when I use my local REST API url, it works. Can anybody explain whats is the problem. Any code sample will be appreciated.
This how i am accessing external Rest API via JQuery.
function GetCompanyName(id) {
jQuery.support.cors = true;
$.ajax({
url: 'http://novacompanysvc.azurewebsites.net/api/companies' + '/' + id,
type: 'GET',
dataType: 'jsonp',
success: function (data) {
WriteResponse(data);
},
error: function (x, y, z) {
alert("company" + x + '\n' + y + '\n' + z);
}
});
}

result is XML so you need to set dataType: "text/xml" and then parse it:
success: function (data) {
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(data);
}
I tried to test this but I got: is not allowed by Access-Control-Allow-Origin that is same-origin restriction so make sure you have access to this API or you will have to do it on the server using CURL in PHP for example.
Your are getting id variable in the function you showed in your question, but you are no using it,
if you want to send it add:
,data:{ id:id }
Request should look something like this:
function GetCompanyName(id) {
jQuery.support.cors = true;
$.ajax({
url: 'http://novacompanysvc.azurewebsites.net/api/companies',
type: 'GET',
data:{ id:id },
dataType: "text/xml",
success: function (data) {
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(data,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(data);
}
WriteResponse(data);
},
error: function (x, y, z) {
alert('error');
}
});
}

Related

Partial View loading using javascript : Possible XSS by HP FORTIFY

I have a js function , which Fortify identified as XSS vulnerable as below. Can you suggest any solution for this since the method is intensively used in my app.
I am here trying to call a partialview in ajax and the result html am appending to a specified dom div
My function look like the below
function loadPartialViewToDiv(div, obj, api) {
try {
const myUrl = new URL(window.location.origin + api); // always local URL only
$.ajax({
url: myUrl ,
data: obj,
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
if (data != undefined && data != null) {
$('#' + div).html(data);
}
}
});
} catch (e) {
('#' + div).html('Error');
}
}
The dynamic DOM element id was the issue ($('#' + div).html(data); ), we fixed it using two methods
giving a static id. $('#abcd').html(data);
OR
change as $('#' + div).text($(data));

calculatematrix using the javascript API rather than REST

I'm trying to use the calculatematrix API to take a load of destinations and calculate the driving distance to them from a given location (my examples first convert the postcode to a latlng)
Using the REST api and JQuery I can get this to work fine. See this JSFiddle - https://jsfiddle.net/vostrx9m/
$.ajax({
url: 'https://geocoder.api.here.com/6.2/geocode.json',
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsoncallback',
data: {
app_id: 'XHHvADl4hLUQWLbUOGNp',
app_code: '-Zhl4CYrM03JxXabdROElA',
searchtext: 'TR9 6QA'
},
success: function(data) {
var LatLon = data.Response.View[0].Result[0].Location.NavigationPosition[0].Latitude + "," + data.Response.View[0].Result[0].Location.NavigationPosition[0].Longitude;
$.ajax({
url: 'https://matrix.route.api.here.com/routing/7.2/calculatematrix.json',
type: 'GET',
dataType: 'jsonp',
jsonp: 'jsoncallback',
data: {
mode: 'fastest;truck;traffic:disabled;',
start0: LatLon,
destination0: '50.395118,-4.934356',
destination1: '50.464852,-5.031908',
destination2: '50.541548,-4.938789',
app_id: 'XHHvADl4hLUQWLbUOGNp',
app_code: '-Zhl4CYrM03JxXabdROElA',
summaryAttributes: 'distance,traveltime'
},
success: function(data) {
for (i in data.response.matrixEntry) {
$('p').append("dest(" + i + "), " + data.response.matrixEntry[i].summary.distance + " meters, " + data.response.matrixEntry[i].summary.travelTime + " seconds<br\>");
}
}
});
}
});
However our site uses MooTools, so I've rewritten this against mootools and I now get CORS issues. "has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status." It looks like the preflight gets a permission error - see this JSFiddle here - https://jsfiddle.net/1av2wkye/5/
getDistancesFromPostCode('TR84LP')
function getDistancesFromPostCode(StartPostCode) {
console.log('getDistancesFromPostCode: ' + StartPostCode)
var req = new Request({
method: 'get',
url: "https://geocoder.api.here.com/6.2/geocode.json",
data: {
app_id: 'XHHvADl4hLUQWLbUOGNp',
app_code: '-Zhl4CYrM03JxXabdROElA',
searchtext: StartPostCode
},
onComplete: function(data) {
console.log(data)
var StartLatLon = data.Response.View[0].Result[0].Location.NavigationPosition[0].Latitude + "," + data.Response.View[0].Result[0].Location.NavigationPosition[0].Longitude;
console.log(StartLatLon)
getDistancesFromLatLng(StartLatLon)
},
}).send();
}
function getDistancesFromLatLng(StartLatLon) {
console.log('getDistancesFromLatLng: ' + StartLatLon)
var req = new Request({
method: 'get',
url: "https://matrix.route.api.here.com/routing/7.2/calculatematrix.json",
data: {
mode: 'fastest;truck;traffic:disabled;',
start0: StartLatLon,
destination0: '50.4153650,-5.0698703',destination1: '50.4154830,-5.0698890',destination2: '50.473036820553446, -4.707902895605457',
app_id: 'XHHvADl4hLUQWLbUOGNp',
app_code: '-Zhl4CYrM03JxXabdROElA',
summaryAttributes: 'distance,traveltime'
},
onComplete: function(data) {
console.log(data)
for (i in data.response.matrixEntry) {
console.log("dest(" + i + "), " + data.response.matrixEntry[i].summary.distance + " meters, " + data.response.matrixEntry[i].summary.travelTime + " seconds<br\>");
}
},
}).send();
}
Any ideas what MooTools is doing wrong or how I fix that?
If not, I tried a different tactic by writing things against the Javascript API and I got the geoencode working, but I cannot see any reference to the calculatematric API in the JavaScript documentation, any ideas?
Thanks
As the request should be a JSONP type request , i would guess using Request.JSONP from MooTools should help with the CORS issue. HERE Javascript API does not have support for the calculate matrix end point of the API.

Post list of string null on web api controller

In my web api project, I got a controller named ContactController and a method named Synchro in it which waits for a list of string as below:
[HttpPost]
[Route("api/Contact/Synchro")]
public IHttpActionResult Synchro([FromBody]List<string> listNumTel)
{
List<Profil> listContact = new List<Profil>();
if (listNumTel.Count() > 0)
{
try
{
listContact = Librairie.Contacts.getContactSync(listNumTel);
return Ok(listContact);
}
catch(Exception e) {
return InternalServerError(e);
}
}
else
{
return BadRequest();
}
}
To test that method, I've created the ajax called below:
$("#btn_synchro").click(function () {
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: {
"listNumTel": [
"+33640512999",
"+33640522997",
"+33640182998",
"+33640742996"]
},
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
When I test on debug mode, the call works fine but the method get a null list. I checked if the json is valid and it is. Does Somebody sees what could be wrong ? Thanks in advance !
Thanks for the answers, but I've just found out the solution. It was all about JSON sent. To send a list of string by an ajax call for example, the JSON should looks like below the variable listNumero
("#btn_synchro").click(function () {
var listNumero =
[ '+33640532999',
'+33640532997',
'+33640532998',
'+33640532996'];
$.ajax({
url: '../api/Contact/Synchro',
type: 'POST',
data: JSON.stringify(listNumero),
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('Synchro réussi: ' + data);
},
error: function (request, error) {
alert("Erreur lors de la synchro");
}
})
});
You can compare to my post, the JSON is different. Now my web api controller can get the values from the list.

How to read the JSON file using jQuery in ASP.NET?

I have tried this alot but always I am getting the failure problem .Can any one guide how can we read the json file using jQuery?I have a json file in my project as given in this image
i have written the code as given below
$(document).ready(function () {
$('#btnLoad').click(function () {
$.ajax({
url: "example.json",
dataType: "text/json",
type: "GET",
contentType: "application/json;charset=utf-8",
success: function (msg) {
AjaxSucceeded(msg);
},
error: AjaxFailed
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
}
function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}
But It is always AjaxFailed is firing.
dataType should be 'JSON'
There are only 4 accepted values for dataType, which you can see here:
http://docs.jquery.com/Specifying_the_Data_Type_for_AJAX_Requests
Also, your error function takes 3 parameters:
errorFn(jqXHR, textStatus, errorThrown) {
// your code
}
Additionally, this:
success: function (msg) {
AjaxSucceeded(msg);
},
Can be this:
success: AjaxSucceeded
Your success function also takes 3 parameters:
success(data, textStatus, jqXHR)
For reference on $.ajax parameters: http://api.jquery.com/jQuery.ajax/

Calling service from Html

i want to call asp.net web service from java script and pass the parameters to it .is there any code sample or demostration that will help me to acheive that??
thanks in advance
JQuery:
function AddLocation(ParentID) {
$.ajax({
type: "POST",
url: "../server.asmx/Save",
data: "{'ID':'0','ParentID':'" + ParentID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var item = document.createElement('option');
item.value = data.d.split("$")[0];
item.text = name;
//do stuff
}
});
}
jQuery supports this behavior. you can use jQuery to do the ajax call as show below. this method has two call back functions for success and for failure.
function loadData()
{
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
url: 'methodurl',
success: methodSuccedded,
error: methodFailure
});
}
function methodSuccedded()
{
//do your logic.
}
function methodFailure()
{
//do your logic.
}
You can do so, using AJAX, and get the response from the server as an JSON object.
var xmlHttp = new ActiveXObject("Microsoft.XmlHttp");
var url = "Service1.svc/ajaxEndpoint/";
url = url + "Sum2Integers";
var body = '{"n1":';
body = body + document.getElementById("num1").value + ',"n2":';
body = body + document.getElementById("num2").value + '}';
// Send the HTTP request
xmlHttp.open("POST", url, true);
xmlHttp.setRequestHeader("Content-type", "application/json");
xmlHttp.send(body);
// Create result handler
xmlHttp.onreadystatechange= function X()
{
if(xmlHttp.readyState == 4)
{
result.innerText = xmlHttp.responseText;
}
}
Getting the response as JSON would help you evualte it asn object and u can act on it through JavaScript.
See these links for reference:
http://blogs.msdn.com/b/alikl/archive/2008/02/18/how-to-consume-wcf-using-ajax-without-asp-net.aspx
http://dotnetslackers.com/articles/ajax/JSON-EnabledWCFServicesInASPNET35.aspx
The below link is a pretty decent method from my experience.
http://encosia.com/2008/03/27/using-jquery-to-consume-aspnet-json-web-services/