How to use JSONP? - javascript

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:");
}
});

Related

How to make an AJAX call to GraphHopper Matrix API

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);
}
});

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 !!

Using json with jquery Ajax doens't return anything

I wanted to learn how to use JSON with jQuery so I followed a simple video tutorial on it. However, after following all the steps and using the exact same code as in the video, I still don't see anything in the console after a console.log. What am I doing wrong?
Here is the HTML page:
<!DOCTYPE html>
<html>
<head>
<title>Document</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$.ajax({
url: 'articles.json',
dataType: 'json',
type: 'get',
cache: false,
succes: function(data) {
$(data.articles).each(function(index, value) {
console.log("success");
});
}
});
</script>
</body>
</html>
And here is my JSON file (articles.json) from which I am trying to use the data:
{
"articles": [
{
"id": 1,
"name": "Article 1"
},
{
"id": 2,
"name": "Article 2"
},
{
"id": 3,
"name": "Article 3"
}
]
}
Thanks in advance!
Here is correct way to read json data in javascript using jquery
<script>
$.ajax({
url: 'articles.json',
dataType: 'json',
type: 'get',
cache: false,
succes: function(data) {
var jsonData = JSON.parse(data);
$.each(jsonData.articles, function(i, v) {
console.log("id = "+ v.id);
console.log("name = " + v.name);
});
}
});
</script>
Use $.getJSON
example
$.getJSON( "articles.json", function( data ) {
$.each( data.articles, function( key, val ) {
console.log(val);
});
});
http://api.jquery.com/jquery.getjson/

AJAX JQuery | accessing returned object data

I am trying to access data returned in an Ajax call I have made. This is referencing the steam API and is successfully returning the data. I have console logged it to check. Whenever I try and access the data i get and undefined console message.
Below is a snippet of my returned JSON file
{
"playerstats": {
"steamID": "Removed for SO",
"gameName": "ValveTestApp260",
"stats": [
{
"name": "total_kills",
"value": 7642
},
{
"name": "total_deaths",
"value": 7349
},
{
"name": "total_time_played",
"value": 427839
},
{
"name": "total_planted_bombs",
"value": 341
},
Below is the code for my ajax call
$.ajax({
url: this.props.url,
dataType: 'json',
crossDomain: true,
success: function(data) {
console.log("success", typeof data);
console.log(data.playerstats.stats.total_kills);
console.log(data["playerstats"]["stats"]["total_kills"]);
}.bind(this),
error: function(xhr, status, err, data) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
I am successfully entering the success function but it is displaying the following in the console
success object
Inline JSX script:21 undefined
Inline JSX script:22 undefined
the 2 undefined errors are appearing on the console.log line where I have tried accessing the Data the only thing I can think of is that I am accessing them wrong.
Attempts
console.log(data.playerstats.stats.total_kills);
console.log(data["playerstats"]["stats"]["total_kills"]);
total_kills is not a property of stats, nor even a property of every item in stats, but a value of the property "name", you want the value of the property "value" of every item in the stats array:
$.ajax({
url: this.props.url,
dataType: 'json',
crossDomain: true,
success: function(data) {
console.log("success", typeof data);
data.playerstats.stats.forEach(function (stat) {
console.log(stat.value);
});
}.bind(this),
error: function(xhr, status, err, data) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
To get only the item which has "total_kills" as the value of its "name" property, you can use this :
var totalKillsObj = data.playerstats.stats.reduce(function(item) {
return item.name === 'total_kills';
});
var totalKills = totalKillsObj.value;
Demo Fiddle
var data = {
"playerstats": {
"steamID": "Removed for SO",
"gameName": "ValveTestApp260",
"stats": [{
"name": "total_kills",
"value": 7642
}, {
"name": "total_deaths",
"value": 7349
}, {
"name": "total_time_played",
"value": 427839
}, {
"name": "total_planted_bombs",
"value": 341
}]
}
}
alert(data.playerstats.steamID);
data.playerstats.stats.forEach(function (stat) {
alert(stat.name + ":" + stat.value);//property for stats are name and value
});

Array not passing from Javascript to MVC

I'm trying to pass an array from javascript back into my MVC app. There is a console.log(selected) in the javascript and it outputs an array of data:
["<img src="https://owlexpress.kennesaw.edu/stugifs/open.gif">", "MATH 1190/01 - Calculus I", "84528", " 4.000", "Full Term", "40", "34", "6", "0", "0", "0", "Kennesaw Campus", "Classroom - 100%", "Mathematics & StatisticsRoom 108", "8:00 am - 9:10 amLecture", "Aug 17, 2015", "Dec 14, 2015", "Xiaohui Rebecca Shi (P)", ""]
But when the breakpoint in the controller hits I see that selectedClassesArray == null
Javascript:
$('#WatchButton').on('click', function (e) {
var selected = [];
$("tr.selected").each(function () {
$(this).find('td').each(function(){
selected.push($(this).html());
});
});
console.log(selected);
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
// I have tried setting data both ways with the same result:
//data: { selectedClassesArray: selected },
data: [selected],
traditional: true,
success: function (data) { alert("SUCCESS"); }
});
});
ViewModel:
public class SelectedClassesArray
{
public string[] arrayOfClasses { get; set; }
}
Controller ACtion:
//Had to set ValidateInput to false since one of the strings contains < (it errored without this)
[HttpPost, ValidateInput(false)]
public ActionResult watchClasses(IEnumerable<SelectedClassesArray> selectedClassesArray)
{ //Breakpoint here shows that selectedClassesArray is null
foreach (var item in selectedClassesArray)
{
Console.WriteLine(item.ToString());
}
return View();
}
Your action is expecting a List of arrays:
watchClasses(IEnumerable<SelectedClassesArray> selectedClassesArray)
You probably want to get only the array, which is in the view model:
watchClasses(SelectedClassesArray selectedClassesArray)
And what #taxicala said makes sense, try passing only the array, not an array inside another array:
data: { selectedClassesArray: selected }
The posted property name must match the view model parameter's name.
Did you try:
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
// I have tried setting data both ways with the same result:
//data: { selectedClassesArray: selected },
data: selected,
traditional: true,
success: function (data) { alert("SUCCESS"); }
});
Or perhaps the traditional serialization is failing:
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
// I have tried setting data both ways with the same result:
//data: { selectedClassesArray: selected },
data: { selectedClassesArray: selected },
traditional: false,
success: function (data) { alert("SUCCESS"); }
});

Categories

Resources