Iterate through json object array in jQuery - javascript

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>

Related

How to parse JSON values and populate to combobox using EXTJS 4.2.1?

The method:
Ext.Ajax.request({
url: 'url',
method: 'GET',
timeout: 60000,
params: {
"perviceTypeId": my.rec.data.prepeId
},
success: function(response) {
var jsonResp = response.responseText;
console.log("ajax data responseText::" + jsonResp);
//how to parse value and display and populate to deageType combobox
var combo = Ext.getCmp('deageType');
}
});
The response is JSON:
{
"message": null,
"data": [
{
"value": "ESS",
"display": "ESS"
},
{
"value": "ANS",
"display": "ANS"
}
],
"errorCode": -1,
"totalCount": 1,
"messages": null,
"resultDate": 1615282701392,
"success": true
}
You can do that:
var combo = Ext.getCmp('myCombo');
combo.store = Ext.create('Ext.data.Store', {
fields: ['value', 'display'],
data: responseJSON.data
});
Here is functional fiddle with that example: https://fiddle.sencha.com/#view/editor&fiddle/3cb0
You should decode the response (using Ext.JSON.decode) and bind the store (using bindStore) to combo:
Example:
Ext.Ajax.request({
url: 'url',
method: 'GET',
timeout: 60000,
params: {
"perviceTypeId": my.rec.data.prepeId
},
success: function(response) {
var jsonResp = Ext.JSON.decode(response.responseText);
var combo = Ext.getCmp('deageType');
combo.bindStore(Ext.create('Ext.data.Store', {
fields: ['display', 'value'],
data: jsonResp['data']
}));
}
});

Change format of value in input from AJAX request

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

Shopify Ajax API is not accepting properties

I am trying to pass three products through the shopify ajax api. It sends over the variant id and quantity but not the properties. the code is below. if I add request.properties to the Shopify.addItem function it stops after one item and gives me a pop saying that one item has been added to the cart. It does not add the other two items nor does it redirect. If I remove request.properties from the Shopify.addItem function it adds all three items to the cart but with no properties.
FINAL CODE Revised from #miglio code
var FreeTrial={
data:[],
ini:0,
total:0,
addItem:function(qty,id,properties,callback) {
var params = {quantity:qty,id:id};
if(properties != false){
params.properties = properties;
}
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
async:false,
data: params,
success: function(){
if(typeof callback === 'function'){
callback();
}
},
error: function(){}
});
},
recursive:function(){
FreeTrial.addItem(FreeTrial.data[FreeTrial.ini].qty,FreeTrial.data[FreeTrial.ini].id,FreeTrial.data[FreeTrial.ini].properties,function(){
//console.log(FreeTrial.data[FreeTrial.ini]);
FreeTrial.ini += 1;
if(FreeTrial.ini < FreeTrial.total){
FreeTrial.recursive();
}else{
//return false;
document.location.href = '/cart';
}
});
},
begin:function(){
/* SET YOUR ARRAY QTY's' ID's*/
FreeTrial.data = [
{
"qty": '1',
"id": 'VARIANT_ID_GOES_HERE',
"properties": false
},
{
"qty": '1',
"id": 'VARIANT_ID_GOES_HERE',
"properties": false
},
{
"qty": '1',
"id": 'VARIANT_ID_GOES_HERE',
"properties": false
},
{
"qty": '1',
"id": 'VARIANT_ID_GOES_HERE',
"properties": false
},
{
"qty": '1',
"id": 'VARIANT_ID_GOES_HERE',
"properties": {
"recurring_price": "200.00",
"shipping_interval_frequency": "30",
"shipping_interval_unit_type": "days",
"subscription_id": "12599"
}
}
];
FreeTrial.total = FreeTrial.data.length;
FreeTrial.recursive();
}
}
FreeTrial.begin();
To add properties I use this function and work fine for me.
addItem=function(qty,id,properties,callback) {
var params = {quantity:qty,id:id};
if(properties != false){
params.properties = properties;
}
$.ajax({
type: 'POST',
url: '/cart/add.js',
dataType: 'json',
data: params,
success: function(){
if(typeof callback === 'function'){
callback();
}
},
error: function(){}
});
}
//Example :
var qty = 1;
var id = 123456;//variant_id
var properties: {
"recurring_price": "12",
"shipping_interval_frequency": "34",
"shipping_interval_unit_type": "56",
"subscription_id": "78"
}
//
addItem(qty,id,properties,function(){
console.log('done');
});
Well, I did this code for multiple items and a save in a gist:
multiple add to cart
Any POST to the endpoint url: '/cart/add.js', can include properties. If the properties are setup correctly, it works like a charm. You can assign as many properties to a variant as you want. Has been working for what, 5 years now? This function has been working for that long at least... no trouble.
addItemWithProperties: function(variant_id, quantity, properties, callback) {
var quantity = quantity || 1;
if(properties) {
var data = properties.join("&")+"&quantity="+quantity+"&id="+variant_id;
} else {
var data = "quantity="+quantity+"&id="+variant_id;
}
var params = {
type: "POST",
url: "/cart/add.js",
data: data,
dataType: "json",
success: function(line_item) {
if((typeof callback) === "function") {
callback(line_item)
} else {
Shopify.onItemAdded(line_item)
}
},
error: function(XMLHttpRequest, textStatus) {
Shopify.api.onError(XMLHttpRequest, textStatus)
}
};
$.ajax(params)
},
edit. I guess you could do the call manually
add to cart
Considering the Shopify.addItem() function is, straight off their API I'm not sure you can simply add a parameter like that.
My guess is that the extra parameter has the effect that the function doesn't run.

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

How to calculate length of object being sent in POST

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

Categories

Resources