I am very new to javascript. I have a requirement to make a server call, get the json response and parse the response and populate the formatted response to a variable inside a object literal.
Its looks something like this below:
$('#dataTables-example').dataTable({
"bJQueryUI": true,
"sPaginationType": "full_numbers",
"bAutoWidth": true,
"aaData":
[
[
"",
"1",
"name-key",
"description"
],
[
"",
"2",
"name",
"description"
],
[
"",
"23",
"name",
"description"
],
[
"",
"24",
"abs",
"Common"
],
[
"",
"5",
"name1",
"description"
],
[
"",
"6",
"name2",
"description"
]
]
});
In the above, I need to populate the aaData variable with json data from a server call. Please let me know how to get this done in javascript.
What you want is to call the server via AJAX. JQuery handles this for you quite easily.
Check out this link: https://api.jquery.com/jQuery.ajax/
A simple example of using AJAX:
$.ajax({
url: 'your url here'
success: function(data, textStatus, jqXHR) {
console.log(data)
}
});
You will want to make this call and set the data from the success function to a variable, format it correctly (possibly using for loops), and then use that variable as your 'aaData' value.
Related
$.ajax({
'url': 'http://localhost:8080/Retail-war/webresources/products/allProducts',
'method': 'GET',
'contentType': 'application/json',
'headers': {"Authorization": 'Bearer ' + sessionStorage.getItem('accessToken')},
}).done( function(data) {
$('#existing-product').DataTable( {
"columnDefs": [
{ "targets": -1, "data": null, "defaultContent": "<button>View More Details!</button>"}
],
"aaData": data,
"columns": [
{ "data": "products.productId"},
{ "data": "products.originalPrice"},
{ "data": "products.currentPrice"},
]
})
This is my format of my JSON file and I would like to populate the DataTable with the 3 columns in products but nothing is showing up in the DataTable and no error is thrown too. How can I populate each columns with the columns in the JSON file under the products object?
{
"products": [
{
"productId": 1,
"originalPrice": 60,
"currentPrice": 50
},
{
"productId": 2,
"originalPrice": 80,
"currentPrice": 70
}
]
}
Instead of accessing your data like this...
// does not work
"data": data,
"columns": [
{ "data": "products.productId"},
{ "data": "products.originalPrice"},
{ "data": "products.currentPrice"}
]
Change the initializer to this:
// works
"data": data.products,
"columns": [
{ "data": "productId"},
{ "data": "originalPrice"},
{ "data": "currentPrice"}
]
DataTable needs the iterable object you will be using to be outside of the columns definitions (where the iteration happens).
These changes work for me (in my stripped-down version of your example).
UPDATE:
As requested, here are some more details to explain the situation:
If you try to use "data": data,, then you are providing a JSON object which has this structure:
{"products": [an array of objects]}
This is used by the columns definitions to iterate over your JSON. But there is nothing to iterate over - there is only the one item - the array.
However, if you first drill down one level in your structure by using "data": data.products, you are passing the following JSON to your the columns definitions:
[{row 1 data}, {row 2 data}, ... {row n data}]
This can be iterated by DataTables, to populate each row in its table.
You can still drill down into each object being iterated, if there are nested objects. In your case there aren't any nested objects - but imagine if your data looked like this (a totally artifical example, by the way):
{
"products": [{
"productId": 1,
"originalPrice": {
"currency": "USD",
"amount": 60
},
"currentPrice": 50
}, {
"productId": 2,
"originalPrice": {
"currency": "USD",
"amount": 80
},
"currentPrice": 70
}]
}
In this case, we can access the data like this:
"data": data2.products,
"columns": [
{ "data" : "productId" },
{ "data" : "originalPrice.amount" },
{ "data" : "currentPrice" }
]
Here we see the use of the dot notation to drill down into the originalPrice object, to grab the number we want to display: originalPrice.amount.
By default DataTables expects the array to be called data. You can change it using the dataSrc property, but only if you are using the built-in DataTables Ajax option, which to be honest is recommended anyway. Define your DataTable like this:
$('#existing-product').DataTable( {
ajax: {
url: "http://localhost:8080/Retail-war/webresources/products/allProducts",
dataSrc: "products",
headers: {"Authorization": 'Bearer ' + sessionStorage.getItem('accessToken')},
}
});
Alternatively rename your array on the server before you echo it back to "data"
I have a Kendo grid where I'm trying to add a delete feature. My datasource looks like:
var datasource = new kendo.data.DataSource({
transport: {
read: {
url: Router.action("Admin", "GetScansForMailItem", { mailItemIdnt: detailinit.data.MailItemIdnt }),
dataType: "json"
},
destroy: {
url: Router.action("Admin", "DeleteScan"),
type: "post"
}
},
model: {
id: "ScanIdnt",
fields: {
ScanIdnt: {editable: false, nullable: false}
}
},
pageSize: 5
});
I added the model part because this answer, however it made no difference.
The actual grid looks like:
.kendoGrid({
dataSource: datasource
scrollable: false,
sortable: true,
pageable: true,
editable: "inline",
columns: [{
field: "ScanIdnt",
title: "Scan ID"
}, {
field: "CreatedDate",
title: "Created",
template: "#= kendo.parseDate(CreatedDate, 'yyyy/MM/dd') #"
}, {
field: "ScanDocumentRelativePath",
title: "File Path",
template: "<a href='/CAMP/Admin/Download?scanIdnt=#= ScanIdnt #'>#= ScanDocumentRelativePath.substring(1) #</a>"
}, {
field: "ScanUserIdnt",
title: "Scanned By"
},{
command: "destroy",
title: ""
}]
});
Strangely, clicking the delete button removes the from the gird on the UI, but there is absolutely no Ajax call is made the the destroy URL. I can't seem to figure out why. Any ideas?
EDIT I'd like to point out that this grid is in fact a nested grid inside of another grid (like here) I discovered that the parent grid handles actually makes a call, but to the wrong function. For some reason, it clicking delete on a to level item calls the read function of the nested grid, however, the nested grids do nothing
Figured it out (sorta). While I think there were many issues with my code and the grid, It seems that when it came down to it, Kendo didn't like how I had my data.
In the Kendo docs related to hierarchical grids, the data for the child grid is stored in a field of the data for the parent. For example, given the following JSON:
"ParentItems": [
{
"Id": 12345 ,
"Name": "Test1",
"ChildItems": [
{"Id": 1, "Name": "Test"},
{"Id": 2, "Name": "Test"}
]
},
{
"Id": 12346 ,
"Name": "Test2",
"ChildItems": [
{"Id": 1, "Name": "Test"},
{"Id": 2, "Name": "Test"}
]
}
]
In the parent grid, each ParentItem would display it's respective ChildItems in the child grid.
On the other hand, I was pulling both data sets separately. Basically, I pulled the ParentItems like:
"ParentItems": [
{
"Id": 12345,
"Name" : "Test1"
},
{
"Id": 12346,
"Name" : "Test2"
}
]
And then made a second request to pull the child items, based on the parent's id.
"ChildItems": [
{"Id": 1, "Name": "Test", "ParentId": "12345"},
{"Id": 2, "Name": "Test", "ParentId": "12345"}
]
I was able to modify the server side code to serve the data like in the very first example and managed to get things working. The specific document that helped me out can be found here
I have an ajax call that returns:
[{"fields":
{"account_to": ["Bank Account - SECU", "11000"],
"posted_by": 1,
"amount": "1000",
"created_date": "2015-07-31T14:53:03.766Z",
"posting_date": "2015-07-31T14:53:03.763Z",
"account_from": ["Consulting Income - ABC", "41000"],
"company": "S&S Co"},
"model": "base.glentry", "pk": 8},
{"fields": ...
]
Note that there is no: {'data': [ data array ]} which all the examples have. I can find how to change the name so that 'data' can be something else, but how do I make it render like this with AJAX without manually processing the return value and wrapping the data?
Here is my javascript:
$('#dt').dataTable( {
"processing": true,
"ajax": "http://localhost:8000/gl/",
"columns": [
{"": "fields.amount"}
]
} );
I've tried all sorts of things, but get the same result. What can I do?
The format for my select 2 is as such:
$("#selectPretty").select2({
tokenSeparators: [","],
tags:["1", "2", "3", "php", "tiger", "test", "big bang theory", "bikes", "gh", "sd", "cheese", "food", "name", "jack", "chickens", "yikes!", "testing", "this", "is", "a", "questionj", "new", "question", "s"]
});
Which shows as such:
BUT, when I try to assign data into the box dynamically through AJAX by using this code:
$.ajax({
type: "POST",
url: "grabTags.php",
data: "tags="+$("#selectPretty").val(),
success:
function(msg2) {
alert(msg2);
$("#selectPretty").select2({
tokenSeparators: [","],
tags:[msg2]
});
}
});
It will come out like so:
For some reason the whole string is one option and I can't make it explode the result into different options...
Does anyone know what I can do here?
Note that 'tags:[msg2]' is returned from my grabTags.php file and 'msg2' = "1", "2", "3, etc...
Kindest Regards
Have you tried splitting the string that comes back from the PHP?
You can invoke the split method on a string (such as that which is returned from your PHP) and pass it a separator (in your case a ,).
Something like this should work:
$.ajax({
type: "POST",
url: "grabTags.php",
data: "tags="+$("#selectPretty").val(),
success:
function(msg2) {
//at this point, msg2 is the string: '"1","2","3"'
var myTags = msg2.split(',');
//myTags is now the array: ["1","2","3"]
$("#selectPretty").select2({
//tags needs to be an array, so pass in myTags
tags: myTags
});
}
});
The Select2 tags need a javascript array, not just a string surrounded by brackets.
So server side, have PHP spit out a json encoded array:
$tags = array("1", "2", "3", "php", "tiger", "test", "big bang theory", "bikes", "gh", "sd", "cheese", "food", "name", "jack", "chickens", "yikes!", "testing", "this", "is", "a", "questionj", "new", "question", "s");
echo json_encode($tags);
Now client side take that response in your ajax success handler, and assign it directly to tags.
Note that you may need to set dataType to json in your ajax call so that jQuery automatically parses the response as json. Not sure if it will figure that out on its own or not.
You may also be able to get rid of tokenSeparators if you provide an actual array as your tags.
I have a json object that I'm loading from wordpress using the JSON API plugin. When I load the json object and try to log out the parts of it, it seems like it treats every single character as its own object so the loop returns me a couple thousand objects all with item in it which is a single character. This is my first time using json so idk if i'm missing a step here. this is the code I'm using so far.
function getProjInfo(theId){
$.ajax({// calling the ajax object of jquery
type: "GET",// we are going to be getting info from this data source
url: 'http://testing.charter21.com/api/get_post/?post_id='+ theId,//the datasource
dataType: "application/json",
success: function(data){
parseJson(data);
}, // what happens when it is successful at loading the XML
error: function(){
alert("error");
}
});
}//end of the function
function parseJson(inData){
postInfo = inData;
$.each(postInfo, function(index, value){
console.log(this);
});
}
the json looks like this:
{
"status": "ok",
"count": 10,
"count_total": 19,
"pages": 2,
"posts": [
{
"id": 175,
"type": "post",
"slug": "home-page-slider",
"url": "http:\/\/testing.charter21.com\/uncategorized\/home-page-slider\/",
"status": "publish",
"title": "Home Page slider",
"title_plain": "Home Page slider",
"content": "<p>The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.<\/p>\n",
"excerpt": "The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.",
"date": "2011-01-25 10:40:25",
"modified": "2011-01-25 10:40:25",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open"
}
so basically instead of giving me "status" as an key and "ok" as a value, i get "s" as an object with an index 0 that has a value of "s" for every single character in the json object. Any help on this matter would be appreciated.
You need to set dataType:json in your $.ajax() request so that jQuery converts the JSON-formatted string into a JavaScript object for you to process as such. You're currently using application/json which is a mime type, and not a valid value for this field in a jQuery request.
In your case you can even try data = eval(data) , this javascript statement should convert your string to json object.
Use the Jquery function:
data = $.parseJSON(data);
before using $.each.
The way I solved it in my AngularJS app is by sending the response from the server (I'm using Node Express) as a JavaScript object, rather than as a string. Nothing else worked for me.
var response = {};
response.error = "Error message";
res.send(response);