Ajax POST data in Request Param - javascript

I am making a POST request as below :
$.ajax({
url :"/clientCredentials.json",
type: "POST",
data: {
"clientEmail": email,
"clientName":clientName,
"orgName":orgName,
"logoURL":logoURL,
"redirectURI":redirectUri
},
success: function(response){
alert("sucess");
},
error:function(response){
alert("something went wrong");
}
});
On the server, I am using #RequestParams to get this data.
#RequestParam String clientEmail, #RequestParam String clientName, #RequestParam String orgName, #RequestParam String logoURL, #RequestParam String redirectURI
I am getting below from from server:
{"code":"400","errorMessage":"Required String parameter 'clientEmail' is not present"}
If I use #RequestBody instead of #RequestParam to accept this data its working fine.
My question is How can I get this data in Request Parameters? What am I doing wrong?
I have tried Jquery($.get(), $.post()) also. nothing working.
Thanks for any help.

I just did small project with latest version of spring boot and jquery and it is working well, and based on investigation I did I found there are 2 factor can make this issue, one from jquery and other one from Spring MVC converters:
1- jquery ajax have contentType parameter
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
if this one changed to application/json or application/xml will change the way it is sending request to server then will make issue to server parsing, but it is default value will send form as key=value coma separated and this is OK with FormHttpMessageConverter "which is drive us to next point"
2- spring MVC is using FormHttpMessageConverter for "application/x-www-form-urlencoded" parsing or converting then you can use #RequestParam if this converter changed to other converter like:
MappingJackson2HttpMessageConverter for 'application/json'
or
Jaxb2CollectionHttpMessageConverter for 'application/xml'
so it will expect another request and you can get it using #RequestBody
So, you have to check request going from jquery is it form, json, or xml using development tools in your browser, then check you spring code/configuration to be sure that this request is converted by the FormHttpMessageConverter, this converter could be changed by the parameters of your #RequestMapping.

you cant use $.get with payload(data) but you can use $.post. please add attribute contentType in your request parameter.
$.ajax({
url :"/clientCredentials.json",
type: "POST",
contentType: "application/json",
data: {
"clientEmail": email,
"clientName":clientName,
"orgName":orgName,
"logoURL":logoURL,
"redirectURI":redirectUri
},
success: function(response){
alert("sucess");
},
error:function(response){
alert("something went wrong");
}
});

Related

400 error "You must pass a valid patch document in the body of the request." [duplicate]

So according to the jQuery Ajax docs, it serializes data in the form of a query string when sending requests, but setting processData:false should allow me to send actual JSON in the body. Unfortunately I'm having a hard time determining first, if this is happening and 2nd what the object looks like that is being sent to the server. All I know is that the server is not parsing what I'm sending.
When using http client to post an object literal {someKey:'someData'}, it works. But when using jQuery with data: {someKey:'someData'}, it fails. Unfortunately when I analyze the request in Safari, it says the message payload is [object Object] ... great... and in Firefox the post is blank...
When logging the body content on the Java side it literally gets [object Object] so how does one send REAL JSON data??
Has anyone had experience with a Java service serializing JSON data in the request body, with the request sent from jQuery?
BTW here is the full $.ajax request:
$.ajax({
contentType: 'application/json',
data: {
"command": "on"
},
dataType: 'json',
success: function(data){
app.log("device control succeeded");
},
error: function(){
app.log("Device control failed");
},
processData: false,
type: 'POST',
url: '/devices/{device_id}/control'
});
An actual JSON request would look like this:
data: '{"command":"on"}',
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:
data: JSON.stringify({ "command": "on" }),
To support older browsers that don't have the JSON object, use json2.js which will add it in.
What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.
Seal them up
//contentType: false,
//processData: false,

How to properly post JSON data using Ajax to Flask [duplicate]

update: I would like to pass the var value to the server
hello,
same old, same old ... :)
I have a form called <form id="testForm" action="javascript:test()"> and a code area called <code id="testArea"></code>
I am using this code to stringify and display the data in the code area:
var formData = form2object('testForm');
document.getElementById('testArea').innerHTML = JSON.stringify(formData, null, '\t');
var value = JSON.stringify(formData, null, '\t');
What I want is to send this data to a JSON file.
I've been working on this project : http://ridegrab.com/profile_old/ and if you press Submit Query button you will see the head of the page populate.
Also I want use this piece of script to send data:
function authenticate(userName, password) {
$.ajax
({
type: "POST",
//the url where you want to sent the userName and password to
url: 'username:password#link to the server/update',
dataType: 'json',
async: false,
//json object to sent to the authentication url
data: '{"userName": "' + userName + '", "password" : "' + password + '"}',
success: function () {
alert("Thanks!");
}
})
}
Again, all I want is to be able to send that JSON data to the server. My server is set up to update or POST the data in the right place.
You post JSON like this
$.ajax(url, {
data : JSON.stringify(myJSObject),
contentType : 'application/json',
type : 'POST',
...
if you pass an object as settings.data jQuery will convert it to query parameters and by default send with the data type application/x-www-form-urlencoded; charset=UTF-8, probably not what you want
'data' should be a stringified JavaScript object:
data: JSON.stringify({ "userName": userName, "password" : password })
To send your formData, pass it to stringify:
data: JSON.stringify(formData)
Some servers also require the application/json content type header:
contentType: 'application/json'
There's also a more detailed answer to a similar question here: Jquery Ajax Posting JSON to webservice
In case you are sending this post request to a cross domain, you should check out this link.
https://stackoverflow.com/a/1320708/969984
Your server is not accepting the cross site post request. So the server configuration needs to be changed to allow cross site requests.

Jquery serialize : trying to pass a form status to an ASP.NET MVC controller without submitting the form

Working on an ASP.NET MVC application.
A form has several buttons submitting the form.
One of the buttons needs to send to the controller the form's controls status without submitting the form.
I plan to use Ajax and $('#FormID').serialize();
I wrote it this way:
function rechercher() {
var formStatus = $('#FormID').serialize();
var url = '#Url.Action("Search", "ImproItemForm"); //?'+ formStatus;
// alert('formStatus: ' + formStatus); //works fine
alert('url: ' + url);
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
data:/* { improItem: formStatus },*/ formStatus ,
contentType: "application/json; charset=utf-8",
success: function (result) {
alert("success" + result);
},
error: function (result) {
alert("failure" + result);
}
});
}
My controller action is as below:
public ActionResult Search(FormCollection improItem)
{
}
If I call ajax this way, it never reaches the controller (and thus triggers the error function.
If I comment this line:
data: formStatus ,
Then it does invoke the controller method but the FormCollection improItem argument has no values of course.
So I suppose that I am not passing the data correctly to Ajax but I do not manage to get this sorted.
thx in advance.
Make sure you specify the correct content type. Right now you seem to have specified application/json; charset=utf-8 but obviously you aren't sending any JSON but rather application/x-www-form-urlencoded which is how the .serialize() method will format the form values. So just get rid of this line:
contentType: "application/json; charset=utf-8",
Usually when you are unsure about what you are sending or receiving instead of trying to explicitly specify it like you did, you'd better don't specify anything and leave jQuery figure it out. The same stands true of course for the dataType: 'json', property. If your controller action doesn't return JSON, this will cause an error. If on the other hand you don't specify the expected return type, then jQuery will simply use the Content-Type response header that the server returned and it will figure it out.
So bottom line: leave it to the framework figure it out unless you know exactly what you are doing.
Ah, and before I forget, please replace this:
public ActionResult Search(FormCollection improItem)
with:
public ActionResult Search(MyViewModel improItem)

Ajax request returns 200 OK, but an error event is fired instead of success

I have implemented an Ajax request on my website, and I am calling the endpoint from a webpage. It always returns 200 OK, but jQuery executes the error event.
I tried a lot of things, but I could not figure out the problem. I am adding my code below:
jQuery Code
var row = "1";
var json = "{'TwitterId':'" + row + "'}";
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(result) {
alert("hello");
alert(result.d);
}
function AjaxFailed(result) {
alert("hello1");
alert(result.status + ' ' + result.statusText);
}
C# code for JqueryOpeartion.aspx
protected void Page_Load(object sender, EventArgs e) {
test();
}
private void test() {
Response.Write("<script language='javascript'>alert('Record Deleted');</script>");
}
I need the ("Record deleted") string after successful deletion. I am able to delete the content, but I am not getting this message. Is this correct or am I doing anything wrong? What is the correct way to solve this issue?
jQuery.ajax attempts to convert the response body depending on the specified dataType parameter or the Content-Type header sent by the server. If the conversion fails (e.g. if the JSON/XML is invalid), the error callback is fired.
Your AJAX code contains:
dataType: "json"
In this case jQuery:
Evaluates the response as JSON and returns a JavaScript object. […]
The JSON data is parsed in a strict manner; any malformed JSON is
rejected and a parse error is thrown. […] an empty response is also
rejected; the server should return a response of null or {} instead.
Your server-side code returns HTML snippet with 200 OK status. jQuery was expecting valid JSON and therefore fires the error callback complaining about parseerror.
The solution is to remove the dataType parameter from your jQuery code and make the server-side code return:
Content-Type: application/javascript
alert("Record Deleted");
But I would rather suggest returning a JSON response and display the message inside the success callback:
Content-Type: application/json
{"message": "Record deleted"}
You simply have to remove the dataType: "json" in your AJAX call
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'json', //**** REMOVE THIS LINE ****//
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
I've had some good luck with using multiple, space-separated dataTypes (jQuery 1.5+). As in:
$.ajax({
type: 'POST',
url: 'Jqueryoperation.aspx?Operation=DeleteRow',
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'text json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
This is just for the record since I bumped into this post when looking for a solution to my problem which was similar to the OP's.
In my case my jQuery Ajax request was prevented from succeeding due to same-origin policy in Chrome. All was resolved when I modified my server (Node.js) to do:
response.writeHead(200,
{
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "http://localhost:8080"
});
It literally cost me an hour of banging my head against the wall. I am feeling stupid...
I reckon your aspx page doesn't return a JSON object.
Your page should do something like this (page_load)
var jSon = new JavaScriptSerializer();
var OutPut = jSon.Serialize(<your object>);
Response.Write(OutPut);
Also, try to change your AjaxFailed:
function AjaxFailed (XMLHttpRequest, textStatus) {
}
textStatus should give you the type of error you're getting.
I have faced this issue with an updated jQuery library. If the service method is not returning anything it means that the return type is void.
Then in your Ajax call please mention dataType='text'.
It will resolve the problem.
You just have to remove dataType: 'json' from your header if your implemented Web service method is void.
In this case, the Ajax call don't expect to have a JSON return datatype.
See this. It's also a similar problem. Working I tried.
Dont remove dataType: 'JSON',
Note: Your response data should be in json format
Use the following code to ensure the response is in JSON format (PHP version)...
header('Content-Type: application/json');
echo json_encode($return_vars);
exit;
I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:
public JsonResult ActionName(){
// Your code
return Json(new { });
}
Another thing that messed things up for me was using localhost instead of 127.0.0.1 or vice versa. Apparently, JavaScript can't handle requests from one to the other.
If you always return JSON from the server (no empty responses), dataType: 'json' should work and contentType is not needed. However make sure the JSON output...
is valid (JSONLint)
is serialized (JSONMinify)
jQuery AJAX will throw a 'parseerror' on valid but unserialized JSON!
I had the same problem. It was because my JSON response contains some special characters and the server file was not encoded with UTF-8, so the Ajax call considered that this was not a valid JSON response.
Your script demands a return in JSON data type.
Try this:
private string test() {
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize("hello world");
}

Ajax query to my webservices is returning xml in my json

I am having this exact problem as raised in this question
ASP.NET JSON web service always return the JSON response wrapped in XML
It's late and I have been sitting in this chair for 10 hours now trying to get ajax and json to work and all I got was deeply frustrated.
So does anyone know how to make my webservice not return my json object wrapped in xml? If I just do a straight dataType: "json" then I get nothing. I have to do dataType: "jsonp" to get anything back from the server at all. But once I do jsonp I get my json wrapped in xml.
Please help
Thanks
Cheryl
If you set the response type to json jQuery is then checking the response to see if it's valid JSON (and since it's XML, that's not the case)...when it's not valid, it silently fails since jQuery 1.4+.
There are 3 important bits when making your request, by default it needs to be a POST and you need to set the contentType to "application/json; charset=utf-8" like this:
$.ajax({
url: 'MyService.asmx/Method',
type: 'POST',
data: myData,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
//do something with data
}
});
Then on the server-side make sure you have the ScriptService attribute set, here's an example very minimal layout:
[WebService] //here by default when you create the service
[ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
public MyObject MyMethod(int id)
{
return new MyObject();
}
}

Categories

Resources