I'm trying to create a JavaScript object based on a template I received as a test. I use Ajax to get the data from my database but i cant seem to create the object.
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'fetch.php',
dataType: 'JSON',
success: function(response) {
var test = JSON.parse(response);
var products = {};
for (var x = 0; x < test.length; x++) {
products[x] = {
productName: test[x]['name']
};
products[x] = {
category: test[x]['category']
};
products[x] = {
price: test[x]['price']
};
}
}
});
});
I'm trying to create something like this object below
products = {data: [
{
productName: "test_item_1",
category: "category1",
price: "49",
image: "test_image.jpg",
},
{
productName: "test_item_2",
category: "category3",
price: "99",
image: "test_image.jpg",
},
{
productName: "test_item_3",
category: "category3",
price: "29",
image: "test_image.jpg",
},],};
This is the how i fetch the data from my database
while($row = mysqli_fetch_assoc($run)){$datas[] = $row;}echo json_encode($datas);
Your lines with products[x] overwrite the earlier.
Change to
products[x] = {
productName: test[x]['name'],
category: test[x]['category'],
price: test[x]['price'],
};
There's a couple of problems first...
The $.ajax() config option is dataType, not datatype
Specifying dataType: "json" means jQuery will automatically parse the response as JSON. You don't need to manually parse it again
As to your mapping problem, you can map the response array to a new one with name renamed to productName using Array.prototype.map()
$.ajax("fetch.php", {
method: "POST",
dataType: "json",
// data: ¯\_(ツ)_/¯
}).done(data => {
const products = {
data: data.map(({ name: productName, category, price }) => ({
productName,
category,
price
}))
};
});
Related
Not getting array of data from ajax to controller.
$.ajax({
type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: {
"Query": JSON.stringify(Query) //change this
success: function() {}
});,
And array of Query :
0: {label: "abc:", value: "123", type: "Select"} 1: {label: "xyz",
value: "Hum", type: "text"}
Can anyone help ?
Try something like this
<script type="text/javascript">
var query=[{label: "abc:", value: "123", type: "Select"},{label: "abc:", value: "1232", type: "Select"} ];
$.ajax({ type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: JSON.stringify(query),
success: function (){
} });
</script>
I think something along this may work for you.
function sendarray() {
var arr = [];
var json = {
"label": 'abc',
"value": 1234,
"Name": 'Name'
};
arr.push(json);
json = {
"label": 'abc2',
"value": 1234,
"Name": 'Name2'
};
arr.push(json);
var myarray = JSON.stringify(arr);
$.ajax({
url: '/controller/GetArray',
type: 'POST',
data: { array: myarray },
success: function (data) {
//Do something
},
error: function () {
//Do something
}
});
}
then in the controller
public JsonResult GetArray(string array)
{
var obj = JsonConvert.DeserializeObject<object>(array);
return Json("");
}
This will send an string with all the data in the array to the controller, then you turn string with json format into an object list
I am working with the Twitter API for trends (see: https://developer.twitter.com/en/docs/trends/trends-for-location/api-reference/get-trends-place).
The API returns the following JSON:
{
trends: [
{
name: 'Boris',
url: 'http://twitter.com/search?q=Boris',
promoted_content: null,
query: 'Boris',
tweet_volume: 1083274
},
{
name: '#COVID19',
url: 'http://twitter.com/search?q=%23COVID19',
promoted_content: null,
query: '%23COVID19',
tweet_volume: 2088454
},
{
name: '#WorldHealthDay',
url: 'http://twitter.com/search?q=%23WorldHealthDay',
promoted_content: null,
query: '%23WorldHealthDay',
tweet_volume: 250817
}
],
as_of: '2020-04-07T14:06:49Z',
created_at: '2020-04-07T14:03:32Z',
locations: [ { name: 'London', woeid: 44418 } ]
}
I would like to transform this into a Javascript array containing all of the values where the key is name; ie.:
arr=["Boris", "#COVID19", "WorldHealthDay"]
How can I achieve this? From what I have read, native JavaScript JSON parsers cannot handle duplicate keys.
your data:
trends = [
{
name: 'Boris',
url: 'http://twitter.com/search?q=Boris',
promoted_content: null,
query: 'Boris',
tweet_volume: 1083274
},
{
name: '#COVID19',
url: 'http://twitter.com/search?q=%23COVID19',
promoted_content: null,
query: '%23COVID19',
tweet_volume: 2088454
},
{
name: '#WorldHealthDay',
url: 'http://twitter.com/search?q=%23WorldHealthDay',
promoted_content: null,
query: '%23WorldHealthDay',
tweet_volume: 250817
}
];
then use map
var ans = trends.map(d => d.name)
results:
ans = ["Boris", "#COVID19", "#WorldHealthDay"]
Arrays can contain duplicate VALUES, which is what you've requested. Arrays do not contain keys, and these strings in the array are also values of the 'name' key inside of the JSON returned from the twitter API.
To solve your problem, for example, with a very basic iteration and no Array.map
const data = JSON.parse(data_str);
const arr = [];
for (const trend of data.trends) {
arr.push(trend.name);
}
I am trying to get all IDs from an array objects and put the in a list so they can be passed to a method (API)
var tempObj= Getlist();
var tmpList = tempObj.listOfdata.filter(function (result) { return (result.Id) });
var data = tmpList
then I have my AJAX call
$.ajax({
url: url,
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
async: true,
method: 'POST',
success: function (data) {
console.log(data);
}
});
no data is being passed
If you want to extract values from a collection of objects, don't use filter. Use map.
let list = [
{ id: 1 },
{ id: 3 },
{ id: 23 },
{ id: 16 }
];
let data = list.map((obj) => obj.id);
console.log(data);
In ES5:
var list = [
{ id: 1 },
{ id: 3 },
{ id: 23 },
{ id: 16 }
];
var data = list.map(function(obj) {
return obj.id;
});
console.log(data);
I try to send an array of json objects to server:
var objectData = [
{ Description: "Bezeichnung", Value: "1", Name: "Betrag (Brutto)" },
{ Description: "Dies ist die erste Bezeicnung", Value: "101", Name: "11,90" },
{ Description: "Dies ist die zweite Bezeicnung", Value: "12", Name: "11,90" }
];
$.ajax({
url: "/system/createinvoice",
data: JSON.stringify({ pos: objectData }) ,
dataType: 'json',
type: 'POST',
});
C#
public class InvoicePos
{
public string Description { get; set; }
public Nullable<double> Value { get; set; }
public string Name { get; set; }
}
[POST("/system/createinvoice")]
public void newquestion2(InvoicePos[] pos)
{
// pos is always null
}
The dataType property is saying what you expect back from the server. Try setting the contentType:
contentType: 'application/json'
Try
data: JSON.stringify({ pos: #objectData })
Also, check what is being rendered in the View through the browser. The reason you are getting null is likely because JavaScript is not getting a proper value.
function SendArrayOfObjects()
{
var things = [{ id: 1, color: 'red' }, { id: 2, color: 'blue' }, { id: 3, color: 'yellow' }];
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/MyServices.aspx/GetData")%>",
data: JSON.stringify({ objdata: things }),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function()
{
$("#msg").html("data sent successfully!");
},
error: function()
{
$("#msg").html(" Can not send data!");
}
});
}
I am using this example using drag and drop from this site:
I am creating containers using Dnd item types example in the same page. Like this;
Source container
var catalog = new dojo.dnd.Source("catalogNode", {
accept: ["inStock,outOfStock"]
});
catalog.insertNodes(false, [
{ data: "Wrist watch", type: ["inStock"] },
{ data: "Life jacket", type: ["inStock"] },
{ data: "Toy bulldozer", type: ["inStock"] },
{ data: "Vintage microphone", type: ["outOfStock"] },
{ data: "TIE fighter", type: ["outOfStock"] },
{ data: "Apples", type: ["inStock"] },
{ data: "Bananas", type: ["inStock"] },
{ data: "Tomatoes", type: ["outOfStock"] },
{ data: "Bread", type: ["inStock"] }
]);
catalog.forInItems(function(item, id, map){
// set up CSS classes for inStock and outOfStock
dojo.addClass(id, item.type[0]);
});
Target container
var wishlist = new dojo.dnd.Source("wishlistNode", {
accept: ["inStock","outOfStock"]
});
here what I am doing;
dojo.connect(dojo.byId('JsonBtn'), 'onclick', function() {
var catalogNode = document.getElementById("catalogNode");
//Get all nodes in the assignRoleListContainer
var container2 = catalogNode.getAllNodes();
var results="";
var catalog_arr = [];
var len = container2.length;
for(var i=0;i<len;i++){
results = catalogNode.childNodes[i].childNodes[0].nodeValue;
catalog_arr.push(results);
}
//Json
var myJSON2 = "";
myJSON2 = JSON.stringify({catalog: catalog_arr});
});
I managed to convert all data in Json;
{"catalog":["Life jacket","Toy bulldozer","Wrist watch","Apples","Bananas","Bread","Tomatoes","Vintage microphone","TIE fighter"]}
But now I want to convert the items to json, but with respect to their types, e.g.
If type inStock
{"inStock":["Life jacket","Toy bulldozer","Wrist watch","Apples","Bananas","Bread"]}
If type outOfStock
{"outOfStock":["Tomatoes","Vintage microphone","TIE fighter"]}
Any suggestion?
Source container
var catalog = new dojo.dnd.Source("catalogNode", {
accept: ["inStock","outOfStock"]
});
catalog.insertNodes(false, [
{ data: "Wrist watch", type: ["inStock"] },
{ data: "Life jacket", type: ["inStock"] },
{ data: "Toy bulldozer", type: ["inStock"] },
{ data: "Vintage microphone", type: ["outOfStock"] },
{ data: "TIE fighter", type: ["outOfStock"] },
{ data: "Apples", type: ["inStock"] },
{ data: "Bananas", type: ["inStock"] },
{ data: "Tomatoes", type: ["outOfStock"] },
{ data: "Bread", type: ["inStock"] }
]);
catalog.forInItems(function(item, id, map){
// set up CSS classes for inStock and outOfStock
dojo.addClass(id, item.type[0]);
});
Target container
var wishlist = new dojo.dnd.Source("wishlistNode", {
accept: ["inStock","outOfStock"]
});
Button with Id=JsonBtn, and onClick event, convert data in target container to json
dojo.connect(dojo.byId('JsonBtn'), 'onclick', function() {
var target_container = wishlistNode.getAllNodes();
var inStock_arr = [];
var outOfStock_arr = [];
for(var i=0;i<target_container.length;i++){
if (hasClass("inStock", target_container[i].classList)){
var inStock_results = target_container[i].childNodes[0].nodeValue;
inStock_arr.push(inStock_results);
}
else if(hasClass("outOfStock", target_container[i].classList)){
var permissions_results = target_container[i].childNodes[0].nodeValue;
outOfStock_arr.push(outOfStock_results);
}
}
var result={};
result["inStock"]=inStock_arr;
result["outOfStock"]=outOfStock_arr;
alert(JSON.stringify(result));
});
Check classList function
function hasClass(className, classList){
for (var i=0; i<classList.length; i++){
if(classList[i]==className){
return true;
}
}
return false;
}
Output: (This output also fine for me)
{
"inStock":[
"Wrist watch", "Life jacket", "Toy bulldozer", "Apples", "Bananas", "Bread"],
"outOfStock":[
"Vintage microphone", "TIE fighter", "Tomatoes"]
}
First of all, thanks to FireFox team for their "FireBug". It helps a lot in debugging and programming and without it its very difficult for me to find the solution.
And if there any explanation needed, I am happy to help.