How to make an AJAX call to GraphHopper Matrix API - javascript

I need to send this json with the following information, but at the time of making the request I get an error
message: "Unsupported content type application/x-www-form-urlencoded; charset=UTF-8"
status: "finished"
I don't the correct way to the request
request sent for JS and Jquery:
<script>
$("#request").click(() => {
var url = "https://graphhopper.com/api/1/matrix?key=d5ab0f9f-538a-4842-926a-9667970d4061";
var data = {
"elevation": false,
"from_points": [-33.467482, -70.624736],
"to_points": [
[-33.468756, -70.622155],
[-33.467359, -70.627332],
[-33.466348, -70.621985]
],
"from_point_hints": ["nuble"],
"to_point_hints": [
"place 1",
"place 2",
"place 3"
],
"out_arrays": [
"distances",
"times"
],
"vehicle": "car"
};
$.ajax({
url: url,
data: JSON.stringify(data),
method: 'POST',
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
});
</script>

you must first enter the longitude and then the latitude and the next error you had was to specify the head of the ajax request
the code would be:
var url = "https://graphhopper.com/api/1/matrix?key=myKey";
var data ={
"from_points": [
[
-70.6247406,
-33.4673461
]
],
"to_points": [
[
-70.913138,
-33.794796,
]
],
"from_point_hints": [
"ñuñoa"
],
"to_point_hints": [
"places 1"
],
"out_arrays": [
"times",
"distances"
],
"vehicle": "car"
};
$.ajax({
beforeSend: function(xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/json");
xhrObj.setRequestHeader("Accept", "application/json");
},
url: url,
data: JSON.stringify(data),
type: 'POST', //en este caso
dataType: 'json',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});

Related

How to parse JSON values and populate to combobox using EXTJS 4.2.1?

The method:
Ext.Ajax.request({
url: 'url',
method: 'GET',
timeout: 60000,
params: {
"perviceTypeId": my.rec.data.prepeId
},
success: function(response) {
var jsonResp = response.responseText;
console.log("ajax data responseText::" + jsonResp);
//how to parse value and display and populate to deageType combobox
var combo = Ext.getCmp('deageType');
}
});
The response is JSON:
{
"message": null,
"data": [
{
"value": "ESS",
"display": "ESS"
},
{
"value": "ANS",
"display": "ANS"
}
],
"errorCode": -1,
"totalCount": 1,
"messages": null,
"resultDate": 1615282701392,
"success": true
}
You can do that:
var combo = Ext.getCmp('myCombo');
combo.store = Ext.create('Ext.data.Store', {
fields: ['value', 'display'],
data: responseJSON.data
});
Here is functional fiddle with that example: https://fiddle.sencha.com/#view/editor&fiddle/3cb0
You should decode the response (using Ext.JSON.decode) and bind the store (using bindStore) to combo:
Example:
Ext.Ajax.request({
url: 'url',
method: 'GET',
timeout: 60000,
params: {
"perviceTypeId": my.rec.data.prepeId
},
success: function(response) {
var jsonResp = Ext.JSON.decode(response.responseText);
var combo = Ext.getCmp('deageType');
combo.bindStore(Ext.create('Ext.data.Store', {
fields: ['display', 'value'],
data: jsonResp['data']
}));
}
});

How to set json model with array of data returned from function

I have a sapui5 application:
I have an xml view called "Submission.view and corresponding controller called "submission.controller".
I have method which is fetching some question id's from a service using certain input parameters.
For example if i pass "null" and "previous" it gives me a json response as:
[
{
"__type__": "QuestionOutput",
"QuestionType": "",
"QuestionID": 51,
"YesNo": "",
"Mandatory": false
},
{
"__type__": "QuestionOutput",
"QuestionType": "",
"QuestionID": 52,
"YesNo": "",
"Mandatory": false
},
{
"__type__": "QuestionOutput",
"QuestionType": "",
"QuestionID": 53,
"YesNo": "",
"Mandatory": false
}
]
Now i want to pass each of the questionid's like 51,52,53 to another method which calls a rest service to fetch the descriptions for the above questionid's from hana data base.
getBpmRules: function(sToken, sQuestionId, sAnswer) {
var that = this;
this.showBusy();
jQuery.ajax({
type: "POST",
contentType: "application/json",
dataType: "json",
async: false,
url: "/bpmrulesruntime/rules-service/v1/rules/invoke?rule_service_name=SelfServiceRule::QuestionRuleService",
context: that,
xhrFields: {
withCredentials: true
},
headers: {
'X-CSRF-Token': sToken
},
data: JSON.stringify([{
"__type__": "QuestionInput",
"QuestionID": "" + sQuestionId + "",
"Answer": "" + sAnswer + ""
}]),
error: function(jqXHR, textStatus, errorThrown) {
that.hideBusy();
sap.m.MessageBox.alert(textStatus + " - " + errorThrown + " : " + jqXHR.responseText, {
icon: sap.m.MessageBox.Icon.ERROR,
title: this.getText("error")
});
},
success: function(data, textStatus, jqXHR) {
var questiondesc = [];
if (data.length !== 0) {
var desc = [];
//this.getModel("questionModel").setProperty("/questionDescription", data);
for (var i = 0; i < data.length; i++) {
desc = that.getQuestionDescriptionById(data[i].Question, sToken);
}
}
that.hideBusy();
this._oManagerBusy.setVisible(false);
this._showSendDialog();
}
});
}
After getting the json data i am just looping and passing the question ids to another method to get the description for each question which again is a json response.
getQuestionDescriptionById: function(id, token) {
jQuery.sap.log.debug("Getting question by Id");
var questionDescription = [];
this.getComponent().ajax({
method: "GET",
url: "/selfservice/rest/question/admin/questionid/" + id,
contentType: "application/json",
context: this,
headers: {
'X-CSRF-Token': token
},
error: function(jqXHR, textStatus, errorThrown) {
this.getModel("resources").setProperty("/ticketSubmitMessage", this.getModel("i18n").getProperty("sendDialogText"));
this._oManagerBusy.setVisible(false);
this._showSendDialog();
},
success: function(data, textStatus, jqXHR) {
//oModel.loadData(“json/Item.json”);
// this.getView().setModel(new JSONModel(data.question,"questionDescription"));
if (data.length !== 0) {
questionDescription.push(data);
}
}
});
return questionDescription;
},
Issue:
I am not able to set the model for the view with the json response that i am getting from the second method since for each questionid it goes to the next method "getQuestionDescriptionById" and even though i return the response..it doesn't work.
Can you please let me know how to set a json model for each response that i get for each question id.
Thanks !!

Iterate through json object array in jQuery

I am using CodeIgniter. In my Controller file, I have JSON containing an array (as a result of calling different API's):
{
"Specialities": [{
"SpecialityID": 1,
"SpecialityName": "Eye Doctor"
},{
"SpecialityID": 2,
"SpecialityName": "Chiropractor"
},{
"SpecialityID": 3,
"SpecialityName": "Primary Care Doctor"
}]
}
In controller, I wrote
echo $response[0];
with this line of code I can easily iterate through json object in jquery:
$.ajax({
type: 'GET',
url: 'http://localhost/rest_project/main/res',
dataType: 'JSON',
crossDomain: true,
xhrFields: { withCredentials: true },
success: function (data){
$.each(data.Specialities,function(key,value){
console.log(value.SpecialityName);
});
}
});
but if I pass the array:
echo json_encode($response);
Then I am unable to get the results:
$.ajax({
type: 'GET',
url: 'http://localhost/rest_project/main/res',
dataType: 'JSON',
crossDomain: true,
xhrFields: { withCredentials: true },
success: function (data){
$.each(data[0].Specialities,function(key,value){
console.log(value.SpecialityName);
});
}
});
Can someone help me please?
It seems that your jsonObject is not an array and each works with array only.
//Check if your jsonObject is array, if not then make it.
if (!$.isArray(jsonObject)) {
jsonObject = [jsonObject];
}
$.each(jsonObject, function(key, value){
console.log("FULL NAME " + value.FullName);
});
var data = {
"Specialities": [{
"SpecialityID": 1,
"SpecialityName": "Eye Doctor"
},{
"SpecialityID": 2,
"SpecialityName": "Chiropractor"
},{
"SpecialityID": 3,
"SpecialityName": "Primary Care Doctor"
}]
};
//Convert your jsonObject to array for each
if (!$.isArray(data)) {
data = [data];
}
$.each(data[0].Specialities,function(key,value){
console.log(value.SpecialityName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

How to use JSONP?

The example I am working with can be found on this link.
My JSONP content looks like so:
myRun (
{
"Status": "SUCCESS",
"Name": "Apple Inc",
"Symbol": "AAPL",
"LastPrice": 106.82,
"Open": 106.62
}
)
The code I am using below does not work. And I am not sure how to reorganize it to use JSONP.
var selfish = this;
$.getJSON('http://dev.markitondemand.com/MODApis/Api/v2/Quote/jsonp?symbol=AAPL&callback=myRun', function(data){
console.log(selfish.data.Symbol);
});
$.ajax({
url: "url",
dataType: 'JSONP',
jsonpCallback: 'callback',
type: 'GET',
success: function (data) {
if (data.error) {
console.log ("data error:", data.error.errorMessage);
}
},
error: function (data) {
console.log ("ajax connection error:");
}
});

Create datatable in js via json data in a variable?

now I encounter a problem. I want to use ajax to show a datatable via using data coming from sql server database. Current state is I have used ajax to call a Handler.ashx to connect sql server and convert the data to json (using newtonsoft.json). In ajax, all json data has been recevied from Handler.ashx and stored in a variable "msg" which could be successfully showed on page. I want to put this "msg" into a datatable but failed all the time. I tried almost all methods online to set the datatable but still give different errors. I want to create a datatable in js and fill in my json data. But the result is either null or no data available in table.
Here is the codes and json data looks like.
js:
$(document).ready(function () {
$("#eventsButton").click(function () {
$.ajax({
type: "POST",
url: "../Handler.ashx",
//contentType: "application/json",
data: { postcode: $("#eventsPostcodeTextbox").val() },
cache: false,
success: function (msg) {
//for (var i in msg) {
// $("#eventGrid").append(msg[i]);
//}
//var jsonStr = JSON.stringify(msg);
document.getElementById("result").innerHTML = msg;
$('#eventtable').dataTable({
//"paging": false,
//"searching": false,
//"retrieve": true,
//"bProcessing": true,
//"data": msg.data,
//"datatype": "JSON",
//"ajax": "HandlerAll.ashx",
//"aaData": JSON.parse(msg),
//"ajax":
//"dataSrc":virtualTable
//"aoColumns": [
// { "mData": "ID" },
// { "mData": "FESTIVAL" },
// { "mData": "SUBURB" },
// { "mData": "POSTCODE" },
// { "mData": "WEBSITE" },
// { "mData": "DESCRIPTION" }
// ]
});
},
error: function (data) {
alert("Server error.");
}
})
});
});
json data (the size depends on the search condition, the table columns should have "ID","Festival" and so on, but no "virtualTable"):
{ "virtualTable": [ { "ID": "1", "FESTIVAL": "Antipodes Festival", "SUBURB": "Lonsdale Street, Melbourne", "POSTCODE": "3000", "WEBSITE": "http://www.antipodesfestival.com.au/", "DESCRIPTION": "The greek precinct in melbourne cbd will transform into a huge, free street festival with the hosting of the antipodes lonsdale street festival which will hold sway from 14 february 2015 to 15 february 2015." }, { "ID": "5", "FESTIVAL": "Boite Singers Festival", "SUBURB": "Victoria", "POSTCODE": "3000", "WEBSITE": "http://boite.com.au/index.php", "DESCRIPTION": "The boite singers festival brings you four days of vocal inspiration and sheer fun on the second weekend of january each year." } ] }
Since you get a JSON as reponse, I would try to convert it to JSON object, take the virtualTable part that it is a set of records in JSON and convert it to an array to add it to my table.
$(document).ready(function () {
$("#eventsButton").click(function () {
$.ajax({
type: "POST",
url: "../Handler.ashx",
// dataType: "json",
data: { postcode: $("#eventsPostcodeTextbox").val() },
success: function (msg) {
var jdata = $.parseJSON(msg);
jdata = jdata.virtualTable;
if (jdata.length != 0) {
var array_data = [];
var temp_array = [];
$(jdata).each(function(key, value) {
temp_array = [];
temp_array = [value.ID,
value.FESTIVAL,
value.SUBURB,
value.POSTCODE,
value.WEBSITE,
value.DESCRIPTION
];
array_data[array_data.length] = temp_array;
});
$('#eventtable').dataTable().fnAddData(array_data);
$('#eventtable').dataTable().fnDraw();
},
error: function (data) {
alert("Server error");
}
SOLUTION
Use the code below to initialize the table:
$('#eventtable').dataTable({
data: msg.virtualTable,
columns: [
{ data: "ID" },
{ data: "FESTIVAL" },
{ data: "SUBURB" },
{ data: "POSTCODE" },
{ data: "WEBSITE" },
{ data: "DESCRIPTION" }
]
});
DEMO
See this jsFiddle for code and demonstration.

Categories

Resources