Return json into ajax from Action Class - javascript

Am currently working on fullCalendar (jQuery plugin) and now stuck with silly issue but I couldn't overcome it .
Trying populate event details from database on Calendar page load . Here is my code ,
$('#calendar').fullCalendar({
defaultDate: '2016-03-12',
editable: true,
eventLimit: true, // allow "more" link when too many events
eventSources: [
getEvents()
]
});
function getEvents(){
alert("Inside get Events");
$.ajax({
url : "/FullCal/eventDetails.do",
dataType : 'json',
success : function(data){
alert(data)
}
});
}
Am using Struts framework and here is my action mappings,
<action path="/eventDetails" type="com.struts.action.CalendarInviteAction" >
<forward name="success" path="/Calendar.jsp" />
</action>
And my action class has the event details data in JSON format. My question is how to write the json data into ajax response(In simpler words , how to return the json data to ajax call) . Here is my action class UPDATED
public ActionForward execute(ActionMapping mapping , ActionForm form , HttpServletRequest request , HttpServletResponse response) throws Exception{
System.out.println("TEsting inside getEventDetails");
ArrayList<EventForm> arr = new ArrayList<EventForm>();
arr.add(new EventForm("HandOff Meeting" , new Date(), new Date(),"Meeting at HandOffBridge"));
Gson gson = new Gson();
String jsonString = gson.toJson(arr);
response.getWriter().write(jsonString);
return null;
}
jsonString contains eventDetails in JSON format , how to return this to ajax.
Please help me to achieve this.

Your ajax call seems fine. Just need to display ajax response in proper way.
events: function(start, end, timezone, callback) {
$.ajax({
url : "/FullCal/eventDetails.do",
dataType : 'json',
success : function(data){
callback(data);
}
});
}

A dataType : 'json' is used by [jQuery Ajax][1] to specify a data type that is expected to return by the success callback function when the action and result is executed, and a response returned from the server.
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
The URL should correctly point to the action mapping. Assume it will be in the default namespace, otherwise you should modify URL and mapping to add the namespace attribute.
<script type="text/javascript">
$(function() {
$("#dialog-form").dialog ({
autoOpen: true,
height: 500,
width: 750,
modal: true,
buttons : {
"Search" : function() {
$.ajax({
url : '<s:url action="part" />',
success : function(data) {
//var obj = $.parseJSON(data);
var obj = data;
alert(JSON.stringify(obj));
}
});
}
}
});
});
</script>

My first guess is why return null?
return null;
Just return the json string:
return jsonString;

Related

Unable to access json object property and value is displayed undefined in rails view

I've almost viewed similar kind of questions but my problem has not solved yet.
I've following codes.
Controller
def create
#task_list = TaskList.new(task_list_params)
if #task_list.save
respond_to do |format|
format.json { render json: #task_list}
end
else
return
end
end
Ajax Script
$(document).on('click','.add', function(){
count = 0;
user_id = $('#user_id').val();
var name = $('.new-list').val();
var current = $(this);
if(name){
$.ajax({
method: 'POST',
url: action,
dataType: 'JSON',
data: {
task_list: {
name: name,
user_id: user_id
}
}
}).success(function(response){
var data = JSON.stringify(response);
alert(data.id);
$(current).parent().parent().parent().before(
'<div class="col-md-12">'+
''+name+''+
'</div>'
);
$(current).parent().parent().parent().remove();
$('.add-list').show();
});
}else{
alert('please add title');
}
});
I just want to take id of the record just saved to the database through ajax post request. Here, in success function it just alerts undefined and I don't know what's going wrong.
This is sample response.
.success(function(response){
alert(response.id);
Remove JSON.stringify from your success function. Response is already in JSON format you can directly get the value from it.
JSON.stringfy converts javascript object into string.
Explanation
Your response is already in JSON format and you have used dataType: "JSON" in your AJAX call. Which will make it possible to transfer JSON data between server and client.
When your response is already in JSON format you can use its property without parsing it. I.e response.id
If you have not used dataType: "JSON" and you are passing json encoded response from your controller to view file you have to first decode the response to get its values.
var d = $.parseJSON(response);
alert(d.id);

controller can't return result in JSON object in ajax response

I have to call and fetch data from rest API with in every second. So I call the method with time 1 sec. As follows.
var myVar = setInterval(function(){ getData1() }, 1000);
Following is my Javascript function which call the controller.
function getData1(){
var url=CONTEXT_ROOT+"/login/getdashboarddata1";
$.ajax({
type: "POST",
url: url,
contentType: "application/json",
dataType: "json",
data:{},
success: function(data){
alert(data);
},
error: function(e){
//alert(e);
}
});
}
This is my controller code
#RequestMapping(value="/getdashboarddata1", method=RequestMethod.POST)
public JSONObject #ResponseBody getDashboardData1() throws JsonParseException, JsonMappingException, NullPointerException{
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/r_f22bc0ac1fe48bce/dataService/lastdata/";
String user = restTemplate.getForObject(url, String.class);
System.out.println("user: "+user);
JSONObject obj = null;
try {
obj = new JSONObject(user);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
If I run the program then jsp does not shows any alert. but if I change the return type of in controller to String then it shows proper JSON string in ajax response.
i.e. [{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]
If i carry this, then I am unable to get data from JSON string.
please tell me what is my issue. or is there any other way to do this.?
You have json array
[{"sno":"3618","data":"01","datetime":"2017-04-05 12:33:26.266"}]
Then access it using index:
data[0].sno
Simply return a String from getDashboardData1()
And then in AJAX success callback:
JSON.parse(data)[0]['sno'];
please tell me what is my issue. or is there any other way to do
this.?
You can't access attributes of a string literal, it has to be a json object.

ODataController converting json to array

This is in continuation with one of the previous questions
I have a OData Controller with the Action as :
[HttpPost]
[ODataRoute("PostUpdate")]
public async Task<string> PostUpdate(HttpRequestMessage eventsToUpdate)
{
//Do something
}
This is how I am calling the controller through the ajax call:
var eventsToUpdate = [];
for(i=0;i<5;i++)
{
//Build the data
var updatedT = {
"Id" : (Id)?Id:0,
"Desc" : CalculatedDesc
}
eventsToUpdate.push(updatedT);
}
Url = "Api/Odata/PostUpdate"
$.ajax({
url :Url,
type:"POST",
data:eventsToUpdate ,
dataType : 'json',
success : function(result) {
}
});
The problem is even after converting an array to json , the data is not available in the controller's action. This is what I did
var eventsToUpdate = JSON.stringify(eventsToUpdate);
But if I just pass
var updatedT = {
"Id" : (Id)?Id:0,
"Desc" : CalculatedDesc
}
I get the same data in action . What is the solution for this?
What seems to me your [HttpPost] is expecting a key named eventsToUpdate but it doesn't find in the posted request as it is not there because of:
data:eventsToUpdate , // which is eq to = data:[{},{}...],
better to send an object like:
data:{eventsToUpdate:eventsToUpdate} ,
//----^^^^^^^^^^^^^^---------this key will be captured at backend
contentType:'application/json', //<------you would need to add this
and another suggestion is to use traditional:true, if required.
Also, async Task<string> if return type is string then you need to change the dataType of the ajax too or you should return json from the WebMethod.

How to parse json object datalist in ajax sucess using javascript

i am trying to parse json datalist in ajax success bt it couldnot work. i have passed object containing list of data using json from controller to view,i help to parse json object in ajax success. i have attached my code below.
//return json object from controller
PurchaseDetails pd = new PurchaseDetails();
foreach (DataRow dr in dt.Rows)
{
pd.serialList.Add(new SerialInfo {
Machine_serial_no = dr[0].ToString(), macAddress = dr[1].ToString(), isMacPresent = _TD1.CheckMac(machineTypes_MTId),brandName=obj.brandName,machineName=obj.machineName,MachineModel=obj.MachineModel,modelId=modelId,machineId=obj.machineId,brandId=obj.brandId});
// pd.macaddressList.Add(new MacAddressInfo { MacAddress = dr[1].ToString() });
}
}
}
return Json(new {pd}, JsonRequestBehavior.AllowGet);
return Json(new {pd}, JsonRequestBehavior.AllowGet);
// my ajax code
$.ajax({
url: "/Import/ImportPurchase",
type: "POST",
data: function () {
var data = new FormData();
data.append("file", jQuery("#file").get(0).files[0]);
data.append("machineTypes_MTId", jQuery('#machineTypes_MTId').val());
data.append("modelId", jQuery('#searchValue').val());
data.append("modelName", jQuery('#searchid').val());
return data;
}(),
dataType:"JSON",
contentType: false,
processData: false,
success: function (data) {
alert(data.Machine_serial_no)
Your controller method is returning
return Json(new { serialObj = pd}, JsonRequestBehavior.AllowGet);
which is an object containing a name serialObj
So in the ajax success call back, you would need to access it using
success: function (data) {
var PurchaseDetails = data.serialObj;
Since PurchaseDetails contains a collection named serialList which is a collection of SerialInfo, then to access the value of the first Machine_serial_no, it would be
var serialNo = data.serialObj.serialList[0].Machine_serial_no;
However it would be easier to just use
return Json(pd, JsonRequestBehavior.AllowGet);
If you then want to access each Machine_serial_no property in the collection, use
success: function (data) {
$.each(data.serialList, function(index, item) {
var serialNo = item.Machine_serial_no;
you can use jQuery.parseJSON() to parse ajax response to JSON.
but seeing from your code, seems the response should already be in JSON because dataType parameter is already set to "JSON".
try this:
remove "()" after the ending bracket of function in "data" parameter.
try to console.log(data) and look at the response from your browser console,
the response might not be a valid json string.
If you are looking for convert js array to JSON then just use JSON.stringify() function. This will convert your JS variable data value to JSON format.
You can more find here.

ASP.NET MVC JsonResult return 500

I have this controller method:
public JsonResult List(int number) {
var list = new Dictionary <int, string> ();
list.Add(1, "one");
list.Add(2, "two");
list.Add(3, "three");
var q = (from h in list where h.Key == number select new {
key = h.Key,
value = h.Value
});
return Json(list);
}
On the client side, have this jQuery script:
$("#radio1").click(function() {
$.ajax({
url: "/Home/List",
dataType: "json",
data: {
number: '1'
},
success: function(data) {
alert(data)
},
error: function(xhr) {
alert(xhr.status)
}
});
});
I always get an error code 500. What's the problem?
Thank you
If you saw the actual response, it would probably say
This request has been blocked because
sensitive information could be
disclosed to third party web sites
when this is used in a GET request. To
allow GET requests, set
JsonRequestBehavior to AllowGet.
You'll need to use the overloaded Json constructor to include a JsonRequestBehavior of JsonRequestBehavior.AllowGet such as:
return Json(list, JsonRequestBehavior.AllowGet);
Here's how it looks in your example code (note this also changes your ints to strings or else you'd get another error).
public JsonResult List(int number) {
var list = new Dictionary<string, string>();
list.Add("1", "one");
list.Add("2", "two");
list.Add("3", "three");
var q = (from h in list
where h.Key == number.ToString()
select new {
key = h.Key,
value = h.Value
});
return Json(list, JsonRequestBehavior.AllowGet);
}
While JustinStolle's answer solves your problem, I would pay attention to the error provided from the framework. Unless you have a good reason to want to send your data with the GET method, you should aim to send it with the POST method.
The thing is, when you use the GET method, your parameters gets added to your request url instead of added to the headers/body of your request. This might seem like a tiny difference, but the error hints why it's important. Proxy servers and other potential servers between the sender and the receiver are prone to logging the request url and often ignore the headers and/or body of the request. This information is also often regarded as non important/secret so any data exposed in the url is much less secure by default.
The best practice is then to send your data with the POST method so your data is added to the body instead of the url. Luckily this is easily changed, especially since you're using jquery. You can either use the $.post wrapper or add type: "POST" to your parameters:
$.ajax({
url: "/Home/List",
type: "POST",
dataType: "json",
data: { number: '1' },
success: function (data) { alert(data) },
error: function (xhr) { alert(xhr.status) }
});

Categories