$.ajax and JSONP.Uncaught SyntaxError: Unexpected token < - javascript

I keep getting an Uncaught SyntaxError: Unexpected token <, and I can not for the life of me , figure out why.
function democracyMap(resp) {
representative.fullName = resp.jurisdictions[5].elected_office[0].name_full;
representative.face = resp.jurisdictions[5].elected_office[0].url_photo;
representative.district = resp.jurisdictions[5].name;
senator1.fullName = resp.jurisdictions[6].elected_office[0].name_full;
senator1.face = resp.jurisdictions[6].elected_office[0].url_photo;
senator2.fullName = resp.jurisdictions[6].elected_office[1].name_full;
senator2.face = resp.jurisdictions[6].elected_office[1].url_photo;
representativeInfo();
senator1Info();
senator2Info();
apiSuccess();
}
function ajaxFail(req, status, err) {
console.log('something went wrong', status, err);
}
function getDemocracyMap(){
$.ajax({
type: "GET",
url: "http://api.democracymap.org/",
data:"location=",
crossDomain: true,
dataType: "jsonp",
success: function(resp) {
democracyMap(resp);
},
error: ajaxFail
});
}
Each representative, as well as sentator 1 and senator are set as global variables as such:
var representative = {
"fullName": "",
"firstName": "",
"lastName": "",
"district": "",
"face": "",
"party": "",
"termStart": "",
"termEnd": "",
"facebookID": "",
"twitter": "",
"youTube": ""
}

Related

How can I able to display the JSON data in an inner array by using vueJS?

My vueJS code is:
<script>
new Vue({
el: '#feed' ,
data: {
data: [],
},
mounted() {
this.$nextTick(function() {
var self = this;
var id = window.location.href.split('=').pop();
console.log(id);
$.ajax({
url: "https://n2s.herokuapp.com/api/post/get/5",
method: "GET",
dataType: "JSON",
success: function (e) {
if (e.status == 1) {
self.data = e.data;
console.log(e.data)
} else {
console.log('Error occurred');
}
}, error: function(){
console.log('Error occurred');
}
});
});
},
})
</script>
This is my html code to display values
<div class="m-single-article" id="feed">
<p>{{details.bussinessName}}</p> //already printed
<p>{{details.pid}}</p> //already printed
<p>{{details.inventory}}</p> //////NOT PRINTING
<p>{{details.sub_category}}</p> ////// NOT PRINTING
</div>
I AM ABLE TO PRINT ALL THE DATA expect INVENTORY AND SUBCATEGORY. please
The url will provide the json data as:
{"status": true, "data": {"pid": 10, "bussinessName": "Ey technology", "services": "1, 3, 4, 2", "inventory": ["specs", "Eye Testing", "Lens", "Doctors"], "workHr": "Monday :9:00AM to 5:00PM,Thuesday :9:00AM to 5:00PM,Wednesday :9:00AM to 5:00PM,Tuesday : 9:00AM to 5:00PM,Friday :9:00AM to 5:00PM,Saturday :9:00AM to 5:00PM,Sunday :9:00AM to 5:00PM", "description": "Good technology company for software", "category": 1, "sub_category": ["Homeo pathy", "Web development"], "lat": 9.5274336, "lon": 76.8224309, "contactName": "simon", "contactEmail": "simon#gmail.com", "contactOfficeAddress": "korno solutions", "contactNumber": "1236547859", "contactOfficeNumber": "858547896", "state": "Canada", "city": "Oranto", "place": "Orania", "pincode": 895621, "referer": 24, "link": 24, "views": 0, "package": 1, "listing_pic": "default", "website": "www.ey.com"}}
By trying this I am not able to display the values of inventory [] and subcategory []. Can anybody please help me to solve my issue.
Also I am getting services as 1,2,3,4. Is there any way to map to the another json data giving name of the services. https://n2s.herokuapp.com/api/post/get_all_services/
You need v-for.
new Vue({
el: '#feed' ,
data: {
details: [],
},
mounted() {
this.$nextTick(function() {
var self = this;
var id = window.location.href.split('=').pop()
console.log(id)
$.ajax({
url: "https://n2s.herokuapp.com/api/post/get/5",
method: "GET",
dataType: "JSON",
success: function (e) {
if (e.status == 1) {
self.details = e.data;
console.log(e.data)
}
else
{
console.log('Error occurred');}
}, error: function(){
console.log('Error occurred');
}
});
})
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="m-single-article" id="feed">
<p>{{details.bussinessName}}</p>
<p>{{details.pid}}</p>
<p v-for="inv in details.inventory">{{inv}}</p>
<p v-for="sub in details.sub_category">{{sub}}</p>
</div>

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

JSON.parse returning error

So this is my JSON.stringify'd return before I try to run JSON.parse
{"id":"2","name":"<small>L</small>(+)-Amethopterin Hydrate","class":"6.1","subclass":"","packing_group":"III","un":"2811","cas":"133073-73-1","poisons":"","hazardous":"Yes","restricted":"No","epa":"","added_by":"0","carcinogen":null},
{"id":"3","name":"(+)-Biotin 4-Nitrophenyl ester","class":"","subclass":"","packing_group":"","un":"","cas":"33755-53-2","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null},
{"id":"4","name":"(+)-Biotin N-hydroxysuccinimide ester","class":"","subclass":"","packing_group":"","un":"","cas":"35013-72-0","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}
When I try to JSON.parse I get Unexpected end of JSON input. And I can't access it as a JSON object because it will say can't define id or something to that extent.
JSON.parse(this.searchService.searchJson(this.php_url));
this.searchService.searchJson(this.php_url) is basically what my JSON string is. Gives error as mentioned above.
Also if I just try to stringify 1 of the 3 elements, it'll give me Unexpected token u in JSON at position 0
Calling function:
searchJson(url: any): any
{
let items: any = [];
let new_data: any = [];
$.getJSON(url ,
function(data)
{
let temp_items: any = {};
console.log(data);
$.each(data, function (key, val)
{
new_data.push(JSON.stringify(val));
});
});
return new_data;
}
You have to wrap it with [] because that is an array of objects:
const data = [{"id":"2","name":"<small>L</small>(+)-Amethopterin Hydrate","class":"6.1","subclass":"","packing_group":"III","un":"2811","cas":"133073-73-1","poisons":"","hazardous":"Yes","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"3","name":"(+)-Biotin 4-Nitrophenyl ester","class":"","subclass":"","packing_group":"","un":"","cas":"33755-53-2","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"4","name":"(+)-Biotin N-hydroxysuccinimide ester","class":"","subclass":"","packing_group":"","un":"","cas":"35013-72-0","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}]
console.log(data); will return [Object, Object, Object]
or if you wanna process as a JSON string you should do this:
const data = '[{"id":"2","name":"<small>L</small>(+)-Amethopterin Hydrate","class":"6.1","subclass":"","packing_group":"III","un":"2811","cas":"133073-73-1","poisons":"","hazardous":"Yes","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"3","name":"(+)-Biotin 4-Nitrophenyl ester","class":"","subclass":"","packing_group":"","un":"","cas":"33755-53-2","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}, {"id":"4","name":"(+)-Biotin N-hydroxysuccinimide ester","class":"","subclass":"","packing_group":"","un":"","cas":"35013-72-0","poisons":"","hazardous":"No","restricted":"No","epa":"","added_by":"0","carcinogen":null}]'
JSON.parse(data) will return too [Object, Object, Object]
Changed the calling function to this:
searchAjax(url: any): any
{
let new_data: any;
return $.ajax({
url: url,
type: 'post',
dataType: "json",
async: false
}).responseText;
}
The most likely cause was that my variable was that my variable was null at the time of being called because of async.
file Nmae: self.json
[
{
"id": "2",
"name": "<small>L</small>(+)-Amethopterin Hydrate",
"class": "6.1",
"subclass": "",
"packing_group": "III",
"un": "2811",
"cas": "133073-73-1",
"poisons": "",
"hazardous": "Yes",
"restricted": "No",
"epa": "",
"added_by": "0",
"carcinogen": null
},
{
"id": "3",
"name": "(+)-Biotin 4-Nitrophenyl ester",
"class": "",
"subclass": "",
"packing_group": "",
"un": "",
"cas": "33755-53-2",
"poisons": "",
"hazardous": "No",
"restricted": "No",
"epa": "",
"added_by": "0",
"carcinogen": null
},
{
"id": "4",
"name": "(+)-Biotin N-hydroxysuccinimide ester",
"class": "",
"subclass": "",
"packing_group": "",
"un": "",
"cas": "35013-72-0",
"poisons": "",
"hazardous": "No",
"restricted": "No",
"epa": "",
"added_by": "0",
"carcinogen": null
}
]
$(document).ready(function($) {
$.ajax({
url: 'self.json',
type: 'GET',
dataType: 'json',
})
.done(function(respose) {
for (var i = 0; i < respose.length; i++) {
resText = respose[i].id+' '+respose[i].name+' '+ respose[i].class+' '+respose[i].subclass;
console.log(resText);
};
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
});
Output:

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

Recreating Ajax POST

I want to recreate Ajax POST which I can peak via Chrome's debugger.
I created post like this:
$.ajax({
method: "POST",
url: url,
contentType: "application/json; charset=UTF-8",
data: { "defaults": "default", "culture": "en-US", "skip": 20, "take": 20, "query": "", "filters": [], "fulltext": [], "sorting": { "field": "ModifiedOn", "asc": false } }
})
.done(function (msg) {
alert("Data Saved: " + msg);
});
I'm getting 500 error. I check and my Request Payload looks like this:
defaults=default&culture=en-US&skip=20&take=20&query=&sorting%5Bfield%5D=ModifiedOn&sorting%5Basc%5D=false
However the source post, which I want to recreate has different Request Payload:
{"defaults":"default","culture":"en-US","skip":20,"take":20,"query":"","filters":[],"fulltext":[],"sorting":{"field":"ModifiedOn","asc":false}}
I think it is causing the error.
How can I modify my request to make Request Payload look like the latter one?
data: { "defaults": "default", "culture": "en-US", "skip": 20, "take": 20, "query": "", "filters": [], "fulltext": [], "sorting": { "field": "ModifiedOn", "asc": false } }
This line is causing the Error. You need to stringify your Data like so:
data: JSON.stringify({ "defaults": "default", "culture": "en-US", "skip": 20, "take": 20, "query": "", "filters": [], "fulltext": [], "sorting": { "field": "ModifiedOn", "asc": false } })
Please read the documentation about jQuery.ajax()-function. You can check all Parameters with their Type.

Categories

Resources