This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 3 years ago.
I am posting a jQuery AJAX POST to a servlet and the data is in the form of JSON String.
I am not sure whether data is getting posted or not. Also, I want to verify login and password by fetching it from json object.
Heres the code snippet:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
<script type="text/javascript">
function doajax(){
var fullname=$("#fullname").val;
var mobileno=$("#mobileno").val;
$.ajax({
url: 'dvsds',
type: 'POST',
dataType: 'json',
data:{ "mobileno":mobileno, "fullname":fullname},
error:function(){
alert("error occured!!!");
},
success:function(data){
alert(data.message);
}
});
}
</script>
My servlet side code:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
try {
String message=null;
JSONObject jObj = new JSONObject(request.getParameter("jsondata"));
Iterator<String> it = jObj.keys(); //gets all the keys
String Name=null;
String mobileno=null;
while(it.hasNext())
{
String key = (String) it.next(); // get key
if(key.equals("fullname"))
Name = (String)jObj.get(key);
else if(key.equals("mobileno"))
mobileno=(String)jObj.get(key);
}
if(Name=="abc" && mobileno=="123" )
message="success";
else
message="fail";
JSONObject jsonObject = new JSONObject();
jsonObject.put("message", message);
out.println(jsonObject);
The datatype attribute of the jQuery.Ajax function states the following:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server.
So, what you are sending is not a JSON string. What you are sending is plain old request data.
You can get this data in your servlet using:
String mobileno = request.getParameter("mobileno");
You do not need to stringify the data ... just send it as a plain old javascript object ... by specifying datatype as json ... jquery will figure out how to pack the data in the request
No need to change anything on server side
So if your AJAX call becomes:
$.ajax({
url: 'dvsds',
type: 'POST',
dataType: 'json',
data: jsondata,
error:function(){
alert("error occured!!!");
},
success:function(data){
alert(data.message);
}
});
Retrieve them in the servlet as
String fname = request.getParameter("fullname");
String mobileno = request.getParameter("mobileno");
I think you will need to be careful about case sensitivity
EDITED
I see that you Can you change your script to be as follows.
<script type="text/javascript">
function doajax(){
var fullname=$("#fullname").val;
var mobileno=$("#mobileno").val;
var postReqData = {}; // Create an empty object
postReqData['mobileno'] = mobileno;
postreqData['fullname'] = fullname;
$.ajax({
url: 'dvsds',
type: 'POST',
dataType: 'json',
data: postReqData,
error:function(){
alert("error occured!!!");
},
success:function(data){
alert(data.message);
}
});
}
Related
In the case, on the server side have some archive restApi.js with REST functions. My REST functions works fine, i test with Prompt Command.
In my client side have some archive index.ejs, And I want to call with this file.
My restApi.js: Server-side
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxx","password":"xxxxxxxxxx","platform":"xxxx" },
headers: { "Content-Type": "application/json" }
};
var numberOrigin = 350;
client.registerMethod("postMethod", "xxxxxxxxxxxxxxxxxx/services/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
console.log(data);
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
var sessionid = match[2]
console.log(sessionid);
openRequest(sessionid, numberOrigin); // execute fine
}
});
function openRequest(sessionid, numberOrigin){
numberOrigin+=1;
var dataRequest = {
data: {"sessionID":sessionid,"synchronize":false,"sourceRequest":{"numberOrigin":numberOrigin,"type":"R","description":"Test - DHC","userID":"xxxxxxxxxx","contact":{"name":"Sayuri Mizuguchi","phoneNumber":"xxxxxxxxxx","email":"xxxxxxxxxxxxxxxxxx","department":"IT Bimodal"},"contractID":"1","service":{"code":"504","name":"Deve","category":{"name":"Developers"}}} },
headers: { "Content-Type": "application/json" }
};
client.post("xxxxxxxxxxxxxxxxxxxxxxxxx/services/request/create", dataRequest, function (data, response) {
// parsed response body as js object
// console.log(data);
// raw response
console.log(data);
});
}
My index.ejs: Client side
<html>
<head> ------------- some codes
</head>
<meta ------- />
<body>
<script>
function send() {
$.ajax({
type: "POST",
url: "restApi.js",
data: '{ sendData: "ok" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
</script>
<script src="restApi.js"></script>
</body>
</html>
I've try see others examples but does not work (Ajax).
And I need to know how to solved this, if have other Best practice for it, please let me knows.
In my console (Chrome) show if I call the ajax function:
SyntaxError: Unexpected token s in JSON at position 2 at JSON.parse (<anonymous>) at parse (C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\types\json.js:88:17) at C:\xxxxxxxxxxxxxxxxxxxxxxxxx\node_modules\body-parser\lib\read.js:116:18
And if I click (BAD Request) show:
Obs.: Same error than app.js, but app.js works fine.
Cannot GET /restApi.js
In the case the file restApi.js Is a folder behind the index.
Folder:
Obs.: public folder have the index.ejs
Your problem is bad url. In case if you have fiule structure like this you have to point as shown in image
Based on the error I think the data you are posting via AJAX is not in correct syntax.
Change function send() as following.
function send() {
var obj = { "sendData" : "ok" };
$.ajax({
type: "POST",
url: "restApi.js",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
}
});
}
This should resolve the error you are facing.
Try this now...
function send() {
var obj = {
sendData : "ok"
};
$.ajax({
type: "POST",
url: "Your url",
data: obj,
dataType: "json",
success: function (result) {
alert("successful!" + result.d);
},
error: function (error) {
console.log("error is", error); // let us know what error you wil get.
},
});
}
Your url is not pointing to js/restapi js.
and what code do you have in js/restapi js?
if your action page is app js you have to put it in url.
url:'js/restapi.js',
I have an ajax on client side:
$("#TIPUL_ACTULUI").change(function(){
var selectedText = $(this).find("option:selected").text();
$.ajax({
type:'POST',
url: '<c:url value="/"/>searchByAct',
data:{act:selectedText},
dataType: 'json',
context:this,
success:function(data){
$('#DREVIZ').html(data);
},
error:function(xmlHttpRequest, textStatus, errorThrown){
if(xmlHttpRequest.readyState=0 || xmlHttpRequest.status == 0)
return;
}
});
});
and on server side:
#RequestMapping(value="/searchByAct", method=RequestMethod.POST)
public ModelMap acte(#RequestParam(required = false, value = "act") String act){
ModelMap model=null;
model.clear();
PortalUserDetails user = (PortalUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
ArrayOfSlSordIdRegInfo arrayActe = ixService.searchActeForCUI(user.getPunctDeLucru().getCnpCuiOE(),
String.valueOf(user.getPunctDeLucru().getIdPDL()));
Map<String, List<SlSordIdRegInfo>> comboItemsMap4 = new HashMap<String, List<SlSordIdRegInfo>>();
comboItemsMap4.put(Constants.CHEIE_SORD_DREVIZ, arrayActe.getSlSordIdRegInfo());
model.addAttribute("comboItemsMap4", comboItemsMap4);
return model;
}
my problem is that the compiller doesn't reach the server side. What did I do wrong? Thanks!
The only thing is coming to mind when i am looking at the code is to change the url into:
url: '/searchByAct',
If you are sure that URL is correct try to stringify the 'data' parameter:
$.ajax({
...
data: JSON.stringify({act:selectedText}),
...
}
I am fetching data from a form using jquery and posting with ajax to a .jsp file.
when i try to receive the data in jsp scriplet using request.get parameter then i get null.
var values = {}; // Create empty javascript object
$("select").each(function() { // Iterate over selects
values[$(this).attr('name')] = $(this).find(":selected").attr('data-citycode'); // Add each to features object
});
var format = "dd/mm/yyyy";
values["datepicker1"] = $("#datepicker1 div").datepicker("getFormattedDate", format);
values["datepicker2"] = $("#datepicker2 div").datepicker("getFormattedDate", format);
//var url ="list_flights.jsp";
$.ajax({
type: "GET",
url: "list_flights.jsp",
async: false,
data: {
values: JSON.stringify(values)
},
error: function(data) {
console.log(data);
},
success: function(data) {
console.log(data);
window.location = "list_flights.jsp";
}
});
and the jsp scriplet
<% out.print(request.getParameter("values")); %>
output
null
it seems that on success of ajax you are changing the window location
success: function(data) {
console.log(data);
window.location = "list_flights.jsp";
}
which is making another request and do not have the values attribute in request.
success: function(data) {
console.log(data);
window.location = "list_flights.jsp?values=" + JSON.stringify(values);
}
But it doesn't make sense of redirecting on success and calling the ajax to the same jsp. You should call a servlet from ajax which will give you the response and based on that response you should redirect to another page.
This is the method from the controller api :
[HttpPost]
public void SaveFloor(int floorID, string json)
{
Floor floor = db.FloorSet.Find(floorID);
floor.SavedJson = json;
floorRepository.Update(floor);
floorRepository.Save();
}
Then I made an ajax call to pass the URL.
function SavingFloor(FloorId, Json) {
$.ajax({
url: "/api/Floor/SaveFloor?FloorID=" + FloorId + "&json=" + Json,
type: "POST",
dataType: 'json',
success: function (data) {
alert('success');
}
});
}
I'm trying to save JSON in database (datatype: nvarchar(MAX)), when I call the URL that executes the saving, I get this error Error HTTP 404.15 - Not Found and it says that the filter module applications is configured to deny a request if the string is too long.
So, what should I do? the JSON that I generate is in fact supposed to be too long, and that's the purpose. Please help.
Send the JSON string as the POST body not as part of the URL. Send it as text and json_decode on the server.
function SavingFloor(FloorId, Json) {
$.ajax({
url: "/api/Floor/SaveFloor?FloorID=" + FloorId,
type: "POST",
data: Json,
dataType: 'text/html',
success: function (data) {
alert('success');
}
});
}
I am new with knockout and mvc, so I need some help, my question is
my dropdown list is populating successfully from server, and on clicking save button calls Save method in controller. But problem is that in controller I am unable to receive json data i.e it is null. here is my code in view
var initialData = #Html.Raw( new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(Model));
var viewModel = function(){
var self = this;
self.HomeAgencies = ko.observableArray(initialData.HomeAgencies);
self.selectedOrgUnit = ko.observable();
self.Save = function () {
$.ajax({
url: "#Url.Action("Save")",
type: "POST",
data: ko.toJSON(this),
contentType: "application/json; charset=utf-8",
dataType:"json",
success: function(result) {alert(result.message)}
});
}
}
var vm = new viewModel();
ko.applyBindings(vm);
Where in controller i have following code
public JsonResult Save(string someData)
{
var message = string.Format("Saved {0} ", "successfully");
return Json(new { message });
}
string someData is always null, where I am expecting some json data.
Try to replace this to self in data and introduce field name and remove contentType.
$.ajax({
url: '#Url.Action("Save")',
type: 'POST',
data: { someData: ko.toJSON(self) },
dataType: 'json',
success: function (result) { alert(result.message); }
});
In your case context of the method can be changed from your object to html element that invoked them method or to window.
issue resolved. Problem was at controller side, in Action of controller pass the same model class instead parsing json manually.