Dynatree init from custom json data - dynatree

There is an example on the website on how to construct child nodes from custom data:
$("#tree").dynatree({
[…]
onLazyRead: function(node){
$.ajax({
url: […],
success: function(data, textStatus){
// In this sample we assume that the server returns JSON like
// { "status": "...", "result": [ {...}, {...}, ...]}
if(data.status == "ok"){
// Convert the response to a native Dynatree JavaScipt object.
var list = data.result;
res = [];
for(var i=0, l=list.length; i<l; i++){
var e = list[i];
res.push({title: "" + i + ": " + e.fcurr + "-" + e.tcurr + ":" + e.ukurs,
icon: false});
}
// PWS status OK
node.setLazyNodeStatus(DTNodeStatus_Ok);
node.addChild(res);
}else{
// Server returned an error condition: set node status accordingly
node.setLazyNodeStatus(DTNodeStatus_Error, {
tooltip: data.faultDetails,
info: data.faultString
});
}
}
});
[…]
});
But there is no mention on how to do this for the initialization of the tree. I tried the following:
initAjax: {
type: "POST",
url: "/doSomething",
data: ...
contentType: "application/json; charset=utf-8"
success: function(data, textStatus){
// In this sample we assume that the server returns JSON like
// { "status": "...", "result": [ {...}, {...}, ...]}
if(data.status == "ok"){
// Convert the response to a native Dynatree JavaScipt object.
var list = data.result;
res = [];
for(var i=0, l=list.length; i<l; i++){
var e = list[i];
res.push({title: "" + i + ": " + e.fcurr + "-" + e.tcurr + ":" + e.ukurs,
icon: false});
}
// PWS status OK
node.setLazyNodeStatus(DTNodeStatus_Ok);
node.addChild(res);
}else{
// Server returned an error condition: set node status accordingly
node.setLazyNodeStatus(DTNodeStatus_Error, {
tooltip: data.faultDetails,
info: data.faultString
});
}
}
},
But then I get an error saying success doesn't work and to use some other method, but there is no documentation on how to use the other method? Can anyone help me out here? I tried using dataFilter to filter out my json string that is being returned, but that didn't work; I tried to use onPostInit and postProcess but don't know exactly what to do since there is no documentation: Do I return the data string after its been reformated, do I return the json version of the data? do I just do data = format(data)?
Any help would be greatly appreciated.
I will be having a lot of status codes and need to do different things based on the code; such as if I have code 1 it means I need to change the class of the node to have red text; or if I return code 2 it means there was an internal error and I need to add that to the node text; etc.

Related

Intervention image 405 method not found outside laravel

I used the Intervention image in my api. Then, I am trying to access it from my web, which is also Laravel but in different project. (I separated the web from the api due to some testing purposes for the api). But the image was successfully resized and saved to my public folder. But in my api there's an error then, when I comment the Image::make(), the error is gone. Why is that?
EDIT: Code from my api where I used Image::make()
$plant_image = $_FILES['image']['tmp_name'];
move_uploaded_file($plant_image, public_path()."\gallery\images\\".$_FILES['image']['name']);
$file_path = public_path() . "\gallery\images\\" . $_FILES['image']['name'];
$img = Image::make($file_path)->resize(216, 145);
$img->save();
Here is the code for the web
$(document).ready(function() {
$("form#addplant").submit(function() {
var form_data = new FormData($("#addplant")[0]);
$.ajax({
url: 'http://127.0.0.1/identificare_api/public/api/plants',
data: form_data,
type: "POST",
processData : false,
contentType: false,
success: function( json ) {
//console.log(json);
if (json.indexOf("error") > -1) {
var jsonparse = JSON.parse(json);
if(jsonparse.hasOwnProperty('error')){
location.reload(true);
alert("Code: " + jsonparse.error.code + "\n" + "Message: " + jsonparse.error.message);
}else{
location.reload(true);
alert("Please fill in empty fields");
}
}else{
window.location.href = "/home/"+ user_token;
alert("This item is currently under review! Please wait for admin's confirmation. Thank you!");
}
},
error: function(){
alert("Something's wrong with your api. Come on fix it!");
}
});
});
});

Display dynamic data with JSON API Jquery

I've been reading about Javascript for 2 days now and I'm still confused. I'm familiar with HTML and CSS. My goal is to display a dynamic value on my website. The data will be from an API call using JSON.
The URL i'm using displays info like this
{
"error" : 0,
"error_message" : "-",
"amount" : 35.63000
}
What I want to do is take the "amount" variable and display it on my website. So far I have managed to jumble a bunch of code together that barely makes sense to me. I'm probably using all the wrong syntax so I will continue to try and figure this out myself. All this does it displays a static variable in "div1". What is the best way to convert the variable from the API call to show instead.
$.getJSON('https://www.amdoren.com/api/currency.php?api_key=jbqe5fH8AykJTFbnyR7Hf3d2n3KVQR&from=USD&to=THB&amount=1', function(data) {
//data is the JSON string
});
////
var $items = $('#amount')
var obj = {}
$items.each(function() {
obj[this.id] = $(this).val();
})
var json = JSON.stringify(obj);
///
var obj = [ {
"error": 0,
"error_message": "-",
"amount": 35.60000 ///THIS IS OBVIOUSLY STATIC...
}]
var tbl = $("<table/>").attr("id", "mytable");
$("#div1").append(tbl);
for (var i = 0; i < obj.length; i++) {
var tr = "<tr>";
var td3 = "<td>" + obj[i]["amount"] + "</td></tr>";
$("#mytable").append(tr + td3);
}

Uploaded image on parse.com gives 403 error

I am trying to upload image to parse.com using REST API, and associating to an object as shown in docs
I am getting the fileUrl from phonegap / appgyver-supersonic camera api.
The Image is uploaded successfully and also associated successfully to the "receipt" object but accessing the url gives 403 error.
How do I access the URL and view the uploaded image, I get a white page (with broken image icon) and 403 error.
File :
http://files.parsetfss.com/68087456-8a5a-403a-820f-13912d2c0911/tfss-5d0edbdb-730b-4cd6-a44f-f0ce1e2ab120-pic.jpg
My receipt class has public write/read access.
Here is my code :
$scope.send = function(fileURL, mimeType){
function win(r) {
$scope.textvar = r;
var response = JSON.parse(r.response);
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
var req = {
method: 'POST',
url: 'https://api.parse.com/1/classes/receipt',
headers: {
'X-Parse-Application-Id':'XXXXXXXXXXXXX',
'X-Parse-REST-API-Key':'XXXXXXXXXXXXXXXX',
"Content-Type": "application/json"
},
data: {"name": "user_receipts",
"images": {
"name": response.name,
"__type" : "File"
}
}
}
$http(req).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("image association success ");
console.log(data);
console.log(headers);
console.log(status);
console.log(config);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
function fail(error) {
console.log("An error has occurred: Code = " + error.code);
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
console.log("upload error http-code " + error.http_status);
}
var uri = encodeURI("https://api.parse.com/1/files/pic.jpg");
var options = new FileUploadOptions();
options.fileKey="data-binary";
options.fileName=fileURL.substr(fileURL.lastIndexOf('/')+1);
options.mimeType=mimeType;
var headers = {"X-Parse-Application-Id": "XXXXXXXXXXXXXXXXX",
"X-Parse-REST-API-Key":"XXXXXXXXXXXXXXXX",
"Content-Type":"image/jpeg"};
options.headers = headers;
var ft = new FileTransfer();
ft.onprogress = function(progressEvent) {
if (progressEvent.lengthComputable) {
console.log("length : "+progressEvent.loaded/progressEvent.total);
} else {
console.log("loaded : "+progressEvent.loaded);
}
};
ft.upload(fileURL, uri, win, fail, options);
};
I have wasted 5 days on this already, Please Help.
I am no expert in either appgyver / phonegap or parse.com

Create complex JSON objects

Hi I have a question to the azure mobile Service custom API script.
I have a custom script to create a JSON Response.
First step was to get flat objects.
Thsi is my code:
var sql = "SELECT [Project].[id] AS [ID]," +
"[Project].[Name] AS [Name]," +
"FROM [Project]";
request.service.mssql.query(sql, [], {
success: function(results) {
if (results.length === 0) {
response.json(statusCodes.OK, results);
return;
}
var resultSet = [];
results.forEach(function(poi) {
resultSet.push(
{
ID: poi.ID,
Name: poi.Name,
RelatedObjects:
{
[
**???**
]
},
});
})
response.json(statusCodes.OK, resultSet);
}
});
This works very well. Now I want to extend my result objects by some sub objects from a releated table. But not simple singel sub properties (this is easy via join), I want to add collections of sub properties selected from another table.
But I don't know how to get the second query into my code? :(
I think it has to be on "???" marked position.
I want to use this JSON self creating code because my result sets are much more complex as the example shows.
Please help!
Ok I solve it with this messi code...
I'm sure there is a more elegant way to do this but I don't found it yet.
var sql = "SELECT [Project].[ID]" +
",[Project].[Name]" +
"FROM [Project]";
var sql2 = "SELECT [ID]" +
",[UniqueSN]" +
",[Name]" +
"FROM [DataLogger]" +
"WHERE [DataLogger].[ProjectID] = ?";
request.service.mssql.query(sql, [id], {
success: function(results) {
var resultSet = [];
results.forEach(function(poi) {
var loggerResultSet = [];
request.service.mssql.query(sql2, [poi.ID], {
success: function(results2) {
results2.forEach(function(logger) {
loggerResultSet.push(
{
ID: logger.ID,
Name: logger.Name,
UniqueSN: logger.UniqueSN,
});
})
resultSet.push(
{
ID: poi.ID,
Name: poi.Name,
Logger: loggerResultSet,
});
response.json(statusCodes.OK, resultSet);
console.log(JSON.stringify(resultSet));
}
});
})
}
});

How can I use a payload instead of form-data for log4javascript

I am bound to the restrictions of my webservice: It expects a json-payload!
So, doing something like
var ajaxAppender = new log4javascript.AjaxAppender("clientLogger");
var jsonLayout = new log4javascript.JsonLayout();
ajaxAppender.setLayout(jsonLayout);
log.addAppender(ajaxAppender);
won't work, as it creates two keys in the forms-collection (data and layout).
How can I, with built-in options, get a json-payload?
I've created a JsonAppender
function JsonAppender(url) {
var isSupported = true;
var successCallback = function(data, textStatus, jqXHR) { return; };
if (!url) {
isSupported = false;
}
this.setSuccessCallback = function(successCallbackParam) {
successCallback = successCallbackParam;
};
this.append = function (loggingEvent) {
if (!isSupported) {
return;
}
$.post(url, {
'logger': loggingEvent.logger.name,
'timestamp': loggingEvent.timeStampInMilliseconds,
'level': loggingEvent.level.name,
'url': window.location.href,
'message': loggingEvent.getCombinedMessages(),
'exception': loggingEvent.getThrowableStrRep()
}, successCallback, 'json');
};
}
JsonAppender.prototype = new log4javascript.Appender();
JsonAppender.prototype.toString = function() {
return 'JsonAppender';
};
log4javascript.JsonAppender = JsonAppender;
used like so
var logger = log4javascript.getLogger('clientLogger');
var jsonAppender = new JsonAppender(url);
logger.addAppender(jsonAppender);
According to log4javascript's change log, with version 1.4.5, there is no longer the need to write a custom appender, if the details sent by Log4Javascript suffice.
1.4.5 (20/2/2013)
- Changed AjaxAppender to send raw data rather than URL-encoded form data when
content-type is not "application/x-www-form-urlencoded"
https://github.com/DECK36/log4javascript/blob/master/changelog.txt
Simply adding the 'Content-Type' header to the AjaxAppender and setting it to 'application/json' is enough
ajaxAppender.addHeader("Content-Type", "application/json;charset=utf-8");
A quick test using fiddler shows that log4javascipt sends a collection of objects. Here's a sample of the payload:
[{
"logger": "myLogger",
"timestamp": 1441881152618,
"level": "DEBUG",
"url": "http://localhost:5117/Test.Html",
"message": "Testing message"
}]