I have a data variable holding an object like this:
{
"details": {
"id": 10,
"name": John Doe,
"hobbies": [{
"id": 1,
"name": "Football"
},
{
"id": 2,
"name": "Badminton"
},
{
"id": 3,
"name": "Running"
}
],
"dob": 1989-12-31
}
}
I retrieve it using this AJAX request:
$.ajax({
type: 'POST',
url: "{{ route('askdata') }}",
dataType: 'json',
data: { 'id': $('#member_id').val(), },
success: function(data) {
$('#id').val(data.details.id);
$('#name').val(data.details.name);
$('#dob').val(data.details.dob);
$('#hobbies').val(JSON.stringify(data.details.hobbies, ['name']));
}
});
I get a value in the hobbies input like this:
[{"name":"Football"},{"name":"Badminton"},{"name":"Running"}]
How can I change this to get the values like Football, Badminton, Running?
Your current logic is building a JSON string from the hobbies array. To get the output you want you can use map() to build an array of the hobby names which you can then join() together to form a single string:
let data = {"details":{"id": 10,"name": 'John Doe',"hobbies": [{"id": 1,"name": "Football"},{"id": 2,"name": "Badminton"},{"id": 3,"name": "Running"}],"dob": '1989-12-31'}}
$('#hobbies').val(data.details.hobbies.map(o => o.name).join(', '));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="hobbies" size="25" />
Also note that your data object is missing some quotes around the name and dob properties, but I assume that was just a typo in the question otherwise you'd get no output at all.
The best solution is :
$.ajax({
type: 'POST',
url: "{{ route('askdata') }}",
dataType: 'json',
data: { 'id': $('#member_id').val(), },
success: function(data) {
const { details: {id, name, dob, hobbies} } = data
$('#id').val(id);
$('#name').val(name);
$('#dob').val(dob);
$('#hobbies').val(JSON.stringify(hobbies.map(hobby => {
return {name: hobby.name}
})));
}
});
Related
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>
I want to bind json data returned by API to dropdownlist.
but unable to fetch value id and name.
Json Format :
{
"categories": [
{
"categories": {
"id": 1,
"name": "CatOne"
}
},
{
"categories": {
"id": 2,
"name": "CatTwo"
}
}
]
}
I am returning JsonResult, using
return Json(responseData, JsonRequestBehavior.AllowGet);
and in Jquery call ,I am using
$.ajax({
type: "POST",
url: "/Home/City",
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
success: function (jsonObj) {
var listItems = "";
//here I want to get id and name
});
}
});
You can populate dropdown from your json like following.
var json = {
"categories": [
{ "categories": { "id": 1, "name": "CatOne" } },
{ "categories": { "id": 2, "name": "CatTwo" } }
]
}
$.each(json.categories, function () {
$('select').append('<option value="' + this.categories.id + '">' + this.categories.name + '</option>')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>
You can just stick a break point (or debugger; statement) inside your success callback. Then you can inspect your jsonObj and it'll tell you exactly what you need to know.
In this case, you should be able to iterate on jsonObj.categories, and your id and name properties will be accessible via jsonObject.categories[i].categories.id and jsonObject.categories[i].categories.name
So your success method will look something like:
for(var i = 0; i < jsonObj.categories.length; i++) {
var category = jsonObj.categories[i].categories;
var id = category.id;
var name = category.name;
}
I would also suggest formatting your json differently, as other answers have suggested.
In my application, I need to make POST requests with this information:
"data": [
{
"type": "Search",
"thing": "{"Table":"Movie","Field":"Title","Type":"String","Value": "INPUT VALUE GOES HERE"}"
},
{
"type": "Search",
"thing": "{"Table":"Movie","Field":"Director","Type":"String","Value": "INPUT VALUE GOES HERE"}"
},
{
"type": "Search",
"thing": "{"Table":"Movie","Field":"Year","Type":"String","Value": "INPUT VALUE GOES HERE"}"
}
]
I have directives that are simply input elements that will get the data to be placed in the "INPUT VALUE GOES HERE" spots.
My question is, can I pre-pend all of this information into the ng-model of my directives so that when I submit my POST request, I can do something like this:
function submitRequest(input){
var dataToSend = [ input.movieTitle, input.movieDirector, input.movieYear];
return $http({
method: 'POST',
data: dataToSend
})
}
The input is a $scope variable that holds the form data collected by all three different directives
I am just unsure how to go about building long query strings like these.
You can set dataToSend to be that data array and just have the values be the appropriate input values. See the code below:
function submitRequest(input){
var dataToSend = [
{
"type": "Search",
"thing": "{"Table":"Movie","Field":"Title","Type":"String","Value": input.movieTitle}"
},
{
"type": "Search",
"thing": "{"Table":"Movie","Field":"Director","Type":"String","Value": input.movieDirector}"
},
{
"type": "Search",
"thing": "{"Table":"Movie","Field":"Year","Type":"String","Value": input.movieYear}"
}
];
return $http({
method: 'POST',
data: dataToSend
})
}
So I ended up doing what rkho suggested and did this:
var query = {
requestId: "xxxx",
method: "search",
include: "title, director, year"
}
function submitRequest(data) {
query.data = [];
for(var i = 0; i < data.length; i++) {
var queryData = {
data: {
table: data[i].table || "default",
field: data[i].field || "default",
type: data[i].type || "default",
value: data[i].value
}
}
queryData["data"] = angular.toJson(queryData["data"]);
query.data.push(queryData);
}
return $http({
method: 'POST',
url: 'URL GOES HERE',
data: query
})
}
This way, it's a little more dynamic.
Hello I'm trying to pull my characters title from the Warcraft Armory but I don't get any returned results. My code is as follows with my character name being replaced with my actual character name .
HTML
<li>Title Prefix: <span id="title">Test</span>
Javascript
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
});
}
);
function GoGet(data) {
$("#title").html(data.titles.name)
;}
The api documentation shows the json items for "titles" as follows:
{
"achievementPoints": 675,
"battlegroup": "Test Battlegroup",
"calcClass": "f",
"class": 10,
"gender": 1,
"lastModified": 1348187981118,
"level": 90,
"name": "Peratryn",
"race": 25,
"realm": "Test Realm",
"thumbnail": "test-realm/1/1-avatar.jpg",
"titles": [
{
"id": 285,
"name": "%s, Savior of Azeroth",
"selected": true
}
]
}
Where am I going wrong?
Not being a WOW player myself, I'll hazard one guess:
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
success: UpdateTitle
});
}
);
function UpdateTitle(response) {
if (response.titles) {
for (var i = 0; i < response.titles.length; i++) {
if (response.titles[i].selected === true) {
$("#title").html(response.titles[i].name);
break;
}
}
}
}
What this is doing is calling UpdateTitle after a successful XHR response from your provided URL. This function will loop through each title and update your #title element with the FIRST selected: true title found in the json response.
I've an object like
{
"Id": 1,
"Value": 10,
"UId" : "ab400"
}
How can I calculate the length of this so that I'm able to send it in ajax request.
$.ajax({
url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings',
type:"POST",
data: data,
headers: {
"Content-Type":"application/atom+xml",
"Content-Length": data.length,
I tried using stringfying the JSON but the length comes incorrect
Tried : JSON.stringify(data).length
you should use JSON.stringify() to get the complete string then apply length attribute to get length.
var data = {
"Id": 1,
"Value": 10,
"UId" : "ab400"
}
var Length = JSON.stringify(data).length;
console.log(Length);//33
console.log(data.length);//undefined, because here data is object not string.
You are calculating the length correctly, so possibly a syntax error before the ajax request.
var data = {
"Id": 1,
"Value": 10,
"UId" : "ab400"
}
var dataLength = JSON.stringify(data).length;
$.ajax({
url: 'http://gdata.youtube.com/feeds/api/videos/keDZXXDxK1c/ratings',
type:"POST",
data: data,
headers: {
"Content-Type":"application/json; charset=utf-8",
"Content-Length": dataLength
},
success: function(data){
console.log(data);
},
error: function(data) {
console.log(data);
}
});