Reputation: 21
Having issues getting my json response back from an SQL query in javascript
This is my javascript
setNouvelle: function(id, action){
this
.$http
.get('news.api.php?function=getNouvelle&id='+id)
.then(function(response){
if (action == 'modal') {
this.modal.nouvelle = response.data;
} else if(action == 'edit') {
this.nouvelle = response.data;
this.nouvelle.publication =
moment(this.nouvelle.publication).format('YYYY-MM-DD');
}
});
},
On the PHP side I have an postgresql query that uses json_build_object and then I send it with
echo json_encode($nouvelle);
When launching the action setNouvelle, the response.data contains the following :
"{"id" : 1872, "title" : "Test Title", "publication" : "2017-09-05T00:00:00", "summary" : "This is a test summary ", "category" : "admin", "content" : "<h2 style=\"text-align: justify;\">This is the test content ", "relateddisciplines" : [{"id" : 2, "name" : "Men's", "code" : "men"}, {"id" : 3, "name" : "Women's", "code" : "wen"}], "athlete" : [{"id" : 37359, "firstname" : "Reb", "lastname" : "ANDRADE", "federation" : "POR"}, {"id" : 25224, "firstname" : "Paul", "lastname" : "BULA", "federation" : "FRA"}], "events" : [{"id" : 15191, "startevent" : "2017-09-01", "endevent" : "2017-09-03", "title" : "World Cup", "city" : {"name" : "Minsk", "country" : {"code" : "BLR"}}, "status" : "approved", "hasresults" : true, "disciplines" : [{"code" : "men"}, {"code" : "wen"}]}], "keywords" : [{"id" : 40, "value" : "Women's"}, {"id" : 49, "value" : "Men's"}, {"id" : 347, "value" : "World Cup"}, {"id" : 771, "value" : "Minsk"}]}"
However I cannot use individual parts of the returned data, for example, showing the summary with this.nouvelle.summary
If I try JSON.parse(response.data), I get the following error message :
Uncaught (in promise) SyntaxError: Unexpected token o in JSON at position 1
How can I set this up so that I can use individual attributes of the JSON response
Thanks
Edit :
this is my app declaration :
var app = new Vue({
http: { options: { emulateJSON: true, emulateHTTP: true }},
el: '#app',
data: {
nouvelle: {
id : "",
title: "",
summary: "",
content: "",
category: "",
publication: "",
press_release: "",
keywords: [],
athletes: [],
events: [],
relateddisciplines: [],
create_time: ""
},
nouvelles: [],
modal: {
nouvelle: {
id : "",
title: "",
summary: "",
content: "",
category: "",
publication: "",
press_release: "",
keywords: [],
athletes: [],
events: [],
relateddisciplines: [],
create_time: ""
}},
file: {},
addMode: true,
alert: {
cls: "hidden",
message: "",
time: 0
}
Upvotes: 1
Views: 1008
Reputation: 21
Made it work by changing this line :
this.modal.nouvelle = response.data;
to
this.modal.nouvelle = JSON.parse(response.body.nouvelle);
Wasn't parsing the right thing
Upvotes: 1