I want to pass the data from a fancytree to a generic handler so that I can save it for future use.
If I use this code:
function SaveTree() {
var tree = $('#TopTree').fancytree("getTree");
$.ajax({
cache: false,
url: "SaveTree.ashx",
data: { 'treeData': tree },
contentType: "application/json; charset=utf-8"
});
}
Then I get the following error from jquery.js:
JavaScript runtime error: Argument not optional
I have also tried:
var tree = $('#TopTree').fancytree("getTree").rootNode.children;
This gives the same error. I understand it is because 'tree' is not JSON. How can I convert the data to a JSON object?
EDIT:
If I use this code:
function SaveTree() {
var data = [];
var tree = $('#TopTree').fancytree("getTree").rootNode.children;
for (var i = 0; i < tree.length; i++) {
data.push(tree[i].title)
}
data = JSON.parse(JSON.stringify(data))
$.ajax({
cache: false,
url: "SaveTree.ashx",
data: { 'treeData': data },
contentType: "application/json; charset=utf-8"
});
}
I can get it to accomplish what I need, but is there not a built-in function for this in fancytree?
Okay, I don't really know a lot about FancyTree; however, I did some investigation and found this page http://wwwendt.de/tech/fancytree/demo/sample-api.html.
Try the tree.ToDict() option to see if that is what you're looking for.
This is the source code.
// Convert the whole tree into an dictionary
var tree = $("#tree").fancytree("getTree");
var d = tree.toDict(true);
alert(JSON.stringify(d));
Related
I actually got this working once but then I lost the code to do it and haven't been able to get it working again.
I am able to get the file pretty easily using a $.get(server filepath) and it gives me a bunch of crazy looking data...I've tried various methods to read in binary data as a blob and arrayBuffer but none of these have worked right.
how can I convert this into the actual data and then to JSON similar to what D3.parseCSV does?
I've tried the following:
$.ajax({
url: url,
method: 'GET',
dataType: 'binary',
processData: false,
responseType: 'arrayBuffer',
}).then(function (data) {
return data
}, function (error) {
alertify.error('There was an error retriving the data');
});
};
which gives me back the same data as just using $.get(url)
I've tried using Sheets.JS and did
$.get(filePath).then(function(data) {
XLSX.read(data, {Props: {type: "buffer"}})
})
and get a "Unrecognized type [object Object]" error.
If I use type: "binary" I get "undefined TypeError: Cannot read property '0' of undefined"
I've tried manipulating it with the following:
var buf = new ArrayBuffer(csvData.length * 2);
var bufView = new Uint16Array(buf);
for (var j = 0; j < csvData.length; j++) {
bufView[j] = csvData.charCodeAt(j);
}
var myData = buf;
I've tried using decoder("utf-8") and then decoder.decode(csvData)...
haven't gotten anything to work.
function getvalue1(){
debugger
var str=document.getElementById("SystemName").value;
var str1=document.getElementById("IP").value;
var str2=document.getElementById("SystemLevel").value;
var str3=document.getElementById("Ownera").value;
var str4=document.getElementById("Ownerb").value;
var str5=document.getElementById("SystemDesc").value;
var str6=document.getElementById("SystemDate").value;
var str7=document.getElementById("Recorder").value;
$.ajax({
type:"post",
url:"../AddServlet",
data: {
str:str,
str1:str1,
str2:str2,
str3:str3,
str4:str4,
str5:str5,
str6:str6,
str7:str7
},
async:false,
dataType:"json",
contentType:"application/json;charset=utf-8",
success:function (data) {
$.message.alert('successful');
},
error:function () {
alert("failedjump");
}
});
}
The previous is my js code, I wanna to take these "strs" into the servlet, I programmed servlet part to get the data is
enter image description here
But these strings are null in the servlet. How can I get the JSON data? thx!
getParameter will read standard form encoded data, not JSON data.
This wouldn't normally be a problem because you are sending standard form encoded data, not JSON.
However, since you have said contentType:"application/json;charset=utf-8", you are claiming to be sending JSON, so it isn't being parsed.
Remove that line.
I have a json data coming from wcf servicein jquery like this
GetBedTypeList1Result1 is function in wcf
{
"GetBedTypeList1Result":[
{"Code":23,"CompanyCode":null,"Decode":"1 Class New Born Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0},
{"Code":22,"CompanyCode":null,"Decode":"1st Class Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0},
{"Code":5,"CompanyCode":null,"Decode":"Classique Bed","DivisionCode":0,"LocationCode":0,"admDueDepAmt":0,"bedTypeCode":0,"caseTypeCode":0,"caseTypeDecode":null,"ptnClassCode":0,"ptnClassDecode":null,"rsvDueDepAmt":0}
],
"strErrMsg":"Y",
"chrErrFlg":"c"
}
I am calling service like below
function CallWcfService() {
//alert("CallWcfServicexxxx");
jQuery.ajax
(
{
type: Type,
url: Url,
data: parameters,
contentType: ContentType, // content type sent to server
dataType: DataType, //Expected data format from server
cache: "false",
crossDomain: true, //Same result if i remove this line
processdata: ProcessData, //True or False
success: function (msg)
{
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
}
);
}
function callService()
{
DataType = "json";
Type = "GET";
var par = 4;
parameters = null;
Url = "http://192.168.2.42/CWSERVERWCF/bedtypemasterService.svc/GetBedTypeList?callback=?";
parameters = "{'strErrMsg':'1'},{'chrErrFlg':'A'},{'pcompanycode':'0'},{'pdiv':'1'},{'ploc':'1'}";
// alert(parameters);
ContentType = "application/json; charset=utf-8";
ProcessData = true;
//alert("sssssasasadsds");
CallWcfService();
}
I am trying to fetch data but not getting lke below
function ServiceSucceeded(result)
{
if (DataType == "json")
{
var obj = jQuery.parseJSON(JSON.stringify(JSON.stringify(result)));
for (var x = 0; x < obj.length; x++)
{
}
}
}
In obj.length count of characters is coming and jQuery.parseJSON(result) is not working
Please help
If the result is json there is no need to parse it in this way. jQuery.ajax will return a javascript object if the datatype is set to json.
So in your ServiceSucceeded function you may operate on the result variable directly. If you are trying to iterate over the bed types change your for loop to something like this:
for (var i = 0; i < result.GetBedTypeList1Result.length; i++) {
// ...do stuff
// var bed = result.GetBedTypeList1Result[i]]
}
Try using JSON.parse(result) instead of: var obj = jQuery.parseJSON(JSON.stringify(JSON.stringify(result)));
Also, since you've mentioned the dataType as 'json' in your $.ajax call, your response should already be in JSON format with no parsing required.
I am having trouble getting the contents of JSON object from a JQery.ajax call. My call:
$('#Search').click(function () {
var query = $('#query').valueOf();
$.ajax({
url: '/Products/Search',
type: "POST",
data: query,
dataType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
for (var x = 0; x < data.length; x++) {
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
$(content).appendTo("#ProductList");
// updateListing(data[x]);
}
}
});
});
It seems that the JSON object is being returned correctly because "alert(data)" displays the following
[{"Id": "1", "Name": "Shirt"}, {"Id": "2", "Name":"Pants"}]
but when I try displaying the Id or Name to the page using:
content = data[x].Id;
content += "<br>";
content += data[x].Name;
content += "<br>";
it returns "undefined" to the page. What am I doing wrong?
Thanks for the help.
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.
I recommend you use:
var returnedData = JSON.parse(response);
to convert the JSON string (if it is just text) to a JavaScript object.
It works fine,
Ex :
$.ajax({
url: "http://localhost:11141/Search/BasicSearchContent?ContentTitle=" + "تهران",
type: 'GET',
cache: false,
success: function(result) {
// alert(jQuery.dataType);
if (result) {
// var dd = JSON.parse(result);
alert(result[0].Id)
}
},
error: function() {
alert("No");
}
});
Finally, you need to use this statement ...
result[0].Whatever
One of the way you can ensure that this type of mistake (using string instead of json) doesn't happen is to see what gets printed in the alert. When you do
alert(data)
if data is a string, it will print everything that is contains. However if you print is json object. you will get the following response in the alert
[object Object]
If this the response then you can be sure that you can use this as an object (json in this case).
Thus, you need to convert your string into json first, before using it by doing this:
JSON.parse(data)
Well... you are about 3/4 of the way there... you already have your JSON as text.
The problem is that you appear to be handling this string as if it was already a JavaScript object with properties relating to the fields that were transmitted.
It isn't... its just a string.
Queries like "content = data[x].Id;" are bound to fail because JavaScript is not finding these properties attached to the string that it is looking at... again, its JUST a string.
You should be able to simply parse the data as JSON through... yup... the parse method of the JSON object.
myResult = JSON.parse(request.responseText);
Now myResult is a javascript object containing the properties that were transmitted through AJAX.
That should allow you to handle it the way you appear to be trying to.
Looks like JSON.parse was added when ECMA5 was added, so anything fairly modern should be able to handle this natively... if you have to handle fossils, you could also try external libraries to handle this, such as jQuery or JSON2.
For the record, this was already answered by Andy E for someone else HERE.
edit - Saw the request for 'official or credible sources', and probably one of the coders that I find the most credible would be John Resig ~ ECMA5 JSON ~ i would have linked to the actual ECMA5 spec regarding native JSON support, but I would rather refer someone to a master like Resig than a dry specification.
Try the jquery each function to walk through your json object:
$.each(data,function(i,j){
content ='<span>'+j[i].Id+'<br />'+j[i].Name+'<br /></span>';
$('#ProductList').append(content);
});
you can use the jQuery parseJSON method:
var Data = $.parseJSON(response);
input type Button
<input type="button" Id="update" value="Update">
I've successfully posted a form with AJAX in perl. After posting the form, controller returns a JSON response as below
$(function() {
$('#Search').click(function() {
var query = $('#query').val();
var update = $('#update').val();
$.ajax({
type: 'POST',
url: '/Products/Search/',
data: {
'insert': update,
'query': address,
},
success: function(res) {
$('#ProductList').empty('');
console.log(res);
json = JSON.parse(res);
for (var i in json) {
var row = $('<tr>');
row.append($('<td id=' + json[i].Id + '>').html(json[i].Id));
row.append($('<td id=' + json[i].Name + '>').html(json[i].Name));
$('</tr>');
$('#ProductList').append(row);
}
},
error: function() {
alert("did not work");
location.reload(true);
}
});
});
});
I'm not sure whats going wrong with your set up. Maybe the server is not setting the headers properly. Not sure. As a long shot, you can try this
$.ajax({
url : url,
dataType : 'json'
})
.done(function(data, statusText, resObject) {
var jsonData = resObject.responseJSON
})
From the jQuery API: with the setting of dataType, If none is specified, jQuery will try to infer it with $.parseJSON() based on the MIME type (the MIME type for JSON text is "application/json") of the response (in 1.4 JSON will yield a JavaScript object).
Or you can set the dataType to json to convert it automatically.
parse and convert it to js object that's it.
success: function(response) {
var content = "";
var jsondata = JSON.parse(response);
for (var x = 0; x < jsonData.length; x++) {
content += jsondata[x].Id;
content += "<br>";
content += jsondata[x].Name;
content += "<br>";
}
$("#ProductList").append(content);
}
Use
dataType: 'json'
In .NET you could also return Json(yourModel) in your action method/API controller.
And parse the returned JSON as follows in the Jquery .ajax:
if you've a complex object: navigate to it directly.
success: function (res) {
$.each(res.YourObject, function (index, element) {
console.log(element.text);
console.log(element.value);
});
});
I've used Simon Whatley's code for the autocomplete plugin. Now, I need help in parsing a jSON data. Here is my code:
$("#country").autocomplete("data/country.cfm",{
minChars:1,
delay:0,
autoFill:false,
matchSubset:false,
matchContains:1,
cacheLength:10,
selectOnly:1,
dataType: 'json',
extraParams: {
format: 'json'
},
parse: function(data) {
var parsed = [];
for (var i = 0; i < data.length; i++) {
parsed[parsed.length] = {
data: data[i],
value: data[i].NAME,
result: data[i].NAME
};
}
return parsed;
},
formatItem: function(item) {
return item.NAME;
}
});
For example, I get this as my jSON string:
[{"name":"country1"},{"name":"country2"},{"name":"country3"}]
What I like to get as results, of course, are the values country1, country2, country3. However, what I get right now in the textbox when I type (e.g. I type "cou") is "undefined". If I click that, what shows in the textfield is the whole string [{"name":"country1"},{"name":"country2"},{"name":"country3"}].
I've also tried these but still not working:
jquery autocomplete, how to parse a json request with url info?
jquery autocomplete with json response
Help please. Thanks!
You can just simply use
var countries = JSON.parse(data);
Since you're using jQuery though, it's a bit safer to use jQuery.parseJSON() in case the browser doesn't have a native parser:
var countries = jQuery.parseJSON(data);