Error: (index):186 Uncaught SyntaxError: Invalid shorthand property initializer - django

I am getting this error while sending my form through Ajax in Django
Error: (index):186 Uncaught SyntaxError: Invalid shorthand property initializer
in line
data= formdata
Can you help me figure out the solution.
uploadBtn.addEventListener('click', e=>{
e.preventDefault()
progressBox.classList.toggle('not-visible', false)
var formdata = new FormData()
formdata.append('csrfmiddlewaretoken', csrftoken)
formdata.append('fileA', FileA.files[0])
formdata.append('a_year', year.value)
$.ajax({
type: 'POST',
url: '',
enctype: 'multipart/form-data',
data = formdata,
success: function(response){
console.log(response)
},
error: function(response){
console.log(response)
},
cache: false,
contentType: false,
processData:false,
})
})

You need to use a colon not =.
Like so:
data: formdata,
not:
data = formdata,

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;
});

Prevent page refresh when submitting Django form

Is there any way to stop refreshing of the form page after hitting submit button?
I am looking for doing this in front end using javascript.
Yes it's possible. jQuery Ajax is good idea
$(document).ready(function(){
$("#submit").on("click", function(){
var form = $("#form").serialize();
$.ajax({
type:"POST",
url:"{% url 'url to view' %}",
data: form,
success:function(data){
// Something success
},
error:function(data){
//When error occurred
},
});
});
});
I was able to achieve this by the following:
var formImage = $("#form_image");
formImage.submit(function (e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (msg, status, jqXHR) {
console.log(msg);
console.log(status);
console.log(jqXHR);
},
cache: false,
contentType: false,
processData: false
});
});

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;

Create Item by using Item web api

I want to know how implement javascript method to create new item by using sitecore item web api.I am trying for below code my self.
But in the browser console show this error:
XMLHttpRequest cannot load http://myproject/-/item/v1/sitecore/Content/Home?name=MyItem5&template=Sample/Sample%20Item&sc_database=master. Request header field X-Scitemwebapi-Password is not allowed by Access-Control-Allow-Headers.
Please can anyone help me!!!!!!!
function createItem(){
jQuery.ajax({
crossDomain: 'true',
type: 'POST',
url: 'http://myproject/-/item/v1/sitecore/Content/Home?name=MyItem5&template=Sample/Sample Item&sc_database=master',
dataType: 'JSON',
contentType: 'application/x-www-form-urlencoded',
headers:{
"X-Scitemwebapi-Username":"sitecore\\Admin",
"X-Scitemwebapi-Password":"b",
},
success: function(data) {
alert(JSON.stringify(data));
},
error: function(res, error){
alert(JSON.stringify(res))
alert(res+ ' something is wrong');
}
});
}
Make sure you have these settings in your Sitecore.ItemWebApi.config
itemwebapi.mode="StandardSecurity"
itemwebapi.allowanonymousaccess="false"/>

No params in route for ajax post

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.