Call 2 Ajax calls in one using Jquery Ajax - java

I have a problem in posting the selected values to the database with mismatching values.Here is the scenario where the ajax call maps to the respective Java function. The problem is, I am not getting correct selected values in the DB when the user logs in for the first time. Kindly provide a solution....
Here is my Jquery Ajax
if(selectedproductIds != '')
{
$.ajax({
url : "selectedProducts",
data : "selectedproducts="+selectedproductIds,
type : "POST",
success : function(data) {
}
});
$.ajax({
url : "<c:out value= "${saveDemoURL}"/>",
data : request,
type : "POST",
success : function(data) {
showNotification({
message : "",
type : "success",
autoClose : true,
duration : 5
});
resetForm();
alert("Demo Request Saved Successfully");
}
});
The first ajax call maps to this java function
#RequestMapping(value = "/selectedProducts")
public #ResponseBody
String getSelectedProducts(
#RequestParam(value = "selectedproducts") String[] selectedproducts,
Map<Object, Object> map) {
List<Product> selectedProd = new ArrayList<Product>();
for (String prod : selectedproducts) {
Product product = new Product();
product.setId(Integer.parseInt(prod));
selectedProd.add(product);
}
if (!Util.isEmpty(selectedProd)) {
map.put("selectedproducts", selectedProd);
}
for (Product product: selectedProd) {
LOGGER.info("Demo ID:"+ " List of selected products:"+product.getId());
}
selectedProdList = selectedProd;
return "success";
}
The second Ajax call maps to this java function
#RequestMapping(value = "/saveDemo")
public #ResponseBody
Map<Object, Object> saveDemo(#ModelAttribute("demoBean") DemoBean demoBean,
Model model, Map<Object, Object> map) {
Map<Object, Object> output = null;
Demo demo = new Demo();
try{
......
}
catch{.....}
return output;
}

Change your code to this format: $.ajax().ajax;:
if(selectedproductIds != '')
{
$.ajax({
url : "selectedProducts",
data : "selectedproducts="+selectedproductIds,
async: false,
type : "POST",
success : function(data) {
}
}).ajax({
url : "<c:out value= "${saveDemoURL}"/>",
data : request,
async: false,
type : "POST",
success : function(data) {
showNotification({
message : "",
type : "success",
autoClose : true,
duration : 5
});
resetForm();
alert("Demo Request Saved Successfully");
}
});

I'm not 100% certain I understand what your two functions are doing, but if I'm right and you're trying to perform something which would normally be wrapped in a transaction then you do not want to coordinate that from the front-end at all. A classic example of a transaction is taking money out of one person's account and putting it into another. If that process gets interrupted in the middle due to power failure, laptop reboot, network problems, etc. then the whole thing needs to go back to its original state, otherwise money can just disappear from one account and never go anywhere.
I want to refer you to this question: jQuery deferred chaining problems
It's a little different because the author has already figured out that promises may be a key to getting things to happen together. But notice that I answer it twice. The second time is to specifically to explain that transactions should never be coordinated from the front-end. If you have two database operations that must always complete together then you must have only one API call which receives all the data needed for both calls and you do them together on the back-end. Technically, even then you should use something like database transactions on the back-end to wrap them so a power failure back there won't leave you with half an operation completed. But failures in the middle of your multi-step processes are 1000% more likely if you try to execute them across the network between a browser and a server. Get that logic into the server where it belongs.

Related

Ajax call returns string for Highcharts series but result is wrong (parsing error?)

I'm developing a Java Spring-Hibernate application that uses Highcharts. I've got a JavaScript function that, when called, it makes an Ajax call to get the chart data (series) and creates the chart with it:
<!-- Stacked bar chart -->
<script type="text/javascript">
//Function that plots the highcharts chart
function plot(park) {
$.ajax({
type: "get",
url: "MainView/report/datagaps/" + park,
dataType: "text",
error: function (error) {
console.log(error);
alert('Error while requesting datagaps for ' + park + ' : ' + error);
},
success: function (result) {
$("#chart" + park).highcharts({
chart: {
type: 'column'
},
series: result
});
}
});
}//END_FUNCTION
</script>
I've removed most of the plot options code, so you see the most relevant code above. There is a model method that deals with this request:
#RequestMapping(value = "/datagaps/{parkName}", method = RequestMethod.GET)
public #ResponseBody String datagaps(#PathVariable String parkName, Map model, HttpSession session) {
LOGGER.debug("Successfully called datagaps for '" + parkName + "'");
LOGGER.debug((String) session.getAttribute("chartData"+parkName));
return (String) session.getAttribute("chartData"+parkName);
}//END_METHOD
The method is quite simple: a session string variable is returned, which is the one that should be used in series: result.
The thing is that this generates an unexpected result:
However, if I set a model variable session.setAttribute("chartData" + park, rrdao.getParkData().get(park)); before loading the form and I use it instead of the result like series: ${chartDataAA}, it works:
This is quite weird, since the data used is exactly the same: both ajax call and model variable come from the same place, and they are logged before beign send, which allows me to be sure data is good. This data has a format like [{name:'AA01', data: [[1412114400000,0],[1412200800000,0],[1412287200000,0],[1412373600000,0],[1412460000000,0],[1412546400000,0],[1412632800000,0]}]
I bet is some kind of string parsing problem when it is returned from the ajax call, perhaps due to the single quotations, but I don't know how to deal with it.
Please help!
Maybe it is misspelling, but your single serie which you have as missing bracket in data array. It should be: [{name:'AA01', data: [[1412114400000,0],[1412200800000,0],[1412287200000,0],[1412373600000,0],[141246‌​0000000,0],[1412546400000,0],[1412632800000,0]] }]
Change: dataType: "text" to dataType: "json"
Then in the controller if you use jackson json just return a List

How to update session attribute

I have some session attributes being saved. I have a jsp page on which a call to a servlet is made through. This servlet updates one of the session variable but I am not able to see the reflection of these changes in my jsp.Pls help.
In My servlet
List<DriverList> abc = dao.getABC();
request.getSession().removeAttribute("abc");
request.getSession().setAttribute("abc", abc);
In my jsp
function update()
{
var url = "updateServlet";
var req = $.ajax({
type: 'GET',
url: url,
cache: false,
type: "GET",
success: function()
{
latlng = [];
latlng = [<c:forEach var="test" items="${abc}">
[<c:out value="${test.latitude}"/>,<c:out value="${test.longitude}"/>,"<c:out value= "${test.name}" />",<c:out value="${test.cellNo}"/>],
</c:forEach> ];
},
error: function (status) {
}
});
}
The value of ${abc} is same as before. How to get the new value ?
The exact flow -
when login servlet is called abc value as sessionAttribute is set.
Now this redirects to base.jsp. I use abc for the first time. Now after every 30 seconds this update() function is called. This update function calls a servlet through ajax where the session attribute abc is updated.
In the success function of ajax request I want to use this new abc value but getting the old one again.
To access the abc variable in the JSP try:
${sessionScope.abc}
Also note that removing before setting is usually redundant. So:
request.getSession().removeAttribute("abc");
request.getSession().setAttribute("abc", abc);
Can simply become:
request.getSession().setAttribute("abc", abc);
I had similar problem.
It turned out that when you use
HttpSession
object in your controller, it shouldn't be annotated using
#SessionAttributes

How to create a Java Servlet for a given jQuery.ajax () call?

I have a file called wfd.proxy.js that contains the following lines of code :
if (!WFD) { var WFD = {}; };
if (!WFD.Proxy) { WFD.Proxy = {}; };
WFD.Proxy =
{
SERVICE_URL : "/delegate/WFD/WFService?",
PDF_SERVICE_URL : "/delegate/pdf-exporter?",
DATA_TYPE : "json", // used by jQuery
DATA_TYPE_EXT : "ajax", // used by ExtJs
DATA_TYPE_TXT : "text", // used for tests
SaveWorkflow : function(code)
{
jQuery.ajax({
url: WFD.Proxy.SERVICE_URL + "task=savemodel",
data: { code : code },
dataType : WFD.Proxy.DATA_TYPE,
type: 'POST',
success : function(data) {
WFD.Proxy.OnSaveWorkflowCallback(data);
},
error : function(jqXHR, textStatus, errorThrown) {
alert("Errore di comunicazione: " + errorThrown);
}
});
}
,
WFD.Proxy.OnSaveWorkflowCallback = function(data)
{
/*
data.response
data.message
data.model_new_id
data.idsNodes[i].original_id
data.idsNodes[i].new_id
*/
}
};
I have written the code that converts an xml file to JSON format. The JSON string that i get from the code I've written until now, should be passed as the code parameter of SaveWorkflow : function(code) .
I'm not really sure what do I have to do at this point.
I did some searches and saw that jQuery.ajax() calls where manipulated using Java Servlets ...
Any idea how to resolve this please?
Thanks in advance
What you've written is client side code (i.e. executes in your browser). The part that's missing is the server side. Your "ajax call" is making an asynchronous connection to a web server, using this URL:
/delegate/WFD/WFService?task=savemodel&code=xxxx
xxxx is the value of the code variable. Your javascript is expecting a text string as response from this URL.
You don't need a servlet per se to handle this. Any web server that accepts the ajax URL and returns the required data will do (e.g. PHP...)
If you need a servlet and you don't know how to build one, I think you have a lot of reading to do.
I suggest:
https://www.google.be/search?q=my+first+servlet

Jquery autocomplete issue

I am new to jQuery and am trying to use the autocomplete widget with an ajax call to my database.
I am able to call the database, returned ArrayList of string values, and converted the response as a JSON object using org.codehaus.jackson.map.ObjectMapper (Do I need to use something else?).
When I put an altar, I can see results as pure strings with comma delimiter, but am not able to see a suggestion list with autocomplete.
Java code that returns the JSON object using org.codehaus.jackson.map.ObjectMapper:
response.setContentType("application/json");
response.setHeader("cache-control", "no-cache");
ArrayList polNo = doa.getPolicyData(ajaxForm.getPolicyNumber());
ObjectMapper mapper = new ObjectMapper();
OutputStream out = response.getOutputStream();
mapper.writeValue(out, polNo);
JavaScript code:
$( "#policyNumber" ).autocomplete({
source: function (request,response){
$.ajax({
type: "POST",
url: "/NB/AjaxSubmit.do",
dataType: "json",
data: {policyNumber: request.term},
success: function (data) {
alert(data);
}
});
},minLength: 3
});
alert data showing as : TMA412732,TMA412733,TMA412734
In above code, I have returned ArrayList of string values and was able to show in autopopulate. I have enhanced the above code to return list of person objects that has first name, last name etc. Now when user typing the firname or last name in the autopopulate , I would like to suggest First name, LastName Middle.
Could someone help to enhance this? Thanks!
success: function(data) {
response(data);//u forgot to set data on response
}
Change success function like
success: function (data) {
response(data); //u forgot to set data on response
}

Should I use 'error:' callback or just check the returned 'data' in ajax call?

Here is how I am submitting my ajax request :
$.ajax({
url: "myurl",
type: 'POST',
dataType : "text",
data : ({
json : myjson
}),
success : function(data) {
if(data == 'success'){
//alert('success');
}
else {
alert('fail');
}
};
}
});
Within java im just returning the string which contains either 'success' or 'fail' depending on wether or not a exception is thrown :
pseudo code :
try {
return "success";
}
catch (Exception e){
return "fail";
}
Will this suffice instead of using the ajax error callback ? If not sufficient how should this callback be used and what extra failure conditions is it checking for ?
error : function() {
alert ('error');
}
The purpose of error callback is different: jQuery will call that function if an error occurred during sending request or receiving a response. For example, if your server doesn't return an answer but instead "500 Internal Server Error" (or any other error for that matter), then success callback function will not be called at all. If you define the error callback, then it will be called - and you'll have some chance of figuring out what the error was.
Just because your server works perfectly doesn't mean that a communication error cannot occur: for example, it could be "Gateway timeout", "No route to host", etc.
Finally, if you declare dataType: json (I know it doesn't apply in your example) but the returned data cannot be parsed (i.e. it's not a well-formatted JSON string), your error function will be called and not your success function.

Categories