Unable to get value in Ajax response - java

The servlet which receives request --
Gson gson = new Gson();
JsonObject myObj = new JsonObject();
LoginBean loginInfo = getInfo(userId,userPwd);
//System.out.println("00000000-----------"+loginInfo.userId);
JsonElement loginObj = gson.toJsonTree(loginInfo);
if(loginInfo.getUserId() == "GUEST!"){
myObj.addProperty("success", false);
}
else {
myObj.addProperty("success", true);
}
myObj.add("login", loginObj);
System.out.println(":::::"+myObj.get("success"));
out.println(myObj.toString());
out.close();
Here is the js file -----
function loadScript(url, callback)
{
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
loadScript("js/json2.js", myJSCode);
var myJSCode = $(document).ready(function() {
$("#loginForm").submit(function(e){
e.preventDefault();
});
$("#login").click(function(e){
dataString = $("#loginForm").serialize();
var id = $("input#id").val();
var pwd = $("input#pwd").val();
dataString = "id=" + id + "&pwd="+pwd;
$.ajax({
type: "POST",
url: "login",
data: {
id : id,
pwd : pwd
},
dataType: "json",
success: function( data, textStatus, jqXHR) {
if(data.success){
$("#ajaxResponse").html("");
$("#ajaxResponse").append("<b>Welcome</b> " + data.login.id + "<br>");
//alert("#ajaxResponse" + data.login.id);
alert(data['id']);
alert(data['pwd']);
}
else {
$("#ajaxResponse").html("<div><b>Login Credentials are invalid!</b></div>");
}
}
});
I am getting the ajaxResponse if I am going with 1 element i.e 'id' but when I tried to get both the response I am getting value as undefined. I have tried with data.login.id & data[id] but unable to get desired output. Any help will be appreciated. Even I have tried with JSON.Stringify().

$.ajax({
type: "POST",
url: "login",
data: {
id : id,
pwd : pwd
},
...
This has data passed to ajax is not the same as the data in
success: function( data, textStatus, jqXHR) {
if(data.success){
...
In this success callback data is response from the server and it has a different (or same structure) based on data that server returns to you.
if you want to print the value from ajax call, you need to use just id
$("#ajaxResponse").append("<b>Welcome</b> " + id + "<br>");
I see you are trying to use "data.login.id" can you check what is real structure of data in response? add console.log(data) or put breakpoint that callback, or simple add debugger; code, it will stop code in that line for you without adding breakpoint.

Thanks Alex. I will give you +1 for the line
$("#ajaxResponse").append("<b>Welcome</b> " + id + "<br>");
Though it is working when I use:
data: {
id: $('#id').val(),
pwd: $('#pwd').val()
},
Without changing my code to this one the line was not working. Thanks for the suggestion.

Related

Springboot controller expect to load .jsp instead of return data

I have a page which contain a combo boxes. onChange of first combo box makes a url call and collect data and generate another combo box with these data.
This is my onchange function:
function seatValue() {
var postid = $('#postid').val();
var dsgid = $('#dsgid').val();
var html2 = '<option value="0" selected>--select--</option>';
$.ajax({
url : 'loadSeat?postid='+postid+'&dsgid='+dsgid, //data
type : 'POST',
dataType : 'json',
success : function(data) {
alert("success!");
for (var i = 0, len = data.length; i < data.length; ++i) {
var item = data[i];
html2 = html2
+ "<option value='"+item.postId+"'>"
+ item.postName + "</option>";
}
$("#postid").html(html2);
$("#scheduleButton").css("display","block");
},
error : function() {
alert("Error!")
}
});
}
Controller :
#RequestMapping(value = { "/loadSeat" }, method = RequestMethod.POST)
public List<SeatValuesModel> LoadSeat(#RequestParam("postid") String postid,
#RequestParam("dsgid") String dsgid) {
List<SeatValuesModel> seatvalues = new ArrayList<>();
seatvalues= employeeService.getSeat(postid, dsgid);
System.out.println("seatvalues "+seatvalues.get(0).getPostName());
return seatvalues;
}
this is the response I'm getting in the console
why this expecting a .jsp . and on my ajax call it always error what is printing. There is some issue with my controller. Pls do help...

How to get value from jquery each loop when controller returns list

I have list and return from controller and i'm trying to show in a mvc view using jquery each loop function.I can get to list and send to view but when jquery loop start i cannot get index and value.I checked Console and Sources,values are there.
This is my controller codes
public JsonResult electric()
{
int id = Convert.ToInt32(Session["id"]);
string cs = "data source=LNPC;initial catalog=db;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework";
SqlConnection connection = new SqlConnection(cs);
SqlCommand command = new SqlCommand("electrcic_bills", connection);
command.CommandType = System.Data.CommandType.StoredProcedure;
command.Parameters.AddWithValue("#id", id);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
List<analiz> TestList = new List<analiz>();
analiz electric;
while (reader.Read())
{
electric= new analiz();
electric.jan= Convert.ToDouble(reader["jan"].ToString());
electric.feb= Convert.ToDouble(reader["feb"].ToString());
electric.march= Convert.ToDouble(reader["march"].ToString());
electric.april = Convert.ToDouble(reader["april"].ToString());
TestList.Add(electric);
}
return Json(new { List = TestList }, JsonRequestBehavior.AllowGet);
}
Jquery codes
$("#electric").click(function () {
$("canvas#myCharts").remove();
$("#canvas1").append('<canvas id="myCharts" width="200" height="200"></canvas>');
$.ajax({
type: "GET",
url: "/MainController/electric",
dataType: "json",
success: function (List) {
var data = List.List;
$.each(data, function (index, value) {
alert(data);
});
},
});
});
With this method i cannot get value but when i write electric.push(List.List[0].jan._bills_electric) like this i can get value manualy perfctly.
This my Source codes from browser
Local List:List: Array(1)
0:
jan_bills: null
jan_bills_electric: 135
dec_bills: null
dec_bills_electric: 60
You are using List word in your return Json() statement. This may be ambiguous for Java.
Try using another name with camel case typography to solve the problem.
In your Javascript, try to use
var data = List["List"];
instead of
var data = List.List;
Okey i found my answer and where l am wrong.
First- there is nothing wrong in my controller
Second- in each loop function,my array not only array,it is array in OBJECT.I've found this link and try each loop in a each loop and i got my items from jquery loop.
var json = [
{ 'red': '#f00' },
{ 'green': '#0f0' },
{ 'blue': '#00f' }
];
$.each(json, function () {
$.each(this, function (name, value) {
console.log(name + '=' + value);
});
});

Javascript won't post into DIV?

So the console shows that the data is being sent and received but for some reason (probably the conditional) nothing is posted in the specified div tag
var var_IDdatacheck = <?php echo $javaid; ?>;
var var_IDcheck = parseInt(var_IDdatacheck);
//datacheck
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck() {
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck, javaid: var_IDcheck},
success: function (check) {
console.log(check);
var verify = JSON.parse(check);
if (var_IDcheck < verify.id) {
var_IDcheck = verify.id;
for (var i=0;i<var_IDcheck;i++){
$('#datacheck').html(verify[i]);
}
}
setTimeout(activitycheck(),5000);
},
error: function(check) {
console.log(check);
setTimeout(activitycheck(),5000);
}
});
}
$(document).ready(function() {
activitycheck();
}); // document ready
Your id from the JSON is a string, and you are comparing it with an integer
try
var verify = JSON.parse(check);
if (var_IDcheck < parseInt(verify.id)) {
var_IDcheck = parseInt(verify.id);
for (var i=0;i<var_IDcheck;i++){

FullCalendar - Adding Multiple Events or Add Event Source

I have looked through the post in stackoverflow to add events into FullCalendar, however I am really new and find it really difficult to understand without an example. In short, is anyone here able to dumb it down for me, in order to add an array of objects into the FullCalendar?
I would like to add appointments that I have created Appointment(Date date, String name, String phoneNo). So they are retrieved in list:
PersistenceManager pm = PMF.get().getPersistenceManager();
String query = "select from " + Appointment.class.getName();
query += " where merchant == '" + session.getAttribute("merchant") + "'";
List<Appointment> appointment = (List<Appointment>) pm.newQuery(query).execute();
How am I able to populate the FullCalendar plugin with the list I obtained? Thanks a lot!
if anyone encounters the same problem as I do - you have a list of java objects and want it to populate FullCalendar, here's the solution:
JSP Page
$(document).ready(function() {
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
var title = prompt('Event Title:');
if (title) {
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
editable: true,
eventSources: [
{
url: '/calendarDetails',
type: 'GET',
data: {
start: 'start',
end: 'end',
id: 'id',
title: 'title',
allDay: 'allDay'
},
error: function () {
alert('there was an error while fetching events!');
}
}
]
});
});
Please take not of the URL, it is the servlet URL
Servlet
public class CalendarServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String something = req.getSession().getAttribute("merchant").toString(); //get info from your page (e.g. name) to search in query for database
//Get the entire list of appointments available for specific merchant from database
//Convert appointment to FullCalendar (A class I created to facilitate the JSON)
List<FullCalendar> fullCalendar = new ArrayList<FullCalendar>();
for (Appointment a : appointment) {
String startDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(a.getDate());
startDate = startDate.replace(" ", "T");
//Calculate End Time
Calendar c = Calendar.getInstance();
c.setTime(a.getDate());
c.add(Calendar.MINUTE, 60);
String endDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(c.getTime());
endDate = endDate.replace(" ", "T");
FullCalendar fc = new FullCalendar(startDate, endDate, a.getId(), a.getName() + " # " + a.getPhone(), false);
fullCalendar.add(fc);
}
//Convert FullCalendar from Java to JSON
Gson gson = new Gson();
String jsonAppointment = gson.toJson(fullCalendar);
//Printout the JSON
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
try {
resp.getWriter().write(jsonAppointment);
} catch (IOException e) {
e.printStackTrace();
}
}
}
if you need more info on JSON or GSON, check the comments above.
Melvin you have tones of examples here in Stack, try searching for add event sources.
From my experience im fullcalendar, you can add events through JSON, well formed XML and array's and i think thats it. You can use ajax calls do retrieve does 3 types of formats.
In your server side you should create a method to return a String already with the XML/JSON/array built so you can pass to you ajax call.
take a look at https://github.com/mzararagoza/rails-fullcalendar-icecube
this is done in rails but i think what you are looking for is
dayClick: function(date, allDay, jsEvent, view) {
document.location.href=new_event_link + "?start_date=" + date;
},
full jquery
$('#calendar').fullCalendar({
dayClick: function(date, allDay, jsEvent, view) {
document.location.href=new_event_link + "?start_date=" + date;
},
header: {
left: 'prev,today,next',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
editable: false,
ignoreTimezone: false,
select: this.select,
eventClick: this.eventClick,
eventDrop: this.eventDropOrResize,
eventSources: [
{
url: '/event_instances.json',
data: {
custom_param1: 'something',
custom_param2: 'somethingelse'
},
error: function() {
alert('there was an error while fetching events!');
}
}
],
eventResize: this.eventDropOrResize
});

how to return multiple json objects from java servlet using one ajax request

I am building web application using jsp and servlet, I send ajax request from jsp and I want to return two json objects from servlet. I tried to do the following but the code did not work.
// in jquery I wrote this code
var id = $(this).attr('id');
var paramenters = {"param":id};
$.getJSON("MyServlet", paramenters, function (data1,data2){
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
// in the servlet I wrote this code
String json1 = new Gson().toJson(object1);
String json2 = new Gson().toJson(object2);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(json1);
response.getWriter().write(json2);
can someone help me???
You should do it like this:
Server side:
String json1 = new Gson().toJson(object1);
String json2 = new Gson().toJson(object2);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
String bothJson = "["+json1+","+json2+"]"; //Put both objects in an array of 2 elements
response.getWriter().write(bothJson);
Client side:
$.getJSON("MyServlet", paramenters, function (data){
var data1=data[0], data2=data[1]; //We get both data1 and data2 from the array
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
Hope this helps. Cheers
Wrap them in JSON array:
[ {..}, {..}, {..}]
or, wrap them in another object:
{ "result1":{..}, "result2":{..} }
You could return a JSON array with both objects as elements of the array. Have your servlet return JSON that has a structure like this one:
[{"name": "object1"}, {"name": "object2"}]
Then your javascript code can be something like this:
$.getJSON("MyServlet", paramenters, function (data){
var data1 = data[0];
var data2 = data[1];
$("h3#name").text(data1["name"]);
$("span#level").text(data1["level"]);
$("span#college").text(data2["college"]);
$("span#department").text(data2["department"]);
});
you're going to need to put both into a single json string like so
response.getWriter().write("[");
response.getWriter().write(json1);
response.getWriter().write(",");
response.getWriter().write(json2);
response.getWriter().write("]");
this puts them in a json array
you could also put them in a json object
response.getWriter().write("{\"object1\":");
response.getWriter().write(json1);
response.getWriter().write(",\"object2\":");
response.getWriter().write(json2);
response.getWriter().write("}");
#Edgar 's answer works for me. But I think we should avoid to form the array by ourselves, so I suggest to use a list. The codes will be something like this:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
...
resp.setContentType("application/json");
resp.setCharacterEncoding("utf-8");
ArrayList<Object> obj_arr = new ArrayList<Object>();
obj_arr.add(obj1);
obj_arr.add(obj2);
Gson gson = new Gson();
String tmp = gson.toJson(obj_arr);
resp.getWriter().write(tmp);
}
And in the front end, for the data we get, we can use data[0] to retrive obj1 and data[1] to retrive obj2. The codes will be something like this (I am using ajax here):
$('#facts_form').submit(function (e) {
e.preventDefault();
var data = new FormData(this);
var url = 'import';
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false,
async: false,
cache: false,
success: function (data) {
for (var i = 1; i < data.length; i++){
//do whatever
}
},
error: function (xhr, status, error) {
alert(status + "\n" + error);
}
});
});

Categories