Cannot retrieve data from ajax with request - javascript

I'm having problems retrieving data from an ajax post in an easy aplication, just making some tests.
I'm working with something easy:
I have 2 classes:
Controller.java:
#RequestMapping(value = "/urlpost", method = {RequestMethod.GET, RequestMethod.POST} )
public urlPostTest(HttpServletRequest request, HttpServletResponse response) {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("post_name");
String age = request.getParameter("post_age");
System.out.println("His name is: " + name);
System.out.println("His age is: " + age);
}
And
PostingClass.js
function posting(){
$.ajax({
url: 'urlpost',
method: 'POST',
data: {
'post_name': "Peter",
'post_age': "22"
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () {
console.log("Send data: SUCCES.");
}
});
}
The ajax goes correctly to the url, but the request is always null.
What could be the problem?.
Thanks.

request.getParameter("post_name"); // works on application/x-www-form-urlencoded
To get the data from a application/json request, use something like this:
String jsonStr = IOUtils.toString(request.getInputStream());
JSONObject jsonObj = new JSONObject(jsonStr);
String name = getString("name");

Related

Why does web service not return string properly?

I have ajax function that send some string to webservice.
Here is ajax:
var data = "wkt=" + wkt;
$.ajax({
url: "....some path",
type: "POST",
data: data,
crossDomain: true,
dataType: "text",
success: function (response) {
alert(response);
},
error: function () {
console.log('Request Failed.');
}
});
And here is web service:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class ValveService : System.Web.Services.WebService
{
[WebMethod]
public string ExecuteQuery(string wkt)
{
return "dummy!";
}
}
As response I get this string:
"<?xml version="1.0" encoding="utf-8"?><string xmlns="http://tempuri.org/">dummy!</string>"
While I expect to get as response "dummy!".
Any idea why I get this strange responce and how to get only string that was sent from service(in my case "dummy!") ?
I'm pretty sure web services only return xml or json. There might be a way around it, setting a response type in the service but I'm not sure. [Edit: I see Nerdi.org already hinted at this.]
When dataType: 'text', the response header is not just text, but Content-Type: text/xml; charset=utf-8, and you get xml.
Go for json (which is a string) and work with that.
//var data = "wkt=" + wkt;
$.ajax({
url: "/path to/ExecuteQuery",
type: "POST",
data: JSON.stringify({ wkt: wkt }),
contentType: "application/json; charset=utf-8", // this will be the response header.
crossDomain: true,
dataType: "json",
success: function(response) {
// response is a wrapper. your data/string will be a value of 'd'.
alert(response.d);
},
error: function() {
console.log('Request Failed.');
}
});
An alternative:
[WebMethod]
public void ExecuteQuery(string wkt)
{
Context.Response.Output.Write("dummy " + wkt);
Context.Response.End();
}

Error while calling Webapi in my asp.net project

This is my api code that return successfull json data while using get method
public Question[] Get() {
getQuestion obj = new AllDataAccess.getQuestion();
return obj.questionList().ToArray();
}
This is my post method data that accept the value and save in database
public void Post([FromBody] string question) {
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
This is the method that call my api
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values',
data: "{'question':'" + $("#submit").value + "'}",
dataType: 'json',
async: false,
success: function(data, status) {
console.log(status);
},
error: function(err) {
console.log(err);
}
});
Now the problem is when i post the data with one textbox value its give me a message in console that "nocontent" and record save in data base with null value
It seems that your ajax url is wrong. You should specify the action name (post). Also, use JSON.stringify to retrieve proper json from javascript object.
var postData = { question:$("#submit").val() };
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'http://localhost:53893/api/values/post',
data: JSON.stringify(postData),
dataType: 'json',
success: function (data,status) {
console.log(status);
},
error: function (err) {
console.log(err);
}
});
In the server side, you should create a model class for Post method;
public class PostInput
{
public string Question { get; set; }
}
And then Post method looks like;
[HttpPost]
public void Post([FromBody]PostInput input)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
If you want to use FromBody, you can do so.
JavaScript
$.ajax({
type: "POST",
//default content-type, could be omitted
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
url: 'http://localhost:53893/api/values/post',
data: {'': $("#submit").val()}
});
API action
[HttpPost]
public void Post([FromBody]string question)
{
SaveQuestion obj = new AllDataAccess.controller.SaveQuestion();
obj.savaData(question);
}
You had these issues.
Wrong content-type for your ajax call.
Data was not posted correctly.
val() should be used instead of .value.
API action should be decorated with [HttpPost].

How to pass Parameter from Ajax to RestController in Spring Boot

i try to pass Parameter from Ajax to RestController to send a Email.
That is the Controller Post Methode to send the Enail
#RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody String create(#RequestParam("covere") String covere, #RequestParam("title") String title,
#RequestParam("username") String username, #RequestParam("usernameto") String usernameto) {
try {
mailService.sendMail(covere, title, username, usernameto);
return "sendmail";
} catch (MailException e) {
e.printStackTrace();
}
return "sendmail";
}
That is the Ajax to Call the Post and pass the Variable to send Message
$("#vuta").on("click", function(e) {
var EmailData = {
"covere" : "John",
"title" :"Boston",
"username" :"test#yahoo.fr",
"usernameto" :"test#yahoo.fr"
}
$.ajax({
type: "POST",
url: "/emailsend",
dataType : 'json',
contentType: 'application/json',
data: JSON.stringify(EmailData)
});
});
I have this Error when i send the Email
Required String parameter 'covere' is not
present","path":"/emailsend"}
Thank for help
Your controller is expecting parameters via Query String. You can use $.param to format the object as query string and send it in the URL:
$("#vuta").on("click", function(e) {
var EmailData = {
"covere" : "John",
"title" :"Boston",
"username" :"test#yahoo.fr",
"usernameto" :"test#yahoo.fr"
}
$.ajax({
type: "POST",
url: "/emailsend?" + $.param(EmailData),
dataType : 'json',
contentType: 'application/json'
});
});

Ajax send large data MVC4

I'm Trying to send large Data amount using ajax , it returns 404 error Not found , and if I send small amount of Data it respond with 200 and work Normally
here is my Code
var str = myDiagram.model.toJson();
document.getElementById("mySavedModel").value = str;
myDiagram.isModified = false;
$.ajax({
dataType: "json",
url: "/Workflow/PraseJson/?diagram=" + str
}).done(function (x) {
});
and Code for Controller
public void PraseJson(string diagram)
{
object yourOjbect = new JavaScriptSerializer().DeserializeObject(diagram);
}
I do not know how to solve this Issue, Can anyone help ?
Try using POST to send data
$.ajax({
dataType: "json",
type: "POST",
data: {diagram: str },
url: "/Workflow/PraseJson/
}).done(function (x) { });
[HttpPost]
public void PraseJson(string diagram)
{
object yourOjbect = new JavaScriptSerializer().DeserializeObject(diagram);
}

How to call MVC Api controllers HttpResponseMessage Post action using javascript as client?

I am calling this action of api from client. The client code also see below.
API Action:
public class StudentTestController : ApiController
{
[HttpPost]
public HttpResponseMessage GetLessonInfo(int request)
{
HttpResponseMessage result = null;
result = Request.CreateResponse(HttpStatusCode.OK,StudentTest.GetLessonInfo(request));
return result;
}
}
JavaScript client script:
function SendRequest() {
var url = "http://localhost:1938/api/StudentTest/GetLessonInfo";
var data1 = "request=293";
$.ajax({
type: 'POST',
url: url,
data: data1,
contentType: 'application/json; charset=utf-8',
dataType: 'jsonp',
success: function (data) {
$('#txtResponce').val(JSON.stringify(data.Data));
},
error: function (xhr, status, error) {
var errorText = xhr.status + "\r\n" + status + "\r\n" + error;
$('#txtResponce').val(errorText);
}
});
}
When i am trying to call Action with the above snippet it will not calling the controller action. How to solve this?
Pavan.
Have you tried this instead:
var url = "/api/StudentTest/GetLessonInfo";
var data1 = "293";
Maybe "request=293" can be considered as a string and not the "int" expected as parameter.
And since the int parameter is not nullable, maybe it's giving you a Bad Request response.
Check with Fiddler what is being sent to the server.

Categories

Resources