I need to load a datatable with a JSON dataset. I don't want to do server side processing. but I do want to retrieve the full set of data from a URL. I got to the point where there's no error on load but for some reason, the table stays empty with 0 results.
I am building the JSON on the server side like this:
public static function datatableOutput($array){
foreach($array as $key=>$line){
$output[] = [
"href"=>$line['href'],
"code"=>$line['code'],
"time"=>$line['time'],
"img_count"=>$line['img_count'],
"int_count"=>$line['int_count'],
"ext_count"=>$line['ext_count']
];
}
return array('data'=> $output);
}
Later in the code it returns a json string like this:
return response()->json($this::datatableOutput($links));
And in the view my script looks like this:
$.ajax({
url: '/crawl',
type: "post",
data: {
url: $("#url").val(),
pages: $("#pages").val(),
_token:"{{ csrf_token() }}"
},
dataType : 'json',
success: function(data){
// Done state
$('#iamarobotnotaslave').hide();
$('#justasecdude').hide();
$('#crawl').hide();
$('#report_section').show();
$('#report').DataTable( {
data: data,
columns: [
{ title: "href" },
{ title: "code" },
{ title: "time" },
{ title: "img_count" },
{ title: "int_count" },
{ title: "ext_count" }
]
} );
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
// Error state
$('#iamarobotnotaslave').hide();
$('#justasecdude').hide();
$('#goaheaddude').show();
$('#error').show();
}
});
The JSON data set returned looks like this:
{
"data":[
{
"href":"\/",
"code":200,
"time":0.2746608257293701,
"img_count":6,
"int_count":204,
"ext_count":6
},
{
"href":"\/feature\/automated-marketing-reports",
"code":200,
"time":0.1753251552581787,
"img_count":7,
"int_count":72,
"ext_count":6
},
{
"href":"\/feature\/marketing-dashboard-2",
"code":200,
"time":0.15781521797180176,
"img_count":8,
"int_count":73,
"ext_count":6
}
]
}
Everything seems to be valid but for some reason I still get 0 results ... I am probably missing something obvious thought. I tried the JSON with and with out the "data" array.
Related
So I can easily pass data to my table when the JSON data is read from a .txt file.
However, when I use ajax to hit an endpoint and return data, I get errors. Can anybody see what's wrong?
var table;
$.ajax({
url: '../forms/test/get_data',
type: 'GET',
dataType: 'json'
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function(data) {
console.log(data); // This comes back correctly and in the same format as the txt file.
table = $('#feeds').DataTable( {
//"ajax": "/javascripts/test/ajax/data/object.txt",
"ajax" : function(dataa, callback, settings) {
callback(data)
},
"scrollX" : true,
"data" : data,
"columns": [
{
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "id" },
{ "data": "status" }
]});
});
I get "Uncaught TypeError: Cannot read property 'row' of undefined
at n.fn.init.createdRow (eval at (jquery-1.12.0.min.js:2), :63:45)" as an error in my console.
User to JSON.parse() method for convert string data to object data like
: "data" : JSON.parse(data),
try above Code..
I'm using jQuery bootgrid to display data in table. I get data using Ajax and I return the values in JSON format. On the JSON string it comes a variable I want to read to display in other section out of the table.
Ajax function is the following:
function ajaxAction(action) {
data = $("#frm_"+action).serializeArray();
$.ajax({
type: "POST",
url: "response_pedidos.php",
data: data,
dataType: "json",
success: function(response)
{
$('#'+action+'_model').modal('hide');
$("#employee_grid").bootgrid('reload');
},
error: function (request, error) {
console.log(arguments);
}
}); }
I'm watching response from PHP page and it comes with the following format:
{"current":1,
"rowCount":20,
"total":7,
"cantidad_totales":8.5,
"id_pedido":13,
"rows":[{"id_pedidos_productos" :"57",
"cantidad":"1.5",
"descripcion":"prueba con decimales",
"nombre":"Astro naranja"},
{"id_pedidos_productos":"52",
"cantidad":"1",
"descripcion":"",
"nombre":"Gipso grande"},
{"id_pedidos_productos":"54",
"cantidad":"1",
"descripcion":"",
"nombre":"Lilis Rosita"},
{"id_pedidos_productos":"53",
"cantidad":"1",
"descripcion" :"",
"nombre":"Plumosos"},
{"id_pedidos_productos":"56",
"cantidad":"1",
"descripcion":"",
"nombre":"ROSAS BABY VENDELA"},
{"id_pedidos_productos":"55",
"cantidad":"1",
"descripcion":"",
"nombre":"Rosas rojas"},
{"id_pedidos_productos":"51",
"cantidad":"2",
"descripcion":"",
"nombre":"ROSAS ROSITAS \"MATIZADAS\"" }]}
On the page, my table looks like this, I want to display obtained value in the field below the table:
Now, what I want to do is to read returned value named: "cantidad_totales".
I would like to catch it to display in resume section of the page.
Does anyone know how can I do it ?
This is how you could handle it:
var cantidadTotales;
$('#tbl').bootgrid({
formatters:{
...
},
rowCount: [5, 10, 25],
...
labels: {
....
},
css: {
...
},
responseHandler: function (data) {
var response = {
current: data.current,
rowCount: data.rowCount,
rows: data.rows,
total: data.total,
cantidad_totales: data.cantidad_totales,
id_pedido: data.id_pedido
};
//store cantidad_totales into a variable...
cantidadTotales = data.cantidad_totales;
return response;
},
ajaxSettings: {
method: 'POST',
contentType: 'application/json'
},
ajax: true,
url: 'The_Url_To_Load_Your_Data'
}).on("loaded.rs.jquery.bootgrid", function (s) {
//Now, display the cantidad_totales in your div or whatever
$('div#YourTotalDiv').html(cantidadTotales);
});
})
I'm trying to send an object that looks like this
var postBody = {
id: userID,
objectID: [0, 1],
objects: [
{id: 0, x: 0.33930041152263374, y: 0.08145246913580247, width: 0.0823045267489712, height: 0.30864197530864196},
{id: 1, x: 0.5277777777777778, y: 0.08453888888888889, width: 0.0823045267489712, height: 0.30864197530864196}
]
};
this is ajax call
$.ajax({
type: 'POST',
url: url,
data: postBody,
dataType: 'JSONP',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
this is what it looks like on server
{ id: '583f137fc338b517ec467643',
'objectID[]': [ '0', '1' ],
'objects[0][id]': '0',
'objects[0][x]': '0.33930041152263374',
'objects[0][y]': '0.08145246913580247',
'objects[0][width]': '0.0823045267489712',
'objects[0][height]': '0.30864197530864196',
'objects[1][id]': '1',
'objects[1][x]': '0.5277777777777778',
'objects[1][y]': '0.08453888888888889',
'objects[1][width]': '0.0823045267489712',
'objects[1][height]': '0.30864197530864196' }
if I put data: JSON.stringify(postBody) this is what I get
{ '{"id":"583f137fc338b517ec467643","objectID":[0,1],"objects":[{"id":0,"x":0.5,"y":0.5,"width":0.1,"height":0.1},{"id":1,"x":0.5401234567901234,"y":0.1833043209876543,"width":0.0823045267489712,"height":0.30864197530864196}]}': '' }
And it works! but then I cannot JSON.parse() it
this is what I get when I try
TypeError: Cannot convert object to primitive value
and all that Im doing on data on backend is this
console.log(JSON.parse(req.body)); // in the first example it was the same thing but only without JSON.parse()
Anyone have an idea why this is happening here?
Even if you have a suggestion on what I could try feel free to post here, otherwise I'm gonna have to write a function for parsing these badass inputs lol.
All the parsing/stringifying is handled by Node, so don't worry about it, just pass your object as it is, and you'll be able to access its properties in req.body.
client :
$.ajax({
type: 'POST',
url: url,
data: postBody,
dataType: 'json',
success: function(data) {
console.log(data);
},
error: function(err) {
console.log(err);
}
});
server :
console.log(req.body); //should give you [Object object]
you can then send it right back with: res.status(200).json(req.body));
and read it in your ajax callback :
success: function(data) {
console.log(data);
},
This is what I want to achieve:
I want to create an interactive map using raphael.js.
Using Php, I get datas from MySql DB and converted into a JSON file.
So far so good.
Inside my raphael js file, I must now:
get those datas
use them in order to modify my raphael file.
I am currently stuck at this first step.
Here's my simplified JSON file (let's call it countries.json) :
[
{
"id": "1",
"type": "Country",
"title": "France",
"published": "1",
"description": "Republic"
},
{
"id": "2",
"type": "Country",
"title": "Belgium",
"published": "0",
"description": "Monarchy"
}
]
Here comes the simplified raphael.js
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': '', 'title': '', 'description':''});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': '', 'title': '', 'description':''});
countries.push(france,belgium);
At the end of the raphael js, I make an Ajax request (using jquery) to get my JSON datas :
$.ajax({
type : 'GET',
url : 'system/modules/countries.json',
data: {get_param: 'value'},
dataType : 'json',
success : function(data, statut){
console.log(statut);
},
error : function(data, statut,erreur){
console.log(statut);
},
complete: function (data) {
var json = $.parseJSON(data);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
}
});
Here come the troubles:
I get a 'success' status trough the success function.
BUT I got an error while completing the script :
Uncaught SyntaxError: Unexpected token o
What did I miss? Can't figure out what is different from http://jsfiddle.net/fyxZt/4/ (see how to parse json data with jquery / javascript?)
That was just for part 1 :-)
Assuming someone could help me to fix that, I still then have no idea how to write js loop that will set the raphael vars attributes as it:
var rsr = Raphael('map', '548', '852');
var countries = [];
var france = rsr.path("M ... z");
france.data({'published': '1', 'type': 'Country', 'title': 'France', 'description':'Country'});
var belgium = rsr.path("M ... z");
belgium.data({'published': '0', 'type': 'Country', 'title': 'Belgium', 'description':'Monarchy'});
communes.push(france,belgium);
Thanks an advance for your help and please excuse my unperfect english!
Vinny
There is no data argument passed to the complete callback,
according to jQuery API:
complete
Type: Function( jqXHR jqXHR, String textStatus )
(...)The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror").
So you only need to use the success callback :
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
var json = data;
$(json)
.each(function (i, val) {
$.each(val, function (k, v) {
console.log(k + " : " + v);
});
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});
Concerning your second question, you cannot interact directly with variable name (accessing dynamic variable) in js, so you'll need to create an object where values are indexed by one of your json's values. However, the cleanest way to handle this would probably be to add your paths to the json...
var rsr = Raphael('map', '548', '852');
var countries = [];
//here I used the "id" property from the json
var paths={
"1":rsr.path("M ... z"),
"2":rsr.path("M ... z")
};
countries.push(france,belgium);
$.ajax({
type: 'GET',
url: 'system/modules/countries.json',
data: {
get_param: 'value'
},
dataType: 'json',
success: function (data, statut) {
datas.forEach(function (country) {
paths[country.id].data(country);
});
},
error: function (data, statut, erreur) {
console.log(statut);
}
});
the post title may not explain fully, but here is what I am hoping to do: I have my JavaScript code in a separate file, and I have it arranged like so
var PK = {
"vars" : {
"uris" : {
"app1": "http://this/server/",
"app2": "http://that/server/"
},
"something": {
"objects": [],
"obj1": { "url": PK.vars.uris.app1 },
"obj2": { "url": PK.vars.uris.app2 }
}
},
"methods" : {
"doThis" : function(a) {
$.ajax({
url: PK.vars.uris.app1,
data: data,
type: "GET",
success: function(data) { .. do something .. }
});
},
"doThat" : function(a) {
$.ajax({
url: PK.vars.uris.app2,
data: data,
type: "GET",
success: function(data) { .. do something else .. }
});
},
"init" : function(position) {
if (position) { PK.methods.doThis();
}
else {
PK.methods.doThat();
}
}
}
};
and then, in my html, I have the following
$(document).ready(function() {
PK.vars.uris.app1 = "[% app1 %]";
PK.vars.uris.app2 = "[% app2 %]";
PK.methods.init();
});
where the values of app1 and app2 are sent from the server based on a config file. Except, it doesn't work as expected, because, when the separate JavaScript loads, PK.vars.uris is not defined at that time. Of course, everything works beautifully if I have PK.vars.uris{} hardcoded.
How can I delay the evaluation of var PK until after the document has loaded and PK.vars.uris is available to be used in the JavaScript code?
Is the problem that you need to pass values into an initialiser?
How's this approach:
In your external file:
function PK_Constructor(app1Uri, app2Uri) {
this.vars = { "uris" : {
"app1" : app1Uri,
"app2" : app2Uri
},
"something": {
"objects": [],
"obj1": { "url": app1Uri },
"obj2": { "url": app1Uri }
},
};
this.doThis = function(a) {
$.ajax({
url: this.vars.uris.app1,
data: data,
type: "GET",
success: function(data) { .. do something .. }
});
// etc
}
And in you HTML:
// Ensuring PK has global scope
var PK = undefined;
$(document).ready(function() {
PK = new PK_Constructor("[% app1 %]", "[% app2 %]");
});