I am learning Spring MVC and I have stuck at how to send a simple string value from client using AJAX and print it at JAVA server (controller). I have written below code for doing this. But when I click button to send string, error.... response is popped-up in my browser and the browser console displays POST http://localhost:8090/addUser 404 (). It has been a day since I am trying to solve this issue. Can someone please tell what can be the problem? Or please tell a working alternative solution for sending data from client using AJAX and printing/saving it on JAVA server (Spring-MVC).
UserController.java
#Controller
public class UserController {
#RequestMapping(value = "/addUser", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
public JSONArray addUser(#ModelAttribute("UserTest") JSONArray name) {
System.out.println(name.toString());
return name;
}
}
AJAX Request:
<script>
function addUser() {
var json = '{"uname":"John", "Age":42}';
obj = JSON.parse(json);
$.ajax({
url : "/addUser",
data : obj,
type : "POST",
async: false,
contentType: "application/json",
success : function(response) {
alert( response );
},
error : function() {
alert("error...."); //this is being popped-up in my browser
}
});
}
</script>
POST http://localhost:8090/addUser 404 ()
Your request is going to http://localhost:8090/addUser, which is not correct. Your request url should have your application and included.
http://localhost:8090/<app_name>/addUser
AFAIK, your request url should have application name included. Now, to achieve this, you are suppose to change your ajax url
url : "/<app_name>/addUser"
The URL for the ajax call is not correct. It should be like
Url:YourApplicationContextPath/ControllerName/addUser
Related
This is a simplified version of a problem I'm having. How do I send data to a Spring Boot Controller via an AJAX Query and then open a new JSP page? When I send data to the url in the AJAX Query to the matching URL in my controller class it seems to run the code within that method but not open the JSP (or return type).
For example if I were to send the following data from an Ajax Query
var hello = "Hello World!";
$.ajax({
type: "POST",
url: "/message1",
data: {
message: hello,
},
datatype: 'json'
});
}
To this method in my Controller class
#RequestMapping(value = "/message1", method = RequestMethod.POST)
public String MessageReceiver(#RequestParam("message")String message,
BindingResult bindingResult,
Model model) {
System.out.println(message);
return "NewPage";
}
"Hello" will print in the console but the JSP page NewPagewill fail to open and will prompt no errors?
Usually if I just call the url in the controller (for example /message1) via a href link, or button etc the NewPage JSP page will open. It seems that the AJAX query is missing something. Do I have to update the URL in the Ajax Query to something similar to /message1/NewPage (tried this, didn't work), or add something to the controller because the NewPage JSP page will not open.
Add the success callback function to your ajax like so:
$.ajax({
type: "POST",
url: "/message1",
data: {
message: hello,
},
datatype: 'json',
success: function(data){
if(data === "NewPage"){
//Open new page
}
}
});
}
I am trying to pass some data from the frontend to the backend of my site using AJAX. This is the post request view in my django views:
def post(self, request):
id_ = request.GET.get('teacherID', None)
print(id_)
args = {}
return JsonResponse(args)
This is the function I have in javascript. I know the correct value is being passed because the console.log(teacher_id) prints the right value.
function send(teacher_id){
console.log(teacher_id)
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'teacherID': teacher_id,
},
dataType: 'json',
success: function (data) {
//location.href = data.url;//<--Redirect on success
}
});
}
When the code is run, and the print statement in my view is run, regardless of what the teacher_id is, None is printed.
what is wrong with the code?
In your Django view the data is being retrieved using GET.get() while the AJAX request is sending it using method: "POST".
POST data can't be retrieved in the same way as GET data so you should either change the way the data is being send (by changing the method in the AJAX call to GET) or read it using the related POST methods.
You can visit this Stack Overflow question if you are doubting which method to use.
I've looked at thousands of articles about my problem, but i didn't found a solution.
Here we go.
When I'm using ajax with url specified as the url of view when i want to use a script it doesn't work. I'm using POST type and receiving data in spring controller. When I change url to something else and do the same in requestmapping value, everything works fine. What possibly causing this problem ? AJAX:
$.ajax({
type : "POST",
url : "/login2",
data :
{x: x}
,
success : function() {
alert('fine');
},
error: function(xhr, status, error) {
alert(xhr.status+status+error);
}
});
SPRING:
#Controller
#RequestMapping
public class LoginController {
#RequestMapping(value = "/login",method = RequestMethod.GET)
public String login() {
return "login";
}
#RequestMapping(value = "/login2",method =RequestMethod.POST)
public #ResponseBody void login2(#RequestParam(value="x[]") String x[]){
System.out.println(x[1]);
}
}
Code above works fine but
When url is "/login" for whole class and methods are specified the same it doesn't work ..
Can You help me please ?
Your parameter for login2 is array of string. Whereas you are sending object from ajax.
try reading the values from Request body instead of request param.
login2(#RequestBody String x[])
Maybe problem is that this is my page declared as login apge in Spring Security ?
I'm attempting to call a web service via AJAX in a WebForms application.
My script looks something like this:
$.post('UpdateServer.asmx/ProcessItem',
'itemId=' + $(this).text(),
function (result) {
alert(result);
});
My web service looks something like this.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class UpdateServer : System.Web.Services.WebService
{
[WebMethod]
public string ProcessItem(int itemId)
{
return new JavaScriptSerializer().Serialize(
new { Success = true, Message = "Here I am!" });
}
}
The web method is called as expected and with the expected argument. However, the argument passed to my success function (last parameter to $.post()) is of type document and does not contain the Success and Message members that I'm expecting.
What's are the magic words so that I can get back the object I'm expecting?
EDIT
On closer inspection, I can find the data I'm looking for as follows:
result.childNodes[0].childNodes[0].data:
"{"Success":true,"Message":"Server successfully updated!"}"
The reason you're seeing that odd structure of nodes that end with JSON is because you're not calling the service the necessary way to coax JSON out of ASMX ScriptServices and then returning a JSON string anyway. So, the end result is that you're returning an XML document that contains a single value of that JSON string.
The two specific problems you're running into right now are that you're manually JSON serializing your return value and you're not calling the service with a Content-Type of application/json (.NET needs that to switch to JSON serializing the response).
Once you fixed those issues, you'd also run into an "invalid JSON primitive" error due to the data parameter being URL encoded instead of a valid JSON string.
To get it working, do this on the server-side:
[ScriptService]
public class UpdateServer : System.Web.Services.WebService
{
[WebMethod]
public object ProcessItem(int itemId)
{
return new { Success = true, Message = "Here I am!" };
}
}
You could also create a data transfer object (aka ViewModel) to return instead of using an anonymous type and object, if you want.
To successfully get raw JSON out of that, do this on the client-side:
$.ajax({
url: 'UpdateServer.asmx/ProcessItem',
type: 'post',
contentType: 'application/json',
data: '{"itemId":' + $(this).text() + '}',
success: function(result) {
// This will be { d: { Success: true, Message: "Here I am!" } }.
console.log(result);
}
});
If you have a few minutes, read through the posts in the communication section of jQuery for the ASP.NET developer. You'll find a lot of that information helpful as you continue down this path.
Note: The links that helmus left were relevant. Nothing has fundamentally changed between 2.0 and present with regards to using ASMX ScriptServices to communicate via JSON. If you're interested in the truly cutting edge approach to this problem in .NET, ASP.NET Web API is the way to go.
Add this attribute to your ProcessItem method:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
Be more explicit in your $.post call.
$.ajax({
type:'post',
url:'UpdateServer.asmx/ProcessItem',
data: {'itemId':$(this).text()}
}).done(function (result) {
alert(result);
});
All the examples of json I can find online only show how to submit json arrays w/ the jquery command $.ajax(). I'm submitting some data from a custom user control as a json array. I was wondering if it's possible to submit a json array as a regular post request to the server (like a normal form) so the browser renders the page returned.
Controller:
[JsonFilter(Param = "record", JsonDataType = typeof(TitleViewModel))]
public ActionResult SaveTitle(TitleViewModel record)
{
// save the title.
return RedirectToAction("Index", new { titleId = tid });
}
Javascript:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
});
}
Which is called from a save button. Everything works fine but the browser stays on the page after submitting. I was thinking of returning some kind of custom xml from the server and do javascript redirect but it seems like a very hacky way of doing things. Any help would be greatly appreciated.
This is an old question but this might be useful for anyone finding it --
You could return a JsonResult with your new titleId from the web page
public ActionResult SaveTitle(TitleViewModel record) {
string tId = //save the title
return Json(tId)
}
and then on your ajax request add a success function:
function SaveTitle() {
var titledata = GetData();
$.ajax({
url: "/Listing/SaveTitle",
type: "POST",
data: titledata,
contentType: "application/json; charset=utf-8",
success: function(data) { window.location = "/Listing/Index?titleId=" + data; }
});
}
That would redirect the page after a successful ajax request.
I just saw that you mentioned this at the end of your post but I think it is an easy and quick way of getting around the issue.
Phil Haack has a nice post discussing this scenario and shows the usage of a custom value provider instead of an action filter.
I don't understand why you would want to post Json if you're wanting to do a full page post. Why not just post normal form variables from the Html form element?