No params in route for ajax post - scalatra

When I post data to a Scalatra route, no params are seen.
On the client:
$.ajax({
type: 'POST',
url: window.location.origin + '/move',
contentType: 'application/octet-stream; charset=utf-8',
data: {gameId: 1, from: from.toUpperCase(), to: to.toUpperCase()},
success: function(result) {
console.log('ok posting move', result);
},
error: function(e) {
console.log('error posting move', e);
}
});
In dev tools network view:
Payload
gameId=1&from=B1&to=C3
In Scalatra route:
params("gameId") // -> java.util.NoSuchElementException: key not found: gameId
However, if I change the ajax call by removing the data field and setting the url to:
type: 'POST',
url: window.location.origin + '/move?gameId=1&from=' +
from.toUpperCase() + '&to=' + to.toUpperCase(),
Then Scalatra can see the params OK, even though it seems wrong to put params in the query string for a post.
Why can't Scalatra see any params when posting data?

You need to use application/x-www-form-urlencoded as content type:
script(type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js")
:javascript
$(function() {
$("#btn").click(function() {
$.ajax({
type: 'POST',
url: window.location.origin + '/form',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: {gameId: 1, from: "FROM", to: "TO"}
});
});
});
span#btn hello
In your Scalatra application:
post("/form") {
val payload = for {
gameId <- params.getAs[Int]("gameId")
from <- params.getAs[String]("from")
to <- params.getAs[String]("to")
} yield (gameId, from, to)
payload
}
For details please take a look at the Servlet specification.

Related

CSRF token missing - django/ajax

CSRF token missing - django/ajax
Have already tried each and every solution proposed in this article but nothing seems to work for me.
"CSRF token missing or incorrect" while post parameter via AJAX in Django
$(document).on('click', '.attendance_submit', function(){
var urlname = '{% url "test" %}'
var tableSel = $('.attendance_table tr:not(.group)');
alert("DATA :"+html2json(tableSel));
$.ajax({
url : urlname,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: {
csrfmiddlewaretoken: '{% csrf_token %}',
'TableData': html2json(tableSel)
},
success:
alert('Attendance updated successfully')
});
return false;
});
PS:
CSRF Token is also enabled in the form which I am using in this template, even tried removing from the form but to no avail.
I was finally able to solve this problem using the below code
#SeriForte 's answer pointed me in the right way when I was trying to troubleshoot some other issue.
{ "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" }
$(document).on('click', '.attendance_submit', function(){
var urlname = $(this).attr('data-url');
var tableSel = $('.attendance_table tr:not(.group)');
const csrftoken =
document.querySelector('[name=csrfmiddlewaretoken]').value;
alert("DATA :"+html2json(tableSel));
$.ajax({
url : urlname,
method: 'POST',
headers:{
contentType: 'application/json',
'X-CSRFToken': csrftoken
},
body: JSON.stringify(html2json(tableSel)),
success:
alert('Attendance updated successfully')
});
return false;
});

Pass an ID from Ajax to a Django view

I have a Django view that accepts an ID and returns a Json Response. Now on Ajax, I want to call the django view with an ID.
Here is my AJAX:
$(document).ready(function () {
$("#button").click(function () {
var id = 25;
$.ajax({
type: "POST", # Added here. Now error message changed
url: "/account/check_id/"
data: {
id: id,
},
dataType: "json",
success: function (data) {
if (data.is_taken) {
alert("ID is available");
}
},
});
});
});
Additional Data:
url:
path('check_id/<int:id>/', hrViews.check_id, name='check_id'),
view:
def check_id(request, id, *args, **kwargs):
However, when I click on button, I get error message
GET http://localhost:8000/account/check_id/?id=25 404 (Not Found). The ?id= is causing the error. How to remove it?
EDIT
After adding type: "POST", got message
POST http://localhost:8000/account/check_id/
How to pass ID here?
Note. Based on w3schools, the data{} is used to pass information to server. So I think that I should pass my ID here. However, my url does not get the ID from data. Please correct me on this if my assumption is wrong.
So I made some changes and this is what worked for me.
$(document).ready(function () {
$("#hold").click(function () {
var id = 25;
$.ajax({
url: "/account/check_id/" + id,
dataType: "json",
success: function (data) {
if (data.is_taken) {
alert("ID is available");
}
},
});
});
});
Removed the type: "POST", then concatinate on URL with my ID. It works so I will go with this based on my use case.

How to update the model from the ajax by rest framework(csrf problem??)

I want to update the table row by from ajax
From auto generated form (by rest framweorks) posting and updating works correctly.
However from ajax it shows
"POST /api/issues/372/ HTTP/1.1" 403 58 error
I googled around and found that this is related with csrt.
However How can I send correct json???
var json = {
"id": 37;
"name": "This is my new name",
"color": "#dddddd"
};
$.ajax({
type:"POST",
url: "{% url 'issues-detail' 372 %}",
data:JSON.stringify(json),
contentType: 'application/JSON',
dataType: "JSON",
success: function(response) {
console.log(response);
},
error: function(response) {
console.log(response);
},
complete: function() {
console.log("complete");
}
});
you can add this code to your js file in document.ready function
$(document).ready(function() {
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url)))
{
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
}
}
});
});
For sending POST request we need to set csrf-token.

Laravel 5.6 Passport token in ajax

I was writing below code in Token Guard before using Passport authentication.
$.ajax({
method: "POST",
url: "{!! route('ViewProfile') !!}?api_token={!! \Auth::user()->api_token !!}",
cache: false,
async: true,
success: function(result) {
},
error: function(result) {
}
});
Now, I am changing my code to adapt Laravel Passport authentication. I have no problem in creating the token and fetching it using below code.
$token = $UserData->createToken(env("Token_Source_Website"))->accessToken;
Question: I was searching for a tutorial about how to send the ajax request to get user details using this token? I meant, will I use something else instead of api_token = somevalue?
It has to be like below. Make sure there is space after Bearer in headers.
$.ajax({
method: "POST",
url: "{!! route('ViewProfile') !!}?api_token={!! \Auth::user()->api_token !!}",
cache: false,
async: true,
headers: {"Authorization": "Bearer " + localStorage.getItem('token')},
success: function(result) {
},
error: function(result) {
}
});
One can get the token through below code.
$token = $UserData->createToken(env("Token_Source_Website"))->accessToken;

Writing to DynamoDB table using API Gateway and Lambda from a Web page

Part of the project, I want to write data entered into my web page from onto to a DynamoDB database, for this, I have written a Node.js code in AWS lambda to write items into a DynamoDB table. Created a web page form with more than one entries for users to fill required information and created an API Gateway to connect Lambda and HTML web page. Below are the codes for Lambda, API gateway, and HTML form. Please go through them.
Lambda My code:
exports.handler = function (e,ctx,callback) {
"use strict";
var params = {
Item : {
marchp : e.stepno,
Prev_step_no :e.prevstepno,
Next_step_no: e.nextstepno,
Inputdata : e.inputdata,
Acknowledgement: e.acknowledgement,
Condition: e.condition,
},
TableName : 'MARCHPevents'
};
API Gateway Body Mapping Templates:
{
"stepno": $input.json("$.stepno"),
"prevstepno": $input.json("$.prevstepno"),
"nextstepno": $input.json("$.nextstepno"),
"inputdata": $input.json("$.inputdata"),
"acknowledgement": $input.json("$.acknowledgement"),
"condition": $input.json("$.condition")
}
HTML Code pasing data to API gateway:
url:API_URL,
success: function(data){
$('#entries').html('');
data.Items.forEach(function(MARCHPreventsItem){
$('#entries').append('<p>' + MARCHPreventsItem.InputData + '</p>');
})
}
});
});
$('#submitButton').on('click', function () {
$.ajax({
type: 'POST',
url: API_URL,
data: JSON.stringify({ "stepno": $('#s1').val() }),
data: JSON.stringify({ "prevstepno": $('#p1').val() }),
data: JSON.stringify({ "nextstepno": $('#n1').val() }),
data: JSON.stringify({ "inputdata": $('#msg').val() }),
data: JSON.stringify({ "acknowledgement": $('#ack').val() }),
data: JSON.stringify({ "condition": $('#con').val() }),
contentType: "application/json",
success: function (data) {
location.reload();
}
});
return false;
});
If on passed one value from HTMLwebpage form to API gateway to passing to perfectly to Lambda which writing that one value to DynamoDB.
Problem Facing is passing more than one value from HTML web page form to API gateway this time it is having an invocation error at Lambda
Any Help?
Your JavaScript looks incorrect - you are overwriting the data parameter. You need to set the properties on the data object, i.e.
var obj = {
stepno : ${'#s1'}.val(),
prevstepno : ${'#s2'}.val(),
...
}
$.ajax({
type: 'POST',
url: API_URL,
data: obj,
contentType: "application/json",
success: function (data) {
location.reload();
}
});