ajax does not send info from client to server side - ajax

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}),
...
}

Related

'Access-Control-Allow-Origin' error when performing request to the server

on my server it runs a RESTful web service:
#GET
#Path("/{deviceId}/dashboard")
#Produces(MediaType.APPLICATION_JSON)
public String getDashboard(#PathParam("deviceId") int id){
List<Integer> dataNachId = new ArrayList<>();
dataNachId = allData.get(Integer.toString(id));
if(dataNachId==null){
return "No Data";
}
return "{data:"+dataNachId.toString()+"}";
}
and I would like to retrieve the return data by calling ajax request to the server as follow (using jsfiddle):
$(function() {
$.ajax({
type: 'GET',
url: 'http://localhost:8085/WSDemo/webapi/data/1/dashboard',
success: function() {
console.log('success', data);
}
});
});
but what I saw on the console is an error with the 'Access-Control-Allow-Origin'. Can anyone help me to fix this problem?
Just add dataype and crossdomain in the ajax request you are sending.
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'jsonp',
url: 'http://localhost:8085/WSDemo/webapi/data/1/dashboard',
success: function() {
console.log('success', data);
}
});

MVC Ajax Post error

I am getting error while I post Ajax request to controller method. In controller method I need to pass Model class object.
But it gives me 500 Internal server error.
Can anybody help me to make it correct?
Mu code is as per below:
jQuery:
var request = $("#frmHost").serialize();
$.ajax({
url: "/Host/HostItemDetails/" ,
type: "POST",
datatype: 'json',
contentType : "application/json",
data: request,
success: function (data) {
if (data == '1111') {
///Success code here
}
else if (data != '') {
jAlert(data);
}
}
});
Controller Method :
[HttpPost]
public JsonResult HostItemDetails(ClsHost objHost)
{
//Code here
return Json("1111");
}
Nirav Try this,
Parse the serialized data as a JSON object and later stringify that while posting using JSON.stringify().
$("#Button").click(function () {
var data = $("#frmHost").serialize().split("&");
var request = {};
for (var key in data) {
request[data[key].split("=")[0]] = data[key].split("=")[1];
}
$.ajax({
url: "/Home/HostItemDetails/",
type: "POST",
datatype: 'json',
contentType: "application/json",
data: JSON.stringify(request),
success: function (data) {
if (data == '1111') {
///Success code here
}
else if (data != '') {
jAlert(data);
}
}
});
});
I ran the same code that you are running.
To test the code I did the following changes. I took a button, and on click event I am sending the post back to the controller.
the '[HttpPost]' attribute is fine too.
Can you make one thing sure, that the frmHost data matches to the class ClsHost,but still that shouldn't cause the server error, the error will be different.
$(document).ready(function () {
$("#clickMe").click(function () {
var request = '{"Users":[{"Name":"user999","Value":"test"},{"Name":"test2","Value":"test"}]}';
$.ajax({
url: "/Home/HostItemDetails/",
type: "POST",
datatype: 'json',
contentType: "application/json",
data: request,
success: function (data) {
if (data == '1111') {
///Success code here
}
else if (data != '') {
jAlert(data);
}
}
});
});
});
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult HostItemDetails(ClsHost objHost)
{
//Code here
return Json("111", JsonRequestBehavior.AllowGet);
}
It is solved by removing same property name in Model class. It is mistakenly added by me twice.

Reading JSON values in servlet [duplicate]

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);
}
});
}

Unable to receive json data in controller with knockout

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.

How can i post same page with ajax json

this is my ajax post code on Default.aspx's source side:
$.ajax({
type: "POST",
url: "Default.aspx/f_Bul,
data: "{_sSKodu:'4'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#" + div).html(msg.d);
$("#" + div).show();
}
}
)
and this is my function which is on the Default.aspx.cs
protected void f_Bul(string _sSKodu)
{
Select s = new Select(_sSKodu);
}
I want send parameter to f_Bul. but i cant post that data.
where is my mistake?
You need to decorate your method with the [WebMethod] attribute, and it must be static. It might have to be public and return a string as well, not 100% on that though.
[WebMethod]
public static string f_Bul(string _sSKodu)
{
Select s = new Select(_sSKodu);
}
I couldn't get it to work with .aspx, so I went to .asmx and this is how I finally got it ot work:
[System.Web.Script.Services.ScriptService]
public class getData : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string finalize(String Number)
{
return "{'result':'success'}";
}
}
I also had to put a script manager on my .aspx page, but it finally worked.

Resources