Currently I'm trying to call a function with a data response from an ajax call, and I'm getting that my constant stores is not iterable. My AJAX call looks like this
jQuery.ajax({
type: 'GET',
url: "<?php echo JURI::base() . "index.php?option=com_ajax&module=hunter_maps_dev&method=getStoresByZip&zip="?>" +zip+ "&format=json",
datatype : "application/json",
success:function(data){
console.log('success');
const stores = data;
console.log(stores);
buildLocationList(stores);
},
...
function buildLocationList({ features }) {
for (const { properties } of features) {
}
}
and I'm logging it to the console.
I'm getting this for the data in the console: data: "{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.9981929\",\"39.7164275\"]},\"properties\":{\"store
and this is the mock I was previously using:
const stores = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-77.034084142948, 38.909671288923]
},
'properties': {
'storeImage' : 'https://via.placeholder.com/150',
'storeName' : 'Test Store',
'phoneFormatted': '(202) 234-7777',
'phone': '2022347336',
'address': '1471 P St NW',
'city': 'Washington DC',
'country': 'United States',
'crossStreet': 'at 15th St NW',
'postalCode': '20005',
'state': 'D.C.'
}
},
]
};
What is missing for me to get this to match the mock format so that it's iterable?
UPDATE: Full response currently
{"success":true,"message":null,"messages":null,"data":"{\"type\":\"FeatureCollection\",\"features\":[{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.9981929\",\"39.7164275\"]},\"properties\":{\"storeImage\":\"1542820219karmalogo2-Copy.png\",\"storeName\":\"Karmaceuticals\",\"phoneFormatted\":\"303-765-2762\",\"address\":\"4 S Santa Fe Drive\",\"city\":\"Denver\",\"country\":\"USA\",\"postalCode\":\"80223\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.8526653\",\"39.7861717\"]},\"properties\":{\"storeImage\":\"1438052652medicineman_logo_web.jpg\",\"storeName\":\"Medicine Man - Denver\",\"phoneFormatted\":\"303-373-0752\",\"address\":\"4750 Nome St.\",\"city\":\"Denver\",\"country\":\"Denver\",\"postalCode\":\"80239\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-105.0135439\",\"39.7206576\"]},\"properties\":{\"storeImage\":\"1455044497CannaBoticaOrange.png\",\"storeName\":\"CannaBotica \",\"phoneFormatted\":\"303-777-1550\",\"address\":\"219 Vallejo st.\",\"city\":\"Denver\",\"country\":\"United States\",\"postalCode\":\"80223\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-104.8664385\",\"39.6817321\"]},\"properties\":{\"storeImage\":\"1458987858medicine-man-aurora.jpg\",\"storeName\":\"Medicine Man - Aurora\",\"phoneFormatted\":\"303-923-3825\",\"address\":\"1901 S Havana Street\",\"city\":\"Aurora\",\"country\":\"\",\"postalCode\":\"80014\",\"state\":\"Colorado\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-116.905029\",\"33.0433045\"]},\"properties\":{\"storeImage\":\"1479714765showgrow-logo.jpg\",\"storeName\":\"Showgrow - Ramona\",\"phoneFormatted\":\"760-687-9700\",\"address\":\"736 Montecito Way\",\"city\":\"Ramona\",\"country\":\"United States\",\"postalCode\":\"92065\",\"state\":\"California\"}},{\"type\":\"Feature\",\"geometry\":{\"type\":\"Point\",\"coordinates\":[\"-117.8467455\",\"33.7201192\"]},\"properties\":{\"storeImage\":\"1479715612showgrow-logo.jpg\",\"storeName\":\"Showgrow -Santa Ana\",\"phoneFormatted\":\"949-565-4769\",\"address\":\"1625 E St Gertrude Pl\",\"city\":\"Santa Ana\",\"country\":\"United States\",\"postalCode\":\"92705\",\"state\":\"California\"}}]}"}
You need to parse the JSON string to convert it to an object:
buildLocationList(JSON.parse(stores));
Related
I'm trying to get familiar with using php and javascript together in a joomla template, but I've moved it to a local box (no joomla, just testing the files on their own) to try and make more sense of it but I'm still stuck
I have a php function which is making a select on the database and returning the result, which is then passed to the default html file where I have my Javascript. So I'm getting the data passed to the page.
My issue is this: I have a mock JSON object in my Javascript that is structured exactly how I need/want it but I'm unsure of how I can convert my datebase result from SQL into this exact structure and replace the mock object.
Here is my query:
SELECT name, phone, address, city, state, zip, country, url, logo, lat, lng
from address_info
where published = 1
and when I dump the result on the page, this is the structure:
object(stdClass)#589 (11) {
["name"]=>
string(14) "TEST STORE"
["phone"]=>
string(12) "555-555-5555"
["address"]=>
string(18) "123 test ave"
["city"]=>
string(6) "Denver"
["state"]=>
string(8) "Colorado"
["zip"]=>
string(5) "80223"
["country"]=>
string(3) "USA"
["url"]=>
string(7) "http://test.com"
["logo"]=>
string(29) "logo.png"
["lat"]=>
string(12) "-104.9981929"
["lng"]=>
string(10) "39.7164275"
}
Any help on how to convert this result into the exact JSON structure is greatly appreciated
<script type="text/javascript">
const stores = {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Point',
'coordinates': [-77.034084142948, 38.909671288923]
},
'properties': {
'storeImage' : 'https://via.placeholder.com/150',
'storeName' : 'Test Store',
'phoneFormatted': '(202) 234-7777',
'address': '1471 P St NW',
'city': 'Washington DC',
'country': 'United States',
'postalCode': '20005',
'state': 'D.C.'
}
},
]
};
</script>
You need to manually assign all values to their corresponding place. So in your specific use case, this would look like this:
// I've set your result from MySQL to be stored in $data
// Populate a new array
$return = [
'type' => 'FeatureCollection',
'feature' => [
[
'type' => 'Feature',
'geometry' => [
'type' => 'Point',
'coordinates' => [
$data->lat,
$data->lng
]
],
'properties' => [
'storeImage' => $data->logo, // you need to convert this into an actual URL
'storeName' => $data->name,
'phoneFormatted' => $data->phone, // this needs formatting aswell
'address' => $data->address,
'city' => $data->city,
'country' => $data->country,
'postalCode' => $data->zip,
'state' => $data->state
]
]
]
];
// output the PHP array as JSON
echo json_encode($return);
i have a form on select from dropdown the request goes to the controller and returns the following in
JSON formate
[{id: 2, slug: "manager", name: "Assistant Manager", created_at: "2019-12-10 09:20:45",…}]
0: {id: 2, slug: "manager", name: "Assistant Manager", created_at: "2019-12-10 09:20:45",…}
created_at: "2019-12-10 09:20:45"
id: 2
name: "Assistant Manager"
permissions: [{id: 2, slug: "edit-users", name: "Edit Users", created_at: "2019-12-10 09:21:01",…}]
0: {id: 2, slug: "edit-users", name: "Edit Users", created_at: "2019-12-10 09:21:01",…}
slug: "manager"
updated_at: "2019-12-10 09:20:45"
now i want to iterate from permissions and show name in another drop-down with multiple selection buit i don't know how to iterate from this JSON i tried the following script but doesn't work
$(document).ready(function () {
$("#roles").on('change', function () {
var query = $(this).val();
// alert(query);
if (query != '') {
$.ajax({
url: "{{route('get-roles-ajax-call')}}",
method: "POST",
dataType: 'JSON',
data: {"_token": "{{ csrf_token() }}", query: query},
success: function (data) {
var values = $.parseJSON(data)
$(values).each(function(i,val){
$.each(val,function(key,val)
{
console.log(key + " : " + val);
});
});
}
});
}
return false;
});
});
When setting this line dataType: 'JSON' you are already telling the $.ajax function to return JSON.
Quoted from jQuery documentation of $.ajax
"json": Evaluates the response as JSON and returns a JavaScript object.
So there is no need to parse the data once you've received it. Is is already JSON.
Now loop through every object in the data to search for the permissions property. If the object has the permissions property and the value of that is an array that is not empty then loop over each object in the permissions array and look for the the name property on each permission.
$.each(data, function(i, entry) {
var permissions = entry.hasOwnProperty('permissions');
if (permissions && permissions.length) {
$.each(entry.permissions, function(j, permission) {
console.log(permission.name);
});
}
});
Though I would suggest that you modify the, or create a new, server response so that all this filter work is done server side and you only have to call the server to get the data you need.
I' trying to send some data from the frontend to a Controller in Spring. I am able to recover all the data except for the Integer [] objectIds.
This is my ajax function:
var dataToSend = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend = JSON.stringify({ 'objectIds': dataToSend });
$.ajax({
type:'POST',
url:'/sendData',
data:{'start':start, 'end':end, 'locale':locale, dataToSend},
async:false,
dataType: "json",
success:function(data){}
});
And this is my Controller function:
#PostMapping(path="/sendData")
public #ResponseBody String sendData(HttpServletResponse response,
#RequestParam(required=true, name="start") String start,
#RequestParam(required=true, name="end") String end,
#RequestParam(required=true, name="locale") Locale locale,
#RequestParam(required=false, name="objectIds") Integer[] objectIds) throws DocumentException, IOException {
//some more code
}
any idea why it's not working??
Problem is in the way you are sending JSON
Case 1: How you are sending
var dataToSend = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend = JSON.stringify({ 'objectIds': dataToSend });
var mainJSOn = {
'start': "start",
'end': "end",
'locale': "locale",
dataToSend
}
console.log(JSON.stringify(mainJSOn));
OUTPUT:
{"start":"start","end":"end","locale":"locale","dataToSend":"{\"objectIds\":[{\"objectIds\":111},{\"objectIds\":222}]}"}
Case 2: How you should actually send
var dataToSend1 = [{ objectIds: 111 }, { objectIds: 222 }];
dataToSend1 = JSON.stringify(dataToSend1 );
var mainJSOn1 = {
'start': "start",
'end': "end",
'locale': "locale",
'objectIds': dataToSend1
}
console.log(JSON.stringify(mainJSOn1));
OUTPUT:
{"start":"start","end":"end","locale":"locale","objectIds":"[{\"objectIds\":111},{\"objectIds\":222}]"}
Look at the Output of Both Cases.
Change your code like done in Case 2
Working Fiddle
Your are stringifying the wrong object and burying the key objectIds inside it
Try changing to
var dataToSend = JSON.stringify([{objectIds: 111}, {objectIds: 222}]);
$.ajax({
type: 'POST',
url: '/sendData',
data: {
'start': start,
'end': end,
'locale': locale,
'objectIds': dataToSend
},
// async:false, // NEVER USE THIS!!!!
dataType: "json",
success: function(data) {}
});
I have just started TypeScript and I want to know how to declare an interface for this type of object:
const branch = {
'CN': {
'name': 'CN Name',
'branch': 'Chinoise',
'url': 'CN URL'
},
'DE': {
'name': 'DE Name',
'branch': 'Allemande',
'discord': 'DE Discord',
'url': 'DE URL'
},
'EN': {
'name': 'EN Name',
'branch': 'Anglaise',
'url': 'EN URL'
},
[...]
}
As you can see, I've got this interface:
interface Branch {
name: string,
branch: string,
discord?: string,
url: string
}
Repeated several times in the above code.
So I wanted to know if it was possible to say to TypeScript:"Hey, the Branch object contains this interface which is repeated many times".
Thanks !
You can do it like this:
const branch: {[key: string]: Branch} = ...;
Which means that branch variable is an object whose keys are of type string and values are of type Branch;
Official Docs for index signatures: https://www.typescriptlang.org/docs/handbook/interfaces.html
I am using KendoUI Web and have set up a TreeView with two levels of hierarchy which are loading data from a CRUD service using the transport option of the DataSource:
var Level2 = kendo.data.Node.define({
id: "Level2_Id",
hasChildren: false,
fields: {
"Level2_Id": { type: "number" },
"Name": { type: "string" },
"Level1_Id": { type: "number" }
}
});
var level2DataSource = {
transport: {
read: {
url: "/service/level2",
type: "get",
dataType: "json"
},
create: {
url: "/service/level2",
type: "post",
dataType: "json"
}
},
schema: {
model: Level2
}
};
var Level1 = kendo.data.Node.define({
id: "Level1_Id",
hasChildren: true,
fields: {
"Level1_Id": { type: "number" },
"Name": { type: "string" },
},
children: level2DataSource,
});
var level1DataSource = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "/service/level1",
type: "get",
dataType: "json"
},
create: {
url: "/service/level1",
type: "post",
dataType: "json"
}
},
schema: {
model: Level1
}
});
var myTreeview = $("#treeview").kendoTreeView({
dataSource: leaguesDataSource,
template: kendo.template($("#treeview-template").html())
});
Reading the data works fine on both levels.
Creating new items is done by calling .append() on the TreeView and then .sync() on the level 1 DataSource.
This results in a POST request to my service which returns the new JSON object. The tree view updates just fine.
However, when doing the same thing on level 2, the treeview will remove all items and only show level 2 children of the level 1 item that the new item was appended to.
The GET requests return a JSON array of level 1 or level 2 items like
result of /service/level1
[
{Level1_Id:1,Name:"Item 1"},
{Level1_Id:2,Name:"Item 2"},
{Level1_Id:3,Name:"Item 3"},
]
result of /service/level2
[
{Level2_Id:1,Name:"Item 2.1",Level1_Id:2},
{Level2_Id:2,Name:"Item 2.2",Level1_Id:2}
]
The POST requests return a single object of the same format.
What format do I need to return in my service so the treeview will update correctly on level 2 after appending an item?
Expected result:
- Item 1
- Item 2 (append here)
- Item 2.1
- Item 2.2 (new item)
- Item 3
Actual result after POST request:
- Item 2.1
- Item 2.2 (new item)
your syntax it not right. your must write
schema:{model:{id: "IdLevel", children: "items", hasChildren: "hasChildren"}}
with hierarchical data.
For example you must have your data like this :
[
{ categoryName: "SciFi", items: [
{ movieName: "Inception", rating: 8.8 },
{ movieName: "The Matrix", rating: 8.7 }
] },
{ categoryName: "Drama", hasAssignedMovies: true }]