Populating a JSTree with JSON data obtained in AJAX - javascript

I'm trying to populate a JSTree with JSON data that I'm obtaining from a service (which is called using ajax). However, I am getting a "Neither data nor ajax settings supplied error" in the jquery.jstree.js file. Because of this the JSTree just displays a loading gif.
AJAX code (editted to try setting json to local variable test, then return test)
function getJSONData() {
var test;
$
.ajax({
async : true,
type : "GET",
url : "/JavaTestService/rs/TestService/MyFirstTestService?languageCode=en_US&version=2",
dataType : "json",
success : function(json) {
test = json;
},
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
test = "error";
}
});
return test;
}
JSTree code
var jsonData = getJSONData();
createJSTrees(jsonData);
function createJSTrees(jsonData) {
$("#supplierResults").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
});
After some debugging, I've found that jsonData is undefined when passed to the createJSTrees method. Am I retrieving that data correctly in the Ajax code?
Thanks in advance

jsonData is undefined because getJSONData() doesn't return a value. You can't rely on the return value from your $.ajax success handler unless you assign a variable local to getJSONData() that gets returned after the $.ajax call completes. But you want something like this, which also has the benefit of being asynchronous:
<script type="text/javascript">
$(function() {
$.ajax({
async : true,
type : "GET",
url : "/JavaTestService/rs/TestService/MyFirstTestService?languageCode=en_US&version=2",
dataType : "json",
success : function(json) {
createJSTrees(json);
},
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
function createJSTrees(jsonData) {
$("#supplierResults").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
});
}
</script>

I have not tested your approach before, where you supply the data parameter directly to the json_data plugin, so I won't be able to supply an answer to this scenario.
However, since you are using an AJAX call to get the data, can't you supply the AJAX call to JSTree and let it handle the call on its own? Here's how I've configured the AJAX call in my code:
(...)
'json_data': {
'ajax': {
'url': myURL,
'type': 'GET',
'data': function(node) {
return {
'nodeId': node.attr ? node.attr("id") : ''
};
}
},
'progressive_render': true,
'progressive_unload': false
},
(...)

Related

Ajax call is throwing an Invalid Character error

I am working on a Java application using Struts 1.2. I am facing a blocking error when I make an AJAX call to a Struts action.
The struts action, getInfos.html, is called successfully but after that when I make the AJAX call I get the following error in the console:
Invalid Character/parsing error
The data variable is a correct JSON format. Why would it trigger this error?
I've gone through all the similar questions online but I don't know why it's triggering an invalid character error.
$.ajax({
type: "POST",
url: "getInfos.html",
dataType: "json",
async: false,
cache: false,
data: {
Code: "code1",
type: "type",
mand: "mand",
signature: "signature"
},
success: function(data) {
console.log('succes');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
In the execute method that is handling the ajax request, i am calling the attributes using the request
final String code = (String) request.getAttribute("code");
final String signature = (String) request.getAttribute("signature");
final String type= (String) request.getAttribute("type");
/*
Making a call to a webservice using the attributes bellow,
using **response** Object
*/
if (reponse != null &&
(CodeReponseHttp.OK.equals(reponse.getCodeReponse()))) {
jsonObj.put(SUCCESS_CALL, true);
} else {
jsonObj.put(SUCCESS_CALL, false);
}
return new JsonResult(jsonObj);
But they are set to null; which means that the ajax data is not passed into the request, when I debug the execute method and I explicitly set values to these attributes everything works fine.
new JsonResult(jsonObj) is a generic class with a constructor that accepts a JSONObject
Like Rory McCrossan Comment it could be the response you got is not a json and your code expect a json response
When i comment dataType param it work fine
$.ajax({
type : "POST",
url : "getInfos.html",
//dataType : "json",
async: false,
cache: false,
data: JSON.stringify({
Code : "code1",
type : "type",
mand : "mand",
signature : "signature"}),
success : function(data){
console.log('succes');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
The problem had been solved, after debugging, the response type was not a JSON since there is a redirection to an error page if an exception is thrown, the exception was thrown because the data attributes were null, and it turned out that they are parametres not attributes, so getting the parameters solved the problem.
request.getParameter("code");
thank you all for your collaboration.

Ajax wont call MVC controller method

I have an AJAX function in my javascript to call my controller method. When I run the AJAX function (on a button click) it doesn't hit my break points in my method. It all runs both the success: and error:. What do I need to change to make it actually send the value from $CSV.text to my controller method?
JAVASCRIPT:
// Convert JSON to CSV & Display CSV
$CSV.text(ConvertToCSV(JSON.stringify(data)));
$.ajax({
url: '#Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { value : $CSV.text() },
success: function(response){
alert(response.responseText);
},
error: function(response){
alert(response.responseText);
}
});
CONTROLLER:
[HttpPost]
public ActionResult EditFence(string value)
{
try
{
WriteNewFenceFile(value);
Response.StatusCode = (int)HttpStatusCode.OK;
var obj = new
{
success = true,
responseText = "Zones have been saved."
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
var obj = new
{
success = false,
responseText = "Zone save encountered a problem."
};
return Json(obj, JsonRequestBehavior.AllowGet);
}
}
RESULT
You should change the data you POST to your controller and the Action you POST to:
data: { value = $CSV.text() }
url: '#Url.Action("EditFence", "Configuration")'
The $CSV is possible a jquery Object related to an html element. You need to read it's text property and pass this as data, instead of the jQuery object.
Doing the above changes you would achieve to make the correct POST. However, there is another issue, regarding your Controller. You Controller does not respond to the AJAX call after doing his work but issues a redirection.
Update
it would be helpful for you to tell me how the ActionResult should
look, in terms of a return that doesn't leave the current view but
rather just passes back that it was successful.
The Action to which you POST should be refactored like below. As you see we use a try/catch, in order to capture any exception. If not any exception is thrown, we assume that everything went ok. Otherwise, something wrong happened. In the happy case we return a response with a successful message, while in the bad case we return a response with a failure message.
[HttpPost]
public ActionResult EditFence(string value)
{
try
{
WriteNewFenceFile(value);
Response.StatusCode = (int)HttpStatusCode.OK;
var obj = new
{
success = true,
responseText= "Zones have been saved."
};
return Json(obj, JsonRequestBehavior.AllowGet));
}
catch(Exception ex)
{
// log the Exception...
var obj = new
{
success = false,
responseText= "Zone save encountered a problem."
};
return Json(obj, JsonRequestBehavior.AllowGet));
}
}
Doing this refactor, you can utilize it in the client as below:
$CSV.text(ConvertToCSV(JSON.stringify(data)));
$.ajax({
url: '#Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { value = JSON.stringify($CSV.text()) },
success: function(response){
alert(response.responseText);
},
error: function(response){
alert(response.responseText);
}
});
If your javascript is actually in a JS file and not a CSHTML file, then this will be emitted as a string literal:
#Url.Action("EditFile", "Configuration")
Html Helpers don't work in JS files... so you'll need to point to an actual url, like '/configuration/editfile'
Also, it looks like you're posting to a method called EditFile, but the name of your method in the controller code snippet is EditFence, so that will obviously be an issue too.
you dont need to add contentType the default application/x-www-form-urlencoded will work because it looks like you have a large csv string. So your code should be like this example
$(document).ready(function() {
// Create Object
var items = [
{ name: "Item 1", color: "Green", size: "X-Large" },
{ name: "Item 2", color: "Green", size: "X-Large" },
{ name: "Item 3", color: "Green", size: "X-Large" }
];
// Convert Object to JSON
var $CSV = $('#csv');
$CSV.text(ConvertToCSV(JSON.stringify(items)));
$.ajax({
url: '#Url.Action("EditFence", "Configuration")',
type: "POST",
dataType: "json",
data: {value:$CSV.text()},
success: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
Your problem is on these lines:
success: alert("Zones have been saved."),
error: alert("Zone save encountered a problem.")
This effectively running both functions immediately and sets the return values of these functions to the success and error properties. Try using an anonymous callback function.
success: function() {
alert("Zones have been saved.");
},
error: function() {
alert("Zone save encountered a problem.")
}

How to jQuery autocomplete with JSON?

For below JSON
{
"partnerNameListBeanStruts2Map": [
{
"firstName": "sachin",
"partnerId": 123
},
{
"firstName": "Ankit",
"partnerId": 234
}
]
}
What code should I wright to done jQuery autocompleter.
Here is my code.
Here I want autocomplete element's value is like sachin OR ankit and id is like like 123 OR 234 is id of element.
$(document).ready(function() {
$(function() {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "list.action",
type : "POST",
data : {
term : request.term
},
dataType : "json",
success : function(data)
{
****What should I write here to work my code?****
}
});
}
});
});
According to the doc, You should return your data with the response callback function.
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
$(function($) {
$("#search").autocomplete({
source : function(request, response) {
$.ajax({
url : "list.action",
type : "POST",
data : {
term : request.term
},
dataType : "json",
success : function(data)
{
***response (data) ;***
}
});
}
});
});

Sending a JSON object to Django backend through AJAX call

I have the following code (jQuery) to create a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
item.Code : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now this is my AJAX function:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ //I need my items object, how do I send it to backend server (django)??
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Now, my doubt is how do I send the 'item[]' object that I created to the backend? I do need to send both the item[] object and the variable 'calltype' which signals what made the AJAX call, as I have the same Django View (its the Controller equivalent for Django) in the backend being called by different AJAX functions.
How will my AJAX function look like?
Hey guys just got my answer right.
I used the following ajax function to get it right:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: items,
calltype: 'save',
'csrfmiddlewaretoken': csrf_token},
dataType: 'json',
// handle a successful response
success : function(jsondata) {
console.log(jsondata); // log the returned json to the console
alert(jsondata['name']);
},
// handle a non-successful response
error : function() {
console.log("Error"); // provide a bit more info about the error to the console
}
});
}());
So, this is sort of a self answer!!! :) Thanks a lot SO!!

Load ajax success data on new page

My ajax call hits the controller and fetches a complete JSP page on success. I was trying to load that data independently on a new page rather than within some element of the existing page. I tried loading it for an html tag but that didn't work either. I tried skipping the success function but it remained on the same page without success data. My ajax call is made on clicking a normal button in the form and the code looks like as shown below.
$.ajax({
url : '/newpage',
type : 'POST',
data : requestString,
dataType : "text",
processData : false,
contentType : false,
success : function(completeHtmlPage) {
alert("Success");
$("#html").load(completeHtmlPage);
},
error : function() {
alert("error in loading");
}
});
This should do:
$.ajax({
url : '/newpage',
type : 'POST',
data : requestString,
dataType : "text",
processData : false,
contentType : false,
success : function(completeHtmlPage) {
alert("Success");
$("html").empty();
$("html").append(completeHtmlPage);
},
error : function() {
alert("error in loading");
}
});
You can try this,
my_window = window.open("");
my_window.document.write(completeHtmlPage);
into your success.

Categories

Resources