Sending JSON List Of Object to Spring MVC controller - ajax

I have an issue with sending a List Of Objects to Spring MVC controller .
The list of object is like this
[{"alias":"1",
"rue":"Rue de la Senette",
"codePostal":"78955",
"ville":"Carrières-sous-Poissy",
"rueComplement":""}]
And I send the above data with the following AJAX code:
$.ajax({
type : 'POST',
dataType : 'json',
contentType :'application/json',
url : $("#clientForm-add").attr('action'),
data : JSON.stringify(adresses.toArray()),
});
When I use this form of ajax, it worked for me and the format sended is as follow:
Request Payload :
[{"alias":"1",
"rue":"Rue de la Senette",
"codePostal":"78955",
"ville":"Carrières-sous-Poissy",
"rueComplement":""}]
Yes, even the above one is worked, when i send it like as follow:
$.ajax({
type : 'POST',
dataType : 'json',
contentType :'application/json',
url : $("#clientForm-add").attr('action'),
data : {adresseList : JSON.stringify(adresses.toArray())},
});
It doesn;t work for me. The sending data is look like
listAdresse=%5B%7B%22alias%22%3A%221%22%2C%22rue%22%3A%22Rue+de+la+Senette%22%2C%22codePostal%22%3A%2278955%22%2C%22ville%22%3A%22Carri%C3%A8res-sous-Poissy%22%2C%22rueComplement%22%3A%22%22%7D%5D
Response Headersview source
And, It gave an error: 400 bad request
Here, my controller
#RequestMapping(value = "creerlivraison/ajouterclientBD",method=RequestMethod.POST)
public String ajouterClientBD(#RequestBody Adresse[] listAdresse, Principal principal) {
for (Adresse adresse : listAdresse) {
System.out.println(adresse);
}
return "ok";
}
I want to know that "What is the difference between the two ajax request?", why the request payload is formatted when I wrap the data inside the braquets {} and specify listAddress.
Here is screen capture:

http://api.jquery.com/jquery.ajax/
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
In this instance,
JSON.stringify(adresses.toArray()) is string, just keep the JSON format.
{adresseList : JSON.stringify(adresses.toArray())} is an object, so it is converted to a query string.

Related

Handle binary data at backend using golang

I don't even know if i had asked the right question or not, but here it go anw.
The question is which data type in golang i should use to store binary data
In the front end i using vuejs and sending a file with axios post request using formData as request body.
1 field in this body is a file which if i check in the devtool it show as (binary) like this : enter image description here
and if i console log it's type then it show as an object
In the front end i send the request :
CreateAccount(){
var formData = new FormData();
formData.append('cv',this.cv);
axios({
method : 'post',
url : 'http://localhost:1323/restricted/Profile',
headers: {
'Authorization' : 'Bearer ' + this.$store.state.token,
'Content-Type': `multipart/form-data;`,
},
data : formData})
In the backend with golang, i use []byte to store this data like this :
Cv []byte `json:"cv" form:"cv" query:"cv"`
But this field return as an empty array, maybe there is a missmatch data type in here so they just don't store my data ?? please help. I have struggle with this 1 task(sending a file in the front end and receive that file in the backend, store it in the postgre db) for more than 3 days
Ther are actually no error. It just that mine Cv varible in the backend return empty, there are nothing in it whereas the other field had the correct value

Prevent encoding in #FormUrlEncoded retrofit

I need to make a post request such that the json data passed, has key pair value,where the key is data.
For example, if i use jquery as below, data is the key.
$.ajax({
url: “/hello",
data:{ data: JSON.stringify(dataObject) },
type:"POST",
dataType:"json"
});
which is equivalent to
data:{ data: {“firstName”:”john”,"lastName”:”doe”}}.
I am using java spring retrofit, to accomplish the similar. In order to pass the key, i am using #FormUrlEncoded and #Field("data") TypedString userInfo
My retrofit interface is as below
public interface userInfoService {
#FormUrlEncoded
#POST(“/hello")
public Response userInfo(#Field("data") TypedString userInfo);
where TypedString is {"firstName":"john","lastName":"doe"}
However, the request looks something like this
data=%7B%22firstName%22%3A%22john%22%2C%22lastName%22%3A%22doe%22%7D, since it form url encoded.The 3 party api can see the data key, but since it has "=" instea of ":", it cant be parsed
How, do i get the request to avoid = and actually send a decoded request.
I have also tried to use #Body instead of #FormUrlEncoded and #Field. Where #Body has TypedString as {data: {“firstName”:”john”,"lastName”:”doe”}}, but for some reason the 3 party api is not able parse the data key.

sendAJAX data parameter in CasperJs

again, I got another problem with casperjs, now with sendAJAX function.
It says that sendAJAX has 5 parameters which are these followings :
url: The url to request.
method: The HTTP method (default: GET).
data: Request parameters (default: null).
async: Flag for an asynchroneous request? (default: false)
settings: Other settings when perform the AJAX request (default:
null)
So, it says the data method is object so, it should be filled with :
var data = new Object();
data.amount= 15;
and also with this one,
var data = {amount:15};
but there were no successful value send to my web service (always send 0 as value, but ajax request successful, even returning the json data) which has an url like this
"http://localhost:9000/TempCountryAmountREST/setCountryAmount"
It will be succeed if I direct bind my data variable to my url like this :
"http://localhost:9000/TempCountryAmountREST/setCountryAmount?amount="+amount
[UPDATE]
The TempCountryAmountREST is my controller name and setCountryAmount is my function inside my controller.
[UPDATE]
I forgot to include my usage of sendAJAX(), here is the code that I use :
return JSON.parse(__utils__.sendAJAX(wsurl, "POST" , data, false, { contentType: "application/json" }));
So how does I fill the data in the sendAJAX parameter?
Thanks in advance...
Sorry, I've found what the answer is.
I make some mistakes in contentType which I was set with contentType: "application/json" instead of contentType: "application/x-www-form-urlencoded" }
If we are looking about how ajax send the content from method send(), they were use x-www-form-urlencoded. See this for more detail
When we see through casperjs clientutils.js script, we should found how sendAJAX work.
On the `this.sendAJAX = function sendAJAX(url, method, data, async, settings) {
}
there are url construction logic which transformed our Object (if so) to x-www-form-urlencoded form. So that we need to set our contentType as application/x-www-form-urlencoded
Very well, thanks for your attention...

Parsing Json results in uncaught syntax error

My browser (chrome) tells me this is what is being returned from the server which I have verified as being valid via JsonLint:
[{"Id":"bdd937ef-c0d4-4191-805f-316288144060","Name":"Accessories and Auto Parts, Moto ","L18nName":null,"State":null,"L18n":"1033","Index":0,"LevelId":0,"ImagePath":"/content/img/browse/sm/","Children":[]},{"Id":"b01bde48-6f1d-4168-aee4-a7e62eef7bd0","Name":"Car Rental","L18nName":null,"State":null,"L18n":"1033","Index":0,"LevelId":0,"ImagePath":"/content/img/browse/sm/","Children":[]},{"Id":"c039a467-1709-433f-a316-008f6ae301fb","Name":"Car Sales ","L18nName":null,"State":null,"L18n":"1033","Index":0,"LevelId":0,"ImagePath":"/content/img/browse/sm/","Children":[]}]
If I just copy this content into a script var it will also parse correctly.
However if i try and parse this content, as returned from the server, into an object I get an Uncaught Syntax error:
$.ajax({
type: "POST",
url: "/Browse/SubCategoryLister/",
data: { rfqID: parentRfqId },
dataType: "json"
})
.done(function (data) {
rp.hide();
sc.show();
console.log(data);
var status = JSON.parse(data);
console.log(status);
});
On the line
var status = JSON.parse(data);
However
console.log(data);
seems to produce a valid object that I can interrogate via developer tools:
So it seems like the data is already a json object? So Im not quite sure what is going on here. I thought it might have something to do with response headers but this payload is being sent down with an:
Content-Type:application/json; charset=utf-8
header just like in other pages in the application where i use JSON.parse(data); to create a JSON object from server returned data. So what is the difference here and why cant I parse it? If it's already a JSON object then how an where was it created?
You parse json twice. Data parameters function (data) is already javascript object, because you've used dataType: "json". From jQuery docs:
"json": 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. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)
You don't need to call var status = JSON.parse(data);. Just use data as you'd use result of JSON.parse.
Update
Also if your server return json content type, then jQuery will choose dataType to be "json". From docs:
If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

Making jQuery $.ajax call to Twitter API 1.1 search

Here is a very simple example of a call to Twitter's search API to get all tweets from a tag known to have tweets, #fml.
I believe I am correctly using the application-only authentication as explained here: https://dev.twitter.com/docs/auth/application-only-auth (see Step 3 for example of a call)
I am being asked for a solution that does not involve any server-side code so I am including the bearer code in the javascript, which isn't good to begin with, but....
I would expect this code to work. Instead it produces the error '400 (Bad Request)'. Any ideas?
$.ajax({
url: "https://api.twitter.com/1.1/search/tweets.json",
dataType: "jsonp",
data: "q=%23fml",
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Bearer XXmyBearerCodeXX");
},
success: function(json){ alert(json); }
});
EDIT 1 - Validated Twitter call
Using hurl.eu I was able to get a successful response from the API with the above query and Authorization header, so I assume this means my Twitter call is correct, just not set up correctly within jQuery.ajax(), but I just don't see what is missing.
You cannot set request headers using AJAX calls with dataType JSONP.
See this question: Set Headers with jQuery.ajax and JSONP?
The best solution is to use a server-side proxy to do the search for you. I know you are looking for a client only solution, but with this restriction, and with no way around CORS, this is how it seems to be done today for the Twitter API.
Edit It may be possible using a proxy like Yahoo's YQL if you don't have access to one.
on your severside create a jsp or servlet and from the client side make a JSON call to the .jsp/servlet and that will return back the json object to the javascript. In serverside use the twitter4j api.
sample code:
`
$.getJSON(http://localhost:8080/test.jsp?callback=?",
{
jspqueryStr : queryStr,
jspgeocodeStr : geocodeStr,
lat:latStr,
lan:lngStr,
radius:radiusStr,
}, displayResult);
//This function returns the data as json object from server.
function displayResult(data) {}
In the jsp the code is like below
<%
String jspqueryStr = request.getParameter("jspqueryStr");
String jspgeocodeStr = request.getParameter("jspgeocodeStr");
String diseasename = request.getParameter("jspqueryStr");
String lat = request.getParameter("lat");
String lan = request.getParameter("lan");
String radius = request.getParameter("radius");
Gson gson = new Gson();
String json = gson.toJson(tweetList);
json = request.getParameter("callback") + "(" + json + ");";
out.println(json);
public List<Status> searchstream(){
//here all the twitter4j api code to get the data
retrun tweetList;
}
%>
`

Resources