Page still refreshing while using ajax with django - ajax

I'm using my own custom form. Which looks like:
{%extends 'base_template.html'%}
{%block title%}
<title> Simple Ajax Demo </title>
{%endblock%}
{%block javascript%}
<script>
$(document).ready(function(){
$("#formi").submit(function(event){
$.ajax({
type:"POST",
url:"{% url 'haha:ajax' %}",
data: {
username : $('#username').val(),
password : $('#password').val(),
csrfmiddlewaretoken: {% csrf_token %},
},
success: function(data){
alert('asdas');
},
});
});
});
</script>
{%endblock%}
{%block content%}
<div>
<form method="post" id="formi">
{%csrf_token%}
Username:<input type="text" id="username"><br>
Password:<input type="text" id="password"><br>
<button type="submit">Click Me</button>
</form>
</div>
{%endblock%}
I've got two input fields with name password and username, to be saved to the table User.
View.py
def ajax(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
Users.objects.create(username=username, password=password)
return render(request,'core/ajax.html')
I've tried with the GET method too. But still the page gets refreshed. Also tried firing the Ajax call while clicking the button, but it says something like multiple-dict value error. Also tried with
username = request.POST.get('username')
password = request.POST.get('password')

Edit onSubmit event as
$("#formi").submit(function(event){
event.preventDefault();
$.ajax({
/* you have type here change it to method */
method:"POST",
url:"{% url 'haha:ajax' %}",
data: {
username : $('#username').val(),
password : $('#password').val(),
csrfmiddlewaretoken: {% csrf_token %},
},
success: function(data){
alert('asdas');
},
});
}
It is the default behaviour of onSubmit to refresh the page whenever we submit the form. By event.preventDefault(); we are pausing that default behaviour.

Just modified the jquery code, works well!! Here's a code:
{%extends 'base_template.html'%}
{%block title%}
<title> Simple Ajax Demo </title>
{%endblock%}
{%block javascript%}
<script>
$(document).on('submit','#formi',function(event){
event.preventDefault();
$.ajax({
method:"POST",
url:"{%url 'haha:ajax'%}",
data: {
username : $('#username').val(),
password : $('#password').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success: function(data){
alert('asasd');
},
});
});
</script>
{%endblock%}
{%block content%}
<div>
<form id="formi" method="post">
{%csrf_token%}
Username:<input type="text" name="username" id="username"><br><br>
Password:<input type="text" name="password" id="password"><br><br>
<input type="submit" value="Click Me"><br>
</form>
</div>
{%endblock%}
But i don't understand why is document.on('submit','#formi'){} is working?

Related

Refresh the likes counter without reloading the Ajax page

It was necessary to write a method for salting posts in php and decorate the whole thing with ajax so that the page would not reload. The method was written, likes are put, but for the changes to be visible, you need to reload the page. I suspect I made a mistake in the area of success
This is part of the post, you need to update the button with id = "likebtn {{$ post-> id}}"
html form
<form action="{{route('likePost', ['id' => Auth::user()->id, 'postId' => $post->id])}}" method="POST" id="likepostform{{$post->id}}">
#csrf #method('PATCH')
<button data-id="{{$post->id}}" id="likebtn{{$post->id}}" type="submit" class="likebtn button-delete-post-2">
<img src="{{asset('img/footer/like.png')}}" class="img-fluid" width="25"><small class="text-muted mr-4">{{$post->likepost}}</small>
</button>
<input type="hidden" value="{{Auth::user()->id}}" id="user_id">
</form>
Ajax
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click",".likebtn",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
var user_id = $("#user_id").val();
$.ajax({
url: "id"+user_id+"/"+id+"/like",
type: 'PATCH',
data: {_token: token, id: id, user_id: user_id},
success: function (data){
$("#likebtn"+id).html($(data).find("#likebtn"+id).html());
},
error: function() {
alert('error');
}
});
});
});
</script>

Laravel Ajax update request is duplicating data

i am trying to update data using ajax, but my data is being duplicated,
due to ajax URL, i am not sure if i am passing correctly/
Ajax Code:
jQuery(document).ready(function($) {
$('#update-form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "teachers/" + $('#update-id').attr("value"), //error is here
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
success: function (data) {
alert("updated");
},
});
});
});
view code:
i have table with list of teachers, and edit button for each teacher;
<button type="button" id="btn" value="{{ $teacher->id }}" class="btn btn-primary btn-block btn-sm edit-btn">Edit</button>
in form i have hidden field
<form method="post" id="update-form">
{{ method_field('PATCH') }}
<input type="hidden" id="update-id" value="{{$teacher->id}}" >
<div class="">
<label for="efirst">efirst</label>
<input type="text" class="form-control" name="efirst" id="update-efirst">
<textarea name="esecond" class="form-control" id="update-esecond" rows="6"></textarea>
</div>
<button type="submit" class="btn btn-success" id="update-submit">Update</button>
</form>
when i click on update, teacher ID's are being changed, one teacher id becomes another teacher id. is it correct way to pass teacher id from hidden field?
Write route name like below
At Web.php
Route::post("teacher/{id}/edit","YourController")->name("teacher.update");
At Blade File
$('#update-form').on('submit', function (e) {
e.preventDefault();
var id = $('#update-id').val(); // $('#update-id').attr("value") also ok
$.ajax({
method: "post",
url: "{{ route('teacher.update',id) }}",
dataType: 'json',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data : $(this).serialize(),
success: function (data) {
alert("updated");
},
});
});
Try this.
It will be work

Django csrf_token works in one form but not in other

I have a page with two lists: for tasks (tareas) and sales (ventas). When you click their links each one opens it´s own modal and retrieves the info with AJAX.
One works with no problem (tareas). The other one gives me a csrf_token error.
I thought maybe it was a problenm of using two tokens in the same template, but I´m doing it in other templates with no problem.
And if I completely remove the tareas part, the ventas one still get´s the same error.
Venta form call
<form name="ventas_form" action="#" id="form_venta_{{operacion.comprobante}}" method="POST">
{% csrf_token %}
<input name="id" id="venta_id_submit" type="text" value="{{operacion.comprobante}}" hidden="true"/>
<a style="padding-left: 1rem;" href="" id="{{operacion.comprobante}}" class="show_venta" data-toggle="modal" >{{operacion.comprobante}}</a>
</form>
Tarea form call
<form name="form" action="#" id="form_tarea_{{tarea.id}}" method="POST">
{% csrf_token %}
<input name="id" id="tarea_id_submit" type="text" value="{{tarea.id}}" hidden="true"/>
<a style="padding-left: 1rem;" href="" id="{{tarea.id}}" class="show_tarea" data-toggle="modal" >{{ tarea.titulo }}</a>
</form>
Venta Ajax
<script>
$(function(){
$('.show_venta').on('click', function (e) {
e.preventDefault();
let venta_id = $(this).attr('id');
$.ajax({
url:'/catalog/ventas-detail/',
type:'POST',
data: $('#form_venta_'+venta_id).serialize(),
success:function(response){
console.log(response);
$('.show_venta').trigger("reset");
openModalVentas(response);
},
error:function(){
console.log('something went wrong here');
},
});
});
});
function openModalVentas(venta_data){
$('#fecha').text(venta_data.venta.fecha);
$('#comprobante').text(venta_data.venta.comprobante);
$('#cliente').text(venta_data.venta.cliente);
$('#vendedor').text(venta_data.venta.vendedor);
$('#lista').text(venta_data.venta.lista);
$('#prod_codigo').text(venta_data.venta.prod_codigo);
$('#prod_nombre').text(venta_data.venta.prod_nombre);
$('#uds').text(venta_data.venta.uds);
$('#vu').text(venta_data.venta.vu);
$('#subtotal').text(venta_data.venta.subtotal);
$('#bonif').text(venta_data.venta.bonif);
$('#modal_ventas').modal('show');
};
</script>
Tarea Ajax
<script>
$(function(){
$('.show_tarea').on('click', function (e) {
e.preventDefault();
let tarea_id = $(this).attr('id');
$.ajax({
url:'/catalog/tareas-detail/',
type:'POST',
data: $('#form_tarea_'+tarea_id).serialize(),
success:function(response){
console.log(response);
$('.show_tarea').trigger("reset");
openModal(response);
},
error:function(){
console.log('something went wrong here');
},
});
});
});
function openModal(tarea_data){
$('#creador').text(tarea_data.tarea.creador);
$('#destinatario').text(tarea_data.tarea.destinatario);
$('#titulo').text(tarea_data.tarea.titulo);
$('#tarea').text(tarea_data.tarea.tarea);
$('#resuelto').text(tarea_data.tarea.resuelto);
$('#fecha_creacion').text(tarea_data.tarea.fecha_creacion);
$('#fecha_limite').text(tarea_data.tarea.fecha_limite);
$('#fecha_resuelto').text(tarea_data.tarea.fecha_resuelto);
$('#empresa').text(tarea_data.tarea.empresa);
$('#persona_empresa').text(tarea_data.tarea.persona_empresa);
$('#modal_tareas').modal('show');
};
</script>
Venta view
def VentaDetailView(request):
ID = request.POST.get('id')
ventas_todas = Ventas.objects.filter(pk=ID).get()
venta = {
"fecha": ventas_todas.fecha,
"comprobante": ventas_todas.comprobante,
"cliente": ventas_todas.cliente,
"vendedor": ventas_todas.vendedor.nombre,
"lista": ventas_todas.lista,
"prod_codigo": ventas_todas.prod_codigo,
"prod_nombre": ventas_todas.prod_nombre,
"uds": ventas_todas.uds,
"vu": ventas_todas.vu,
"subtotal": ventas_todas.subtotal,
"bonif": ventas_todas.bonif,
}
return JsonResponse({'venta': venta})
Tarea view
def TareaDetailView(request):
ID = request.POST.get('id')
tarea_select = Tareas.objects.filter(pk=ID).get()
tarea = {
"creador": tarea_select.creador.username,
"destinatario": tarea_select.destinatario.username,
"titulo": tarea_select.titulo,
"tarea": tarea_select.tarea,
"resuelto": tarea_select.resuelto,
"fecha_creacion": tarea_select.fecha_creacion,
"fecha_limite": tarea_select.fecha_limite,
"fecha_resuelto": tarea_select.fecha_resuelto,
"empresa": tarea_select.empresa.Nombre,
"persona_empresa": tarea_select.persona_empresa.nombre,
}
return JsonResponse({'tarea': tarea})
No idea why the tareas part works ... but for sure I would add 'X-CSRFToken' header to both ajax calls:
$.ajax({
url:'/catalog/ventas-detail/',
type:'POST',
data: $('#form_venta_'+venta_id).serialize(),
headers: {'X-CSRFToken': getCookie('csrftoken')}
...
});
where:
function getCookie(name) {
var value = '; ' + document.cookie,
parts = value.split('; ' + name + '=');
if (parts.length == 2) return parts.pop().split(';').shift();
}
You can add CSRF token to header like that too :
$.ajaxSetup({
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
});
Then you didn't need to manually add your CSRF token to all your ajax request.

django.utils.datastructures.MultiValueDictKeyError DJANGO

I have a form. When I post the form without using ajax, it works well. But when I use the ajax, I have an error like this;
django.utils.datastructures.MultiValueDictKeyError:
My codes are below that without using ajax. It works.
HTML Form:
<form id="add_form" action="/adding/" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input type="file" name="picture">
<button type="submit" id="send_form" value="ok">Ok</button>
</form>
My views.py codes are:
if request.method == "POST":
title = request.POST.get('title')
pic = request.FILES['picture']
query = Images_Table(title=title, pic=pic)
query.save()
My model codes are:
class Images_Table(models.Model):
title = models.CharField(max_length=70, blank=True, null=True)
pic = models.FileField(upload_to='images_folder', blank=True, null=True)
Until here; everythings are normal, codes works. When I use ajax, I have an error. My HTML Form:
<form id="add_form" method="post" enctype="multipart/form-data">
<input type="text" name="title">
<input type="file" name="picture">
<button id="send_form" value="ok">Ok</button>
</form>
My ajax codes are:
$("#send_form").click(function(){
$.ajax({
url: '/adding/',
method:'post',
data: $("#add_form").serialize(),
headers: '{{ csrf_token }}',
success : function(){
alert('Success posted!');
}
});
});
Error code is below;
django.utils.datastructures.MultiValueDictKeyError: "'picture'"
I solved the problem by changing ajax.
$("#send_form").click(function(){
var file_data = $('#picture').prop('files')[0];
var form_data = new FormData($('form').get(0));
form_data.append('file', file_data);
$.ajax({
url: '/adding/',
method:'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
headers: {'X-CSRFToken': '{{ csrf_token }}'},
success : function(){
alert('Success posted!');
}
});
});

File Data is blank array in server side: Laravel 5.3

I am trying to post File using JQuery. Below is my code.
<script language="javascript">
$(document).ready(function() {
$('#frmUpdateProfile').on("submit", function(event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data = {
"FileName" : event.target.FileName.files,
"_token" : "{!! csrf_token() !!}"
};
$.ajax({
url: '{{URL::route("UpdateProfile")}}',
method: "POST",
async: true,
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=utf-8",
success: function (msg) {
SuccessCallback(msg);
},
error: function (jqXHR) {
ErrorCallback(jqXHR);
}
});
});
});
</script>
I tried processData: false,. While debugging in Js, you can check that image is coming in the data. Below is the screenshot.
But when I print the request data in Laravel, it show blank array.
Html form is here
<form method="POST"
action="http://localhost:1234/AS6-Code/public/UpdateProfile"
accept-charset="UTF-8"
enctype="multipart/form-data"
id="frmUpdateProfile">
<input name="_token" type="hidden" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input type="hidden" name="_token" value="26KWkWdNqe5iOFE8VRBf1dRnL5xKxwN25jg3tAFW">
<input multiple="1" name="FileName" type="file">
<input class="btn btn-info" type="submit" value="Update">
</form>
Am I doing something wrong?
Try sending your request with FormData instead:
var data = new FormData($('#frmUpdateProfile')[0]);
Also set contentType to false:
contentType: false
Also Update
event.target.FileName.files
to
event.target.FileName.files[0]
event.target.FileName.files is a FileList object. I believe you need event.target.FileName.files[0] instead.

Resources