JsTree and Laravel Trouble - javascript

I'm following this guide to setup JsTree with lazy load using Ajax in my Laravel 5.5 app .
This is my controller: https://gist.github.com/aaronr0207/7fa0a38f40bfd2f728a15d655254f82d
My View:
https://gist.github.com/aaronr0207/f87720263e3d6026b04b00c08bae5cb2
My JsTree class is exactly the same I didn't make any change.
Actually I'm getting the following error on chrome's console:
d9973d3e-1476-4453-a013-9e9c8430bcba:1 Uncaught TypeError: Cannot read property 'children' of undefined
But when I dump the response to debug it (at the end of TreeViewController data method):
dd(response()->json($tree->build()));
It works...
My response looks like this (when I die-dump it):
Any idea? Thank you
EDIT1: If I return a simple json_encode($tree->build) there are no errors but it shows an empty tree... and the response looks like this:
EDIT2: got it! But now there are a new issue... All I did to solve it was change the url string with a callback:
$('#jstree').jstree({
'core': {
'data': {
'url': function (node) {
return '{!! route('tree.data') !!}' ;
},
'data': function (node) {
console.log(node);
return {'id': node.id};
}
}
}
});
But now when I fetch next level directories, if they have another directorie inside it fails without error:
Test1 content is the following:
If I delete test1/test2 folder, it works showing:
Same when I delete the txt file...What is happening now? Maybe this is a new question so I'll post my solution to the main problem and I'll accept it.

I suspect your named route is not working correctly. In your TreeController.php, change the route tree/route as follows:
Route::get('tree/route', 'TreeController#data')->name('tree.data');

got it! All I did to solve it was change the url string with a callback:
$('#jstree').jstree({
'core': {
'data': {
'url': function (node) {
return '{!! route('tree.data') !!}' ;
},
'data': function (node) {
console.log(node);
return {'id': node.id};
}
}
}
});

This could be caused by the escaping in the response. Can you dd($request->id) when the id is set?

Related

JS Fetch api and Symfony2 FOSRestBundle

Currently I am trying to get a response from my Symfony2 FOSRest Controller using Javascript Fetch API. In my controller I am serving a response with the following code:
return View::create()
->setStatusCode(200)
->setData(array('success'=>true));
And in my JS I am getting it with this:
fetch(url, 'get').then(
function (response) {
if (response.status !== 200) {
console.log('Problem, status: ' + response.status);
return;
}
response.json().then(function (data) {
console.log('OK');
if (typeof callback == 'function')
return callback(data);
});
}
).catch(function (err) {
Console.log(err);
});
As a result my controller is giving me a pure json which I can see (in Chrome Dev Tools under Response section) if I type my url directly into browser, but when js code is executed I see the following error:
Uncaught (in promise) SyntaxError: Unexpected token <
which is related to my initial file which begins from !doctype html. In my debugger if I log response.body I see that it is ReadableByteStream, but not my json. I think that the problem is somewhere in Symfony because I can read my json if I send it from regular .php file but not from RESTFul controller. Any help would be appreciated.
UPD:
when I changed response.json() to response.text() I finally got the data)) Is there any reason for that? And in addition in my url I have query string parameters (like ?par1=1&par2=2) which I want to pass to my REST Controller and which I get when I again type my url into browser directly with the following method:
$data = $request->query->get('data');
But when I pass it with JS fetch (in url parameter) no data is transferred to controller. Any idea what to do in this case? Thank You
UPD2
My symfony config.yml
fos_rest:
param_fetcher_listener: true
body_listener: true
format_listener: true
view:
formats:
json: true
xml: false
html: false
rss: false
templating_formats:
json: false
xml: false
html: false
rss: false
view_response_listener: 'force'
sensio_framework_extra:
view: { annotations: false }
router: { annotations: true }
Try to add this in your config :
fos_rest:
# ...
view:
# ...
formats:
json: true
If it doesn't work, add the following :
fos_rest:
# ...
format_listener:
rules:
- { path: '^/yourApiPrefix', priorities: ['json'], fallback_format: json, prefer_extension: false }

Meteor, TypeError: Cannot read property '_id' of undefined. Getting the _id from from a post parameter

I've just started to have a play with meteor and I'm slowly moving a
NodeJS/Express app over to meteor. However on my blog section, I can't seem to get a single post _id into the helper. With NodeJS alone, I could use req.params._id.
Using the Differential boilerplate as a starting poing, (still using insecure and autopublish in dev) I have this:
//both/controllers/post.js
PostController = AppController.extend({
waitOn: function() {
return this.subscribe('posts');
},
data: function () {
return Posts.findOne({_id:this.params._id});
}
});
And in the router file
//both/router/router.js
Router.route('/posts/:_id', {
name: 'post'
});
The links on the main blog listing page, to the single posts are formated as follows.
//client/templates/blog/blog.html
<h3>{{ title }}</h3>
Then the helper file which seems to be the issue?
// /client/templates/post/post.js
Template.post.rendered = function() {
};
Template.post.helpers({
data: function () {
return Posts.findOne({_id:this.params._id});
}
});
Template.post.helpers({
createdAtFormatted: function () {
return moment(this.createdAt).fromNow();
}
});
I've tried this.params._id, request.params.id, req.params._id,
And other than setting an on click event and setting the _id in session (I don't like this idea, if it will even work efficiently/effectively). I'm stuck on ideas.

c3.generate not throwing error

I'm using c3 + d3 + javascript to create a line chart in a webpage. I managed to create a code that was working fine locally, but when I uploaded it to my server, the code stopped working. I explain the problem below:
Problem: c3.generate is not throwing errors when uploaded to server
JSFiddle: http://jsfiddle.net/xq6wmyvp/10/
var chart;
function initialize(path) {
try {
c3.generate({
bindto: '#chart',
data: {
x: 'label',
url: path,
type: 'line',
},
axis: {
x: {
type: 'categories',
label: {
text: 'days',
},
},
y: {
label: {
text: 'yield',
},
tick: {
format: d3.format(".2%")
}
}
},
});
} catch (err) {
return false;
}
return true;
}
var path1 = 'https://gist.githubusercontent.com/SamMorrowDrums/f571240047c0344a4af8/raw/433eae455570b64edcdc7ece39416b468b612f49/test.csv';
alert(initialize('blabla'));
Code explanation: the code (in the fiddle) has a function that initializes a chart with a line graph using some data. The path to the data is given as a variable to that function (which is called 'initialize(path)'). This function uses c3.generate to create the graph. If the data is not available or does not exist, c3.generate throws an error (this works locally, but not when uploaded to a server - this is the problem) and the function (initialize) returns false. If the data exists, the graph is loaded and 'initialize' returns true.
Problem Restated: after uploading the code to a server, the function 'initialize(path)' only returns 'true', even if the data is not available/non-existent.
I don't know how to solve this. Can you help me?
Thanks for reading!
(Github link to problem: https://github.com/masayuki0812/c3/issues/960)
As I stated in my comment, under the hood c3 is using a d3.xhr to retrieve the data. This is an async call meaning that it's outside of your try block.
Possible workarounds include:
1.) fix it in the c3 source code At line 1903, you see the error is being dropped.
2.) create a global error handler
3.) don't use c3's url option. Issue your own d3 xhr request (handle the error the proper way there) and if successful, then call c3.generate with the columns option. This is the way I'd do it.
d3.csv("path/to/file.csv", function(error, json) {
if (error){
// handle error properly
return;
}
c3.generate({
...
});
});

Error when doing ajax with grails and javascript

I have this jquery function on the client side...
$('#add-car').on('click', function() {
$.ajax({
type: 'POST',
url: 'cars/',
data: {brand: 'brand', model: 'model', price: 100,
registryYear:1999},
success: function(data) { console.log(data)},
dataType: 'json'
});
});
And this Grails code in the server side
class UrlMappings {
static mappings = {
"/cars/$id?"(controller: "cars") {
action = [GET:"list", POST:"save", DELETE:"delete", PUT:"edit"]
}
"/$controller/$action?/$id?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
}
}
import grails.converters.JSON
class CarsController {
def index() {
render ( Car.findAll() as JSON )
}
def save() {
def json = request.JSON
def car = new Car(json)
car.save()
render (json)
}
def delete() {
def car = Car.findById(params.id)
car?.delete()
render (car as JSON)
}
def edit() {
def car = Car.findById(params.id)
bindData(car, request.JSON)
render (car.save() as JSON)
}
}
But when the button #add-car is pressed it returns nothing... What Am I doing wrong?
This is about debugging method.
Please check if the request comes to your server or not. You can do that by adding some logs "Running here" into your requested action at the controller.
If the "Running here" get printed, the request was sent and you must find out how the server doesn't return the expected result.
If the log doesn't get printed, it means you must re-check your javascript. Using Firebug may help in uncovering some tricky javascript bugs.
By the way, I think you should use "jQuery" instead of "$" sign in your javascript. That is for avoiding conflicts with other libraries, such as:
jQuery('#add-car').click(function() {
....
});
well i dont code in grails
but your closest url mapping appears to be this "/cars/$id?"
which im assuming requires an ID
but from your javascript code you are not sending back any variable named Id

jquery.couchdb.js Ajax success/error not being called

I'm using jquery.couchdb.js to query my CouchDB database. The view I want to query has both map and reduce functions within. When sending the basic query as shown below:
$(document).ready(function() {
view_name = db_name+'/jobs_by_mod_stat'
options = {'group': 'true' , 'reduce': 'true' };
mod_stat = {};
$db.view(view_name , {
success: function(data) {
console.log(data)
for (i in data.rows) {
console.log(data.rows[i].value);
}
},
error: function(e) {
alert('Error loading from database: ' + e);
}
});
});
I see a sensible log for the data, indicating the query has been successful. However, changing the line:
$db.view(view_name , {
To
$db.view(view_name , options, {
I don't get a success outcome from the Ajax query, but an error message is not shown either. Firebug shows the query being sent, and the JSON data returned looks sensible:
{"rows":[
{"key":["template","completed"],"value":2},
{"key":["template","running"],"value":2},
{"key":["template","waiting"],"value":6}
]}
But the success function is not entered. Any ideas why I'm seeing this behaviour, I did wonder if it's a bug in jquery.couch.js (I have couchdb 1.1.0).
Cheers.
I've had a bit of trouble myself with the list function, until I went and looked through the source code of jquery.couch.js (the online documentation I found at http://bradley-holt.com/2011/07/couchdb-jquery-plugin-reference/ seems to be outdated).
Basically, the parameters for view and list are different, the list having an extra parameter for the options, instead of having everything under the same parameter as with views.
View:
$.couch.db('yourdb').view('couchapp/' + viewName, {
keys: ['keys here'],
success: function (data) {
}
});
List:
$.couch.db('yourdb').list('couchapp/' + listName, viewName, {
keys: ['keys here']
}, {
success: function (data) {
}
});

Categories