The JSON Response I'm getting,
{
"user_data": {
"id": 22,
"first_name": xxx,
"last_name": xxx,
"phone_number": "123456789",
},
"question_with_answers" : [
{
"id": 1,
"question_name": "Features of our project that you like (select one
or more):",
"answers": [
{
"id": 19,
"question_id": 1,
"customer_id": 22,
"option": "Location",
},
{
"id": 20,
"question_id": 1,
"customer_id": 22,
"option": "Architecture",
},
]
},
{
"id": 2,
"question_name": "Features of our project that you DID NOT like
(select one or more):",
"answers": [
{
"id": 22,
"question_id": 2,
"customer_id": 22,
"option": "Location",
},
]
},
{
"id": 3,
"question_name": "How soon are you looking to buy a new home?",
"answers": [
{
"id": 24,
"question_id": 3,
"customer_id": 22,
"option": "Immediately",
}
]
}
]
}
So that is how JSON response looks like, now I need to display data using jquery
My js code
function openModal(Id){
var CustomerId = Id;
$.ajax({
type : 'get',
url: 'customer-details',
data: {
'CustomerId':CustomerId
},
success: function(data)
{
//what I have to do here
}
})
}
The output I want is,
first_name : xxx
last_name : xxx
phone_number : 123456789
1.Features of our project that you like (select one or more):
ans: Location, Architecture
2.Features of our project that you DID NOT like (select one or more)
ans: Location
3.How soon are you looking to buy a new home?
ans: Immediately
Thats how my output should look like from above json response,Is it possible to get above output using that Json response I got
There are two variable that I have passed from backend like user_data and question_with_answers
In success handler first of all make your json into a array using
var obj = JSON.parse(data);
Now in data you have array of your response and you can use this like
obj.first_name
obj.last_name
Note:- may be you have issue in JSON.parse so use first
var data = json.stringify(data)
after that use Json.parse function and use above data variable
this data
You have to set the dataType in the $.ajax call, set it to dataType:"json"...
After that, you got on the data variable in the success the json object and you can access it like data.user_data or data.id or data.first_name.
If you dont define the json as dataType, it will not work properly.
Addition
If you want to display the content of "question_with_answer" you have to iterate trough it, like ....
for (i in data.question_with_answer) { alert(data.qestion_with_answer[i]); }
Related
I'm a beginner and would like to know how I can get a specific object from an array
I have an Array that looks like this:
data {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
},
To get the data from above I would do something like this:
return this.data.orderid
But how can I go deeper and get the status in userinfo?
return this.data.orderid.userinfo.status
doesn't work... anyone have any ideas?
A few points:
data is not an array, is an Object (see the curly braces, arrays have squared brackets). To be really precise, your syntax is invalid, but I assume you wanted to type data = { ... }, as opposed to data { ... }
Your syntax is almost correct, the only mistake you are making is that userinfo is an array, and arrays have numeric indexes (I.e. array[0], array[1]). What you are looking for is this.data.orderid.userinfo[0].status
Use data.userinfo[0].status to get the value (in your case this.data.userinfo[0].status)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
console.log(data.userinfo[0].status);
User Info is an array, so you would need to access it using indexer like so:
return this.data.userinfo[0].status
MDN on arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
You need to iterate over data.userinfo (it's an array)
var data = {
"orderid": 5,
"orderdate": "testurl.com",
"username": "chris",
"email": "",
"userinfo": [
{
"status": "processing",
"duedate": "" ,
}
]
};
data.userinfo.forEach(function(element) {
console.log(element.status);
});
I'm running a node.js server that sends queries to an elasticsearch instance. Here is an example of the JSON returned by the query:
{
"took": 2,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 9290,
"max_score": 0,
"hits": []
},
"suggest": {
"postSuggest": [
{
"text": "a",
"offset": 0,
"length": 1,
"options": [
{
"text": "Academic Librarian",
"score": 2
},
{
"text": "Able Seamen",
"score": 1
},
{
"text": "Academic Dean",
"score": 1
},
{
"text": "Academic Deans-Registrar",
"score": 1
},
{
"text": "Accessory Designer",
"score": 1
}
]
}
]
}
}
I need to create an array containing each job title as a string. I've run into this weird behavior that I can't figure out. Whenever I try to pull values out of the JSON, I can't go below options or everything comes back as undefined.
For example:
arr.push(results.suggest.postSuggest) will push just what you'd expect: all the stuff inside postSuggest.
arr.push(results.suggest.postSuggest.options) will come up as undefined even though I can see it when I run it without .options. This is also true for anything below .options.
I think it may be because .options is some sort of built-in function that acts on variables, so instead of seeing options as JSON and is instead trying to run a function on results.suggest.postSuggest
arr.push(results.suggest.postSuggest.options)
postSuggest is an array of object.options inside postSuggest is also array of object. So first you need to get postSuggest by postSuggest[0] and then
postSuggest[0].options to get array of options
This below snippet can be usefule
var myObj = {..}
// used jquery just to demonstrate postSuggest is an Array
console.log($.isArray(myObj.suggest.postSuggest)) //return true
var getPostSuggest =myObj.suggest.postSuggest //Array of object
var getOptions = getPostSuggest[0].options; // 0 since it contain only one element
console.log(getOptions.length) ; // 5 , contain 5 objects
getOptions.forEach(function(item){
document.write("<pre>Score is "+ item.score + " Text</pre>")
})
Jsfiddle
I'm having some problems when trying to retrieve values from a JSON response sent via the $.post() method in jQuery. Here is the script:
var clickedName = $('#customerId').val();
$.post("/customer-search", { name: clickedName }).done( function(response) {
var results = $.parseJSON(response);
console.log(results);
$('#account-name').html(results.firstname + ' ' + results.lastname);
$('#email').html(results.email);
$('#telephone').html(results.telephone);
if (results.fax) {
$('#fax').html(results.fax);
} else {
$('#fax').html('n/a');
}
$('#personal').fadeIn();
return false;
});
Just to explain, I'm using twitter typeahead in a Symfony2 project, and basically this script will fire when a name is clicked (selected) from the list after typing. The customer-search URL runs a search of the database as follows:
$q = $request->request->get('name');
$em = $this->getDoctrine()->getManager();
$customer = $em->getRepository('AppBundle:Oc73Customer')->findLikeName($q);
$addresses = $em->getRepository('AppBundle:Oc73Address')->findByCustomerId($customer[0]['customerId']);
$results = array();
$results['customer'] = $customer;
$results['addresses'] = $addresses;
return new Response(json_encode($results));
Which will successfully return a Json encoded response, and the value of 'response' which is printed in the console (as per the jquery above) is:
{
"customer": [{
"firstname": "Mike",
"lastname": "Emerson",
"email": "xxxx#xxxx.co.uk",
"telephone": "01234 5678910",
"fax": null,
"password": "8e1f951c310af4c20e2cd6b68dee506ac685d7ae",
"salt": "e2b9e6ced",
"cart": null,
"wishlist": null,
"newsletter": 0,
"addressId": 84,
"customerGroupId": 1,
"ip": null,
"status": 1,
"approved": 1,
"token": null,
"dateAdded": {
"date": "2016-02-16 12:59:28.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"availCredit": null,
"customerId": 75
}],
"addresses": [{}]
}
I am trying to retrieve the customer details by using the method I always use, so to get the firstname, I use results.firstname where results is a parsed JSON string, as written in my jQuery response.
However, all I get from results.firstname is undefined, even when it clearly is defined. So, basically, I'm wondering what I am doing wrong?
Hope someone can shed some light on my problem.
The properties you're trying to access are objects in the customer array, not on the parent object itself. Assuming that the response only ever contains one customer object then you can use result.customer[0], like this:
$.post("/customer-search", { name: clickedName }).done(function(response) {
var results = $.parseJSON(response);
var customer = response.customer[0];
$('#account-name').html(customer.firstname + ' ' + customer.lastname);
$('#email').html(customer.email);
$('#telephone').html(customer.telephone);
$('#fax').html(customer.fax ? customer.fax : 'n/a');
$('#personal').fadeIn();
});
If it's possible that multiple customer objects will be returned in the array the you would need to amend your code to loop through those objects and build the HTML to display them all - without using id attributes.
I was able to access it like "results.customer[0].firstname"
var cus =
{
"customer": [{
"firstname": "Mike",
"lastname": "Emerson",
"email": "xxxx#xxxx.co.uk",
"telephone": "01234 5678910",
"fax": null,
"password": "8e1f951c310af4c20e2cd6b68dee506ac685d7ae",
"salt": "e2b9e6ced",
"cart": null,
"wishlist": null,
"newsletter": 0,
"addressId": 84,
"customerGroupId": 1,
"ip": null,
"status": 1,
"approved": 1,
"token": null,
"dateAdded": {
"date": "2016-02-16 12:59:28.000000",
"timezone_type": 3,
"timezone": "Europe/Berlin"
},
"availCredit": null,
"customerId": 75
}],
"addresses": [{}]
}
alert(cus.customer[0].firstname);
I want to append following object array with existing one in angulajs for implementing load more feature.
ie,appending AJAX response with existing one each time.
I have one variable, $scope.actions which contains following JSON data,
{
"total": 13,
"per_page": 2,
"current_page": 1,
"last_page": 7,
"next_page_url": "http://invoice.local/activities/?page=2",
"prev_page_url": null,
"from": 1,
"to": 2,
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I want to append following JSON response each time this variable.
{
"data": [
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
},
{
"id": 2108,
"action_type_id": 202,
"user_id": 1
}
]
}
I have tried with $scope.actions.data.concat(data.data);
but it is not working and getting following error message
$scope.actions.data.concat is not a function
You can use angular.extend(dest, src1, src2,...);
In your case it would be :
angular.extend($scope.actions.data, data);
See documentation here :
https://docs.angularjs.org/api/ng/function/angular.extend
Otherwise, if you only get new values from the server, you can do the following
for (var i=0; i<data.length; i++){
$scope.actions.data.push(data[i]);
}
This works for me :
$scope.array1 = $scope.array1.concat(array2)
In your case it would be :
$scope.actions.data = $scope.actions.data.concat(data)
$scope.actions.data.concat is not a function
same problem with me but i solve the problem by
$scope.actions.data = [].concat($scope.actions.data , data)
Simple
var a=[{a:4}], b=[{b:5}]
angular.merge(a,b) // [{a:4, b:5}]
Tested on angular 1.4.1
I'm using REST adapter, when I call App.Message.find() Ember.js makes call to the /messages to retrieve all messages and expect to see JSON structure like this:
{
"messages": [] // array contains objects
}
However API I have to work with response always with:
{
"data": [] // array contains objects
}
I only found the way1 to change namespace or URL for the API. How to tell REST adapter to look for data instead of messages property?
If this is not possible how to solve this problem? CTO said we can adapt API to use with REST adapter as we want, but from some reason we can't change this data property which will be on each response.
Assuming you are ok with writing your own adapter to deal with the difference, in the success callback you can simply modify the incoming name from "data" to your specific entity -in the case above "messages"
I do something like this to give you and idea of what if possible in a custom adapter
In the link below I highlighted the return line from my findMany
The json coming back from my REST api looks like
[
{
"id": 1,
"score": 2,
"feedback": "abc",
"session": 1
},
{
"id": 2,
"score": 4,
"feedback": "def",
"session": 1
}
]
I need to transform this before ember-data gets it to look like this
{
"sessions": [
{
"id": 1,
"score": 2,
"feedback": "abc",
"session": 1
},
{
"id": 2,
"score": 4,
"feedback": "def",
"session": 1
}
]
}
https://github.com/toranb/ember-data-django-rest-adapter/blob/master/packages/ember-data-django-rest-adapter/lib/adapter.js#L56-57
findMany: function(store, type, ids, parent) {
var json = {}
, adapter = this
, root = this.rootForType(type)
, plural = this.pluralize(root)
, ids = this.serializeIds(ids)
, url = this.buildFindManyUrlWithParent(store, type, ids, parent);
return this.ajax(url, "GET", {
data: {ids: ids}
}).then(function(pre_json) {
json[plural] = pre_json; //change the JSON before ember-data gets it
adapter.didFindMany(store, type, json);
}).then(null, rejectionHandler);
},