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.
Related
I tried to integrate the diagram viewer in my webapp. The error happend while loading the page http://localhost:8080/MyActiviti/diagram-viewer/index.html?processDefinitionId=myProcess:1:4&processInstanceId=10001
The following is error info, I haved checked the json format of responseText, any other solutions?
Just comment dataType line in ActivitiRest.js.There should be three positions.
like this:
$.ajax({
url: url,
//dataType: 'jsonp',
cache: false,
async: true,
success: function(data, textStatus) {
var processDefinition = data;
if (!processDefinition) {
console.error("Process definition '" + processDefinitionKey + "' not found");
} else {
callback.apply({processDefinitionId: processDefinition.id});
}
}
}).done
I'm Developing A windows Phone 7 Application Using Phone Gap.Language Used[HTML,css,JavaScript]
I'm using A web Service For Get Json Data Web service And Bind In Drop Down List.
In Single Page I'M Using 5 AJAX Calls Ex[Age,Height,Religion,Cast,Country,Language,Status,Education]
My Sample Ajax Call For Age given Below.
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "https://www.xxxxxxxx.com/yyyyyyyy/zzzzzzzzzz.svc/GetMasterDataoverHTTPS?AuthToken=" + encodeAuthtoken + "&ListKey=" + encodeListkey + "&ListValue=" + encodeMinAge,
crossDomain: true,
dataType: "jsonp",
success: function (data) {
var result = data;
$.each(result, function (key, value) {
var appenddata = "<option value = '" + value.ListKey + "'>" + value.ListValue + " </option>";
$('#ddlSFromAge').html($('#ddlSFromAge').html() + appenddata);
});
//alert(result);
},
error: errorResponse
});
function errorResponse(xhr, ajaxOptions, thrownError) {
alert('Error on Ajax Call' + '\n Status: ' + xhr.status + '\n Response Text: ' + xhr.responseText + '\n Error: ' + thrownError);
}enter code here
For Each And Ever Drop Down I call Like This . I know This Is Not Good.
Any One Tell Me How To Reduce This AJAX call's [For Each Drop down Separate URL Used]
I am guessing you are using so many ajax calls because the data types are dynamic? If they are not dynamic, then you should really consider using the device sqlite database to store your values and just query that. Documentation can be found here.
If you really really need to make that many calls because the data is dynamic then so be it. But instead of having 5 seperate AJAX functions you can just use 1 function and either pass the function your url you want it to use function ajaxCall('http://www.myserviceurl') or pass it a value to run agains a switch to determine what url to use.
I Changed My Code Like This Credits Go To #Dom
<script type="text/javascript">
doAjaxCall("Country");
doAjaxCall("Language");
doAjaxCall("religion");
doAjaxCall("Caste");
function doAjaxCall(type) {
var url;
switch (type) {
case "Country":
url = "https://www.xxxxxx.com/yyyyyyy/GetCountryoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlCountry');
break;
case "Language":
url = "https://www.xxxxxx.com/yyyyyyy/GetLanguageoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlLanguage');
break;
case "religion":
url = "https://www.xxxxxx.com/yyyyyyy/GetReligionoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlReligion');
break;
case "Caste":
url = "https://www.xxxxxx.com/yyyyyyy/GetMotherTongueoverHTTPS?AuthToken=Z0lFITFVMw==&FormCode=U1A=";
ajaxCall(url, '#ddlMother');
break;
default:
url = ""; //or some other code to execute if type doesnt match anything
}
function ajaxCall(paramurl,paramControlId) {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: url,
crossDomain: true,
dataType: "jsonp",
success: function (data) {
var result = data;
$.each(result, function (key, value) {
var appenddata = "<option value = '" + value.ListKey + "'>" + value.ListValue + " </option>";
$(paramControlId).html($(paramControlId).html() + appenddata);
});
//alert(result);
},
error: errorResponse
});
function errorResponse(xhr, ajaxOptions, thrownError) {
alert('Error on Ajax Call' + '\n Status: ' + xhr.status + '\n Response Text: ' + xhr.responseText + '\n Error: ' + thrownError);
}
}
}
</script>`
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');
}
});
}
When I debug using Firebug I see the control jumping to error section after hitting success. I am unable to find out what is going wrong. Can some body please point out what is wrong with this code.
$(function(){
$.ajax({
type: "POST",
url: "service/MyService.asmx/GetAsgInfo",
data: "{id: " + parseInt($('#AsgId').val()) + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// var s = eval('(' + msg.d + ')');
alert(msg.d[0].SubmittedCount);
},
error: function (e) {
alert("error : " + e);
}
});
});
POST :
{id: 5301}
RESPONSE :
{"d":[{"__type":"Proxies.AFARServiceRef.AssignmentInfo","ExtensionData":
{},"AssignDate":"\/Date(1319526000000)\/","AssignFileName":null,"ClaimId":"MH001025","ClaimantName":"Deborah C Plaid","FirstContactDate":"\/Date(1319526000000)\/","FirstContactTime":
{"Ticks":420000000000,"Days":0,"Hours":11,"Milliseconds":0,"Minutes":40,"Seconds":0,"TotalDays":
0.4861111111111111,"TotalHours":11.666666666666666,"TotalMilliseconds":42000000,"TotalMinutes":700,"TotalSeconds":42000},"Id":5301,"InspectionDate":"\/Date(1319612400000)\/","StatusId":1,
"SubmittedCount":4,"UploadedCount":14}]}
Instead of using the success and error functions, try using complete:
complete: function(jqXHR, textStatus) {
alert(textStatus);
}
I had a similar problem with handling json, and it turns out I wasn't setting the content-type properly on the server side. Even valid json sometimes causes weird errors when it is in a response labeled as "text/plain" or even "text/json". Make sure your content type is right.
I am trying to get JQueryUI's Autocomplete code working with an ASMX web service. I am getting close, but hit yet another wall yesterday. The JSON data is being returned in {d:"data"} format (see http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx). My data now looks like:
d: "[{"DOTNumber":"001061010","JobTitle":"Project Architect"},{"DOTNumber":"003061005","JobTitle":"Principal Electrical Engineer"}]"
My code is:
$(function() {
function log(message) {
$("<div/").text(message).prependTo("#log");
$("#log").attr("scrollTop", 0);
}
});
$("#dotmatch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function(data) {
var safe = data;
response($.map(safe.d, function(item) {
return {
label: item.JobTitle + "(" + item.DOTNumber + ")",
value: item.DOTNumber
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
log(ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value);
$get("DOTNumber").value = ui.item.value;
},
});
The problem lies in the success function.
What is the right syntax to get past the "d" issue?
Your data should look like this:
{"d":[{"DOTNumber":"001061010","JobTitle":"Project Architect"},"DOTNumber":"003061005","JobTitle":"Principal Electrical Engineer"}]}
It appears you are missing quotes around your "d" and you have extra quotes around your array.
Don't eval() your data - this opens you up to more security issues than the d: prevented.. You should have access to JSON.parse() or if not jQuery.parseJSON() (which wraps JSON.parse() if available... depends on your target platform(s)).
This has been an incredibly difficult process, but I finally got it working. There were a number of hurdles:
1) My JSON return string was getting wrapped in an XML blanket, so it would not parse
2) Solving this problem required the contentType: 'application/json' line
3) With that content type, a POST was required. GET would not work
4) POST required putting the data together using the JSON.stringify. I am still not sure about this one, but I found some code somewhere that did it.
5) Data coming back from the POST was prefixed with a "d " (see: http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
6) getting access to the data itself required the "eval(data.d)" line.
$("#dotmatch").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "/AutoSuggestJSTest/AutoSuggest.asmx/DOTFind",
contentType: 'application/json',
dataType: "json",
data: JSON.stringify({ prefixText: request.term, count: 20 }),
success: function(data) {
var output = eval(data.d);
response($.map(output, function(item) {
return {
label: item.JobTitle + "(" + item.DOTNumber + ")",
value: item.DOTNumber
}
}));
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
minLength: 2
});
If I ever have this much trouble writing a few lines of code again, I am going to take a very large guage shotgun to my computer!
Bob Jones
If you use a WCF JSON service with the webHttpBehavior (instead of enableWebScriptBehavior), it will not emit the "d"