How I send the result of the AJAX back to the JSP? - javascript

I post some via AJAX in my servet from my jsp
$.ajax({
url: 'myServlet?action=FEP',
type: 'post',
data: {machine: i, name: txt}, // i, txt have some values.
success: function (data) {
alert('success');
}
});
and in my Serlvlet
String jspAction = request.getParameter("action");
//...
if(jspAction.equals("FEP")){
int idMachine = Integer.parseInt(request.getParameter("machine"));
String name = request.getParameter("name");
double value = actions.getValue(idMachine, name); //<-- this variable I want to send it back to the JSP.
}
The data are sent succesfully. However I haven't understand how I send back the vaule to the jsp..

returning a string would go as follows:
response.getWriter().write("a string");
return null;
If you want to return json, you can use many libraries like: http://www.json.org/
This would result in something like following code:
response.setContentType("application/json");
JSONObject jsonObject = new JSONObject();
double aDouble = 38d;
jsonObject.put("returnValue", aDouble);
response.getWriter().write(jsonObject.toString());
return null;

Use
response.getWriter().write(value);
return null;
And in your ajax success block access the value.
See the following link for more understanding http://www.javacodegeeks.com/2014/09/jquery-ajax-servlets-integration-building-a-complete-application.html

Related

Trying to make an Ajax call to a web form method and getting an internal server error. I have tried almost all solutions to similar questions

The function getClientData() gets called from one of the anchor tags in a grid's column. The anchor tag has a couple of Data-Tags which are passed to the code behind method. I have to perform some DB operation through these parameters but before that I wanted to make sure if this prototype would work.
This is how the anchor tag looks:
Show
This is my Javascript method:
function getClientData() {
//var dataValue = { "keyData": this.event.target.getAttribute("data-kt"), "valueData": this.event.target.getAttribute("data-kv")};
$.ajax({
type: "GET",
url: "Clients.aspx/GetClientData",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ keyData: this.event.target.getAttribute("data-kt"), valueData: this.event.target.getAttribute("data-kv")}),
dataType: 'json',
error: function (error) {
alert(error.statusText);
},
success: function (result) {
alert("Success: " + result );
}
});
}
I put a break point here and it never gets triggered. This is my web method in the code behind file:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string keyData, string valueData)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}
This is the URL that gets created for the POST request "http://localhost:60825/Clients.aspx/GetClientData?{%22keyData%22:%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22,%22valueData%22:%221p7q9%22}". Please let me know if I am doing something wrong.
I am not sure how you configured routing but based on your API method (code behind) your data should be formatted in following manner:
Method 1:
http://localhost:60825/Clients.aspx/GetClientData?keyData=Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy&valueData=1p7q9
As you can see, instead passing stringified JSON object I am sending data in format of query string where keyData and valueData has corresponding values.
Method 2:
If you prefer to send stringified JSON you can modify your Payload in URL like this:
http://localhost:60825/Clients.aspx/GetClientData?data=%7BkeyData%22%3A%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22%2C%22valueData%22%3A%221p7q9%22%7D
Here I am sending stringified JSON as data parameter in query string. For that purpose your code behing method needs to be like this:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string data)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}

how to replace single quotes with double qoute in jq

I have some thing like this.."Skin','Hair"...
i want result like this ['Skin', 'Hair'];
I tried this
type: 'GET',
url: '/HOME/Getselecteddata',
dataType: 'json',
data: { id: 8 },
success: function (data) {
debugger;
var endString = data.replace(/"/g, "'");
var selectedCodeWBs = [data]
$(".tokenizationSelect2").val(selectedCodeWBs).trigger('change');
Not working. please someone help me
my controller code:
public ActionResult Getselecteddata(int id)
{
var data = db.Segments.Where(x => x.Id == 7003).Select(x => x.Segname).SingleOrDefault();
List<string> segmentdata = new List<String>(data.Split(','));
string s2 = String.Join("','", segmentdata);
return Json(s2, JsonRequestBehavior.AllowGet);
}
You can much better do this:
return Json(segmentdata, JsonRequestBehavior.AllowGet);
Using segmentdata directly will work 100% better than creating a messy string variable that contains unbalanced quotes.
MVC Json() is perfectly capable of working with a List, it will output it as JSON array notation. Then in your javascript the received value in data will already be a Javascript array that won't need further manipulating.

JQuery/AJAX call is not hitting Spring MVC controller

I am trying to verify username and other fields while creating a change password page.The problem is AJAX call in Jquery script is not hitting my controller.i tried giving hard coded path also in url field of the ajax request.
Below is my Script
this checkUname function is triggering on onblur event from one of the input field.
<script type="text/javascript">
function checkUname()
{
// get the form values
var uName = $('#username').val();
var secQues = $('#secQues').val();
var secAns = $('#secAns').val();
var dataObject = JSON.stringify({
'uName' : uName,
'secQues': secQues,
'secAns' : secAns
});
$.ajax({
url:"validateCredentials.do" ,
type: "POST" ,
data: dataObject ,
contentType: "application/json; charset=utf-8" ,
dataType : 'json' ,
success: function(response)
{
alert(response);
} ,
error: function()
{
alert('Error fetching record.... Sorry..');
}
});
}
</script>
This is my MVC controller
#Controller
public class ArsController
{
#RequestMapping(value="validateCredentials.do", method = RequestMethod.POST)
public String changePass(#RequestParam("uName") String uName ,#RequestParam("secQues")String secQues,
#RequestParam("secAns") String secAns)
{
System.out.println("AJAX request");
Users dummyUSer = null;
String msg = null;
try
{
dummyUSer = servObj.findUser(uName);
}
catch (ArsException e)
{
System.out.println("error occurred while validating user data during password change");
e.printStackTrace();
}
if(dummyUSer == null)
{
msg = "No user exists with this username";
}
else
{
if(!secQues.equals(dummyUSer.getSecQues()))
{
msg = "Security question is not correct";
}
else
{
if(!secAns.equals(dummyUSer.getSecAns()))
{
msg = "Security answer does not match";
}
}
}
return msg;
}
Instead of using RequestParam in controller, you should use String. Because when we are posting JSON data it will not come as individual parameters in Request, instead it will be received as String in your controller. Once you get the String convert it to JSON object and then get your values accordingly.
try remove content-type and data-type.
You are not sending a json that should be parsed in a object, you are sending controller's parameters.
The way to do that is using an object in the Ajax 's data (as you did) but without the content-type or data-type that saying "I'm sending one json parameter"

Is it possible for a Java controller to pass an attribute to a success ajax call?

As the title says, I want to pass a variable from a controller to a success ajax call function but is it possible? For example:
I have a Java class with a controller like this:
#RequestMapping(value = "checkFruit", method = RequestMethod.POST)
#ResponseBody
public ModelAndView checkFruit(HttpServletRequest request, String fruitInput) {
ModelAndView modelAndView = new ModelAndView();
if (fruitInput.equals("apple")) {
modelAndView.addObject("fruitType", 1); //This is what I want to pass to the success ajax call.
} else if (fruitInput.equals("orange") {
modelAndView.addObject("fruitType", 2); //This is what I want to pass to the success ajax call.
}
modelAndView.setViewName("fruitGarden");
return modelAndView;
}
And a jsp view with an ajax call like this:
$("#checkFruitBtn").click(function () {
var fruitInput = $("input[name=fruitInput]").val();
$.ajax({
type: 'POST',
url: 'checkFruit',
data: 'fruitInput=' + fruitInput,
success: function () {
var fruitType= ${fruitType}; //I want to get the attribule of that "fruitType" variable set in the controller. But this is where things went wrong.
if (fruitType == 1) {
alert("This is an apple.");
} else if (fruitType == 2) {
alert("This is an orange.");
}
window.location.href = "/someURL";
}
});
});
In the above example. When I click the button "checkFruitBtn", it will send an ajax call to the controller "checkFruit". And in this controller, I'll set a variable "fruitType" to send it to the success ajax call function. In this success ajax call function, I'll get the value of the "fruitType" variable to check it and show alert message according to its value... But, things aren't going as planned.
My question is, is there a possible way of getting the value of that "fruitType" variable? I've searched for a getting method but I still can't find one that fitted in my case. I'm terribly sorry if this question have been asked before.
Thanks in advance!
With annotation #ResponseBody, Springmvc converts the returned object to a response body by using an HttpMessageConverter.
ModelAndView usually involves command object and view name.
so you can use ModelAndView with a Jsp page , then use el to evaluate command object values. to use #ResponseBody, Springmvc only return strings.
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var g = response;
var x= g.fruitType; //Now you can do the operation based on the output.

how can pass array to java servlet

On my jsp, this is my code :
$('.save').on("click",function(){
var array = $.map($('table tr'), function (val, i) {
var obj = {}, inputs = $(val).find('td input:not(:hidden)');
obj[inputs.filter(':first').val()] = $.map(inputs.not(':first'), function (val, i) {
return val.value;
});
return obj;
});
var data = JSON.stringify(array);
$.post("Controller.html", data, function(response) {
/// i dont know what to put here,so i think this where i get trouble with
});
});
but still data is null when i check on servlet.
this is my servlet :
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String data=request.getParameter("data");
if (data== null) {
System.out.println("null");
}
RequestDispatcher view = request.getRequestDispatcher("/page.jsp");
view.forward(request, response);
}
fiddle here
First you need to send the data, you can use an ajax post method:
$.post("yourservlet", data=JSON.stringify(array), function(response) {
// handle response from your servlet.
alert(response)
});
In servlet, you retrieve the data with the command:
String data=request.getParameter("data");
Then you need to parse the json, you can use a library like JSON simple:
Object obj = JSONValue.parse(data);
JSONArray array = (JSONArray) obj;
Or you can manually parse it. Based on your code, your json string will look like this:
data = "[{'orange':['1.00','5']},{'apple':['2.00','5']}]";
You can use split() method or StringTokenizer to separate each object, but you should write your own parser method, for this you can find many tutorials on google.
Javascript is in client-side. And java servlet is for server-side.
You must use ajax to make a call from client-side to your servlet.

Categories

Resources