Prevent page refresh when submitting Django form - django

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

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.

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

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,

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;