Spring portlet + Ajax json request body - ajax

I am using jQuery AJAX to make a resource call with JSON request body, since #requestbody is not supported in spring portlet. Any other way I can access the form data?
I tried using:
'url : '${saveLostItem}',
async : true,
type : "post",
cache : false,
data : {form_data:newmainform}'
In the controller side:
String mainForm = request.getParameter("form_data");
It is working fine, but the security team is not allowing this. saying the request is not a valid json. So I changed my AJAX to:
url : '${saveLostItem}',
async : true,
type : "post",
cache : false,
data : newmainform
without the key value, but I am unable to get request data in controller. Please help.

Related

AJAX Post to AWS API Gateway not working (405 Method not allowed), but its working with Postman

I built a small HTML form with bootstrap and I'm hosting it as a static Website in an AWS S3 Bucket. Then I added an AWS API Gateway and Lamda function so that the data from this form is stored into an AWS DynamoDB.
At this point, I can "Post" raw JSON Data via Postman to the API Gateway and the Lambda function is storing the data in the DynamoDB table. I created a .ajax in my Website to gather the data and send it as JSON. But I always get this error:
My AJAX:
$(document).ready(function(){
$("#form>button[type=submit]").click(function(event){
event.preventDefault();
let apiGatewayInvokeURL = 'https://gxt8igxck7.execute-api.eu-central-1.amazonaws.com/dev/test';
var body = {
KundenID : $("#KundenID").val(),
Vorname : $("#Vorname").val(),
Nachname : $("#Nachname").val(),
Telefonnummer : $("#Telefonnummer").val(),
Email : $("#Email").val(),
Strasse : $("#Strasse").val(),
Hausnummer : $("#Hausnummer").val(),
PLZ : $("#PLZ").val(),
Ort : $("#Ort").val(),
Ankunftszeit : $("#Ankunftszeit").val(),
Abreisezeit : $("#Abreisezeit").val(),
datencheck : $("#datencheck").val()
};
$.ajax({
type: 'POST',
url : apiGatewayInvokeURL,
crossDomain: 'true',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(body),
success: function () {
$("#form").trigger('reset');
alert('Successfull');
},
error: function (response) {
alert('Failed: HTTP ' + response.status);
}
});
});
});
I just can't seem to find the reason for this error. The API Gateway can clearly handle POST requests, but maybe I got the wrong idea about what I'm doing. If you need any further data just let me know.
Thanks in advance!
EDIT
Here is the Network Tab of Chrome while submitting:
It seems the Post request is going to the S3 Bucket Server instead of the API Gateway?
And Content-Type of my Request Header is application/x-www-form-urlencoded, shouldn't it be application/json?
EDIT LAST
Found the Error.. apparently
$("#form>button[type=submit]").click(function(event)
was not working as intended. Because of this
event.preventDefault();
was not called correctly and the form natively POSTED to the Website HOST which is S3 Bucket and is not allowing POST Requests. I changed the Code to
$("#btn").click(function(event){
event.preventDefault();
Now it's working like a charm after fixing some minor CORS errors.
Maybe this helps someone

How to send json serialize data from a form to ajax using django

Currently, I'm sending the data via code in this way and it's working but how can I send the entire form in json?
Code :
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
data : { csrfmiddlewaretoken : csrftoken,
email : email,
password : password,
username : username,
dob : dob,
}, // data sent with the post request
I want to send and retrieve everything including csrfmiddlewaretoken using formdata json.
I have tried something similar to that :
var formData = new FormData($('#my_form');
formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
data : formData, // data sent with the post request
But, this does not work for some reason. How can I get it to work?
you need to send json serialized form data as one paramater and csrf token as another parameter because every POST request expects a csrf token in it.
csrfmiddlewaretoken = $("#add_member_Form").find("input[name='csrfmiddlewaretoken']" ).val();
formData = $('#add_member_Form').serializeArray();
formData = JSON.stringify(formData);
$.ajax({
url : url,
data : {
"csrfmiddlewaretoken" : csrfmiddlewaretoken,
"formData" : formData
},
method: "POST",
dataType : "json",
At server side in your view, you need to deserialize the data.
form_data_dict = {}
form_data_list = json.loads(form_data)
for field in form_data_list:
form_data_dict[field["name"]] = field["value"]
return form_data_dict
You could grab the form data usingserializeArray function in jQuery, then convert it into dictionary and send as post data.
The serializeArray function output would be something like,
{
'name': 'the_name',
'value': 'the_value'
}
Then, you would have to convert it to the dictionary or json format. Write a global function for that,
function objectifyForm(formArray) {
var returnArray = {};
for (var i=0;i<formArray.length;i++) {
if (formArray[i].value) {
returnArray[formArray[i].name] = formArray[i].value;
}
}
return returnArray;
}
Call it whenever you have to grab the form data,
var formData = $('#my_form').serializeArray();
formData = objectifyForm(formData);
$.ajax({
url : window.location.href, // the endpoint,commonly same url
type : "POST", // http method
data : formData,
success: blaah,
error: bleeh,
});
It would be much less effort than having to decode the dictionary every time from the server side.

ajax request adding url paratemeters

I'm unsure if I'm just thinking of this the wrong way of thinking or I'm just missing something.
I have a search box that does some wildcard searches in a database. I have made this an ajax request so I don't need to reload the page and I can have a little please wait icon while the data loads.
Now as there is pagination so I could do with the url parameters being added to the url, can you do this on a ajax request, ad if so how?
here is a sample code (param1) :
data : $('#form-contactSupplementaire').serialize() + "&param1=value",
Request full ajax :
$.ajax({
method : "POST",
url : "...",
data : $("...").serialize() + "&param1=value",
dataType: "",
success : function (json) {
// ...
console.log(json);
}, error: function () {
console.log("Error");
}
});

Rest API Ajax Call Add parameter to URL

Mostly, rest api url' s like:
/api/student:id/notes
I create a rest api and my urls like above. But I dont know how to add parameter before notes.
$.ajax({
url : "api/v1/student/notes",
data : { "id" : uid },
type : "get",
headers : { "Authorization" : api_key },
dataType : "json",
success : function(response) {
console.log(response);
}
});
When I call like this, the url seems /api/student/notes?id=5. How can Iadd id parameter between student and notes?
Example url: http://www.sitepoint.com/best-practices-rest-api-scratch-introduction/
AFAIK, jQuery does not offer a neat API for injecting resource URI fragments like Angular's $resource. You'll have to build the URL yourself. Something like
$.ajax({
url: 'api/v1/students/' + encodeURIComponent(uid) + '/notes',
// and so on, no "data" required.

kendo datasource sending jquery string

I have this Kendo UI datasource. I am trying to pass the data parameter
transport: {
read: {
url: "http://clientstoprofits.paupertopresident.com/api/Schedule/Tasks_Read",
data:{
UserId:id,
startDate:startTime
},
dataType: "jsonp"
},
but the only thing that is being sent is
Request URL:http://mydomain.com/api/Schedule/Tasks_Read?callback=jQuery19107631381487008184_1398210088201&_=1398210088207
can anybody tell me why i am getting this callback=Jquery*?
The callback url parameter is the name of the callback jQuery created for this JSONP request (for a more detailed explanation, take a look at the dataType option for jQuery.ajax().
As to why your data is not being sent: you can only do that with POST requests, and JSONP requests are by definition GET requests. So you'll have to encode the user id and start date as url params instead.

Resources