AJAX form submission in Django - javascript

I keep receiving 'Not Ajax' as a response during my form submission. I have to be missing something small but I cannot see it...
class VideoLikeView(View):
def post(self, request):
if request.is_ajax():
message = 'Ajax'
else:
message = 'Not Ajax'
return HttpResponse(message)
The AJAX code looks like this:
$(function () {
$("#like-form").submit(function (event) {
$.ajax({
type: "POST",
url: form.attr('action'),
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: {'pk': $(this).attr('value')},
success: function(response) {
alert('Video liked');
},
error: function(rs, e) {
alert(rs.responseText);
}
}
});
});
});
And my HTML:
<form id="like-form" action="{% url 'video-like' %}" method="post">
{% csrf_token %}
<input name="like"
type="hidden"
value="{{ video.id }}">
<button type="submit">
<span class="video-options ml-auto fas fa-heart fa-2x m-2"></span>
</button>
</form>
One question to add to this; how can I use an <input> in my form without using a <button>? I would like to use fontawesome icons but it seems I have to use a button to get the form to submit.

I found one answer on the internet that seems to work but I don't understand what the issue was. Seems like some type of serialization needed (?)... Anyways, here is what worked:
var frm = $('#like-form');
frm.submit(function () {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('success');
},
error: function(data) {
console.log('failed');
}
});
return false;
});
Would love to hear from people why this works and not the previous..

try change your btn type button and add ID for event click :
since putting the submit button goes directly to view.py without going through AJAX
<form id="like-form" action="{% url 'video-like' %}" method="post">
{% csrf_token %}
<input name="like"
type="hidden"
value="{{ video.id }}" id="id_pk">
<button type="button" id="id_btn">
<span class="video-options ml-auto fas fa-heart fa-2x m-2"></span>
</button>
in your script
$("#id_btn").click(function() {
$.ajax({
url:window.location.origin + 'your url'
type: 'POST',
data: {'pk':$(#id_pk).val(), 'accion':'guardar'},
success: function (data) {
console.log('success');
},
error: function(data) {
console.log('failed');
}
});
});
and your view.py
def post(self, request):
if 'guardar' in request.POST['accion']:
print("")

Related

Django + Ajax: why does it redirect to a new URL and renders the response on browser?

Based on my understanding, ajax could be used to prevent the page from reloading/refreshing/redirecting after submitting a request to the server. However, my code will redirect to display the JSON response. I used e.preventDefault() and it didn't work. Is there anything that I am doing wrong?
My Django code looks like this:
views.py:
def projects(request):
if request.method == 'POST':
task_id = request.POST.get('task_id')
myUser = User.objects.get(pk=request.user.id)
myTask = Task.objects.get(pk = task_id)
myTask.claimed.add(myUser) #add the user to the task
return JsonResponse({'status': 'ok'})
projects = Project.objects.all()
tasks = Task.objects.all()
open_tasks = tasks.filter(status='Created')
proj_dict = {}
context = {
'projects' : projects,
'tasks' : tasks,
'open_tasks' : open_tasks,
}
return render(request, 'projects/projects.html', context)
My HTML:
<form action="{% url 'projects:' %}" method="POST" class='join-form' id='{{task.id}}'>
{% csrf_token %}
<input type="hidden" name="task_id" value={{task.id}}>
<button type="submit" class=" claim-font claim-button">
Join
</button>
</form>
Tha ajax call:
<script>
$(document).ready(function () {
$('#join-form').on('submit', function (e) {
e.preventDefault();
e.stopPropagation();
const url = $(this).attr('action');
console.log("here we are");
const task_id = $(this).attr('id');
$.ajax({
type: 'POST',
dataType: "json",
headers: { 'X-CSRFToken': csrftoken },
url: url,
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
task_id: task_id,
},
success: function (response) {
alert(data);
console.log("here we are");
},
error: function (response) {
console.log('error', response);
alert("shit")
}
})
return false;
});
});
</script>
Seems like ajax will make sure that my browser doesn't redirect/reload/refresh after the submit button is clicked, and only the server-side changes. However, my browser turns out to be displaying: {"status": "ok"}
Any insights are greatly appreciated!
I noticed that you have class attribute for your form. Change your JQuery selector from $('#join-form') to $('.join-form') for class attributes
<script>
$(document).ready(function () {
$('.join-form').submit(function(e) {
e.preventDefault();
// write your code here
});
});
</script>
You need to change button type from "submit" to "button"

make like button in django using ajax

How I can make like button in Django using ajax
my html, I need to click like button without reload the page, The ajax function didn't work
<form method="POST" action="{% url 'video:like' video.pk %}">
{% csrf_token %}
<input type="hidden" class="likin" name="next" value="{{ request.path }}">
<button class="remove-default-btn" type="submit">
<i class="fa fa-thumbs-up" aria-hidden="true"><span>{{ video.likes.all.count }}</span></i>
</button>
JavaScript
$('.likin').click(function(){
$.ajax({
type: "POST",
url: "{% url 'video:like' video.pk %}",
data: {'content_id': $(this).attr('name'),'operation':'like_submit','csrfmiddlewaretoken': '{{ csrf_token }}'},
dataType: "json",
success: function(response) {
selector = document.getElementsByName(response.next);
if(response.liked==true){
$(selector).css("color","blue");
}
else if(response.liked==false){
$(selector).css("color","black");
}
}
});
})
You have added an event on the buttons click but that will not stop the forms submission (your button has type="submit" and submits the form). Instead of adding an event on the button's click instead add an event on the forms submission and prevent it. Next submit it yourself using ajax.
First in your form tag add an id:
<form method="POST" action="{% url 'video:like' video.pk %}" id="my-like-form">
Next add an event to the form submission:
$("#my-like-form").submit(function(e){
e.preventDefault(); // Prevent form submission
let form = $(this);
let url = form.attr("action");
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
dataType: "json",
success: function(response) {
selector = document.getElementsByName(response.next);
if(response.liked==true){
$(selector).css("color","blue");
} else if(response.liked==false){
$(selector).css("color","black");
}
}
})
})

DJANGO: How to get form value in views.py without submitting it

In html,I have a form and I want to know the form value without submitting it or refreshing the page. Once user will click on it, I want to get the value of the form and then pass it to view.py. Its working while I'm using type='submit' but not working if I'm disabling the submit button by using type='button'. Please let me know how to get the value of the form without submitting it.
URL:
url(r'^segmentation',include('segmentation.urls'))
VIEWS:
def index(request):
.......
.....
if request.method == 'POST': # If the form has been submitted...
html_node_number2=request.POST.get('url')
..........
......
return render(request, 'tree_home.html',context)
TREE_HOME.HTML:
.....
...
FORM1:
<form method="post" enctype="multipart/form-data" > {% csrf_token %}
{% for node in tuples %}
<button class="open-button" onclick="openForm()" name="html_node_number" value=
{{node.list1|safe}} type="button" id="test"> </button>
<script type="text/javascript">
$(document).ready(function() {
var url = 12; 'Used 12 instead of html_node_number to cross check but even 12 is not also passed to views.'
$("#test").click(function() {
$.ajax({
url: "/segmentation",
type: "POST",
<!-- dataType: "json", -->
data: {
url: url,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
alert("Successfully sent the URL to Django");
},
error : function(xhr,errmsg,err) {
alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
}
});
});
});
</script>
</form>
ERROR: Its generating html_node_number = NONE value

Django: Update Page Information Without Redirecting

I have this code:
html
<form method="post" id="idForm" name="frm1" action = "/myproject/save/"
enctype="multipart/form-data">
{% csrf_token %}
....
<input type="submit" name="save" id="save" value="Save">
</form>
<span class="status">Value: {{ request.mylist}} </span>
js code
$(document).on('submit', '#idForm',function(e){
$.ajax({
type: 'POST',
url: '{% url "myproject:save_form" %}',
data: {},
success:function(json){
$('.status').contents()[0].textContent = data.mylist
},
error : function(xhr,errmsg,err) {
alert("ajax error")
}
});
});
views
if request.method == 'POST' and 'save' in request.POST:
print("runs save form")
mylist= [5]
return JsonResponse({'mylist':mylist})
Question:
When I click on Save button, It is redirected to a page with
{"mylist": [5]}
How can I make it update only the status part, Value?
Use simple a button
<button type="button" onclick="sendData()">Save/button>
instead of this
<input type="submit" name="save" id="save" value="Save">
Make this a function
function sendData(){
$.ajax({
type: 'POST',
url: '{% url "myproject:save_form" %}',
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
formdata: JSON.stringify($("#idForm").serialize())
},
success:function(json){
let result = json.mylist[0];
$("#status").html(result);
},
error : function(xhr,errmsg,err) {
alert("ajax error")
}
});
}
You should also pass csrfmiddlewaretokentoken in data of ajax to csrf middle trust your request.
You can do the update in ajax success callback.
Update
At server side you can get the serialized data like this
if request.method == 'POST' and 'save' in request.POST:
print("runs save form")
data=json.loads(request.POST.get('formdata'))
mylist= [5]
return JsonResponse({'mylist':mylist})

jQuery and Multiple Forms, only the first one works

I have a page with multiple elements and some jQuery code to send when one of the forms are clicked.
form:
<form method="post" action="">
{% csrf_token %}
<input id="vote" name="vote" type="hidden" value="up">
<input id="post_id" name="post_id" type="hidden" value="{{submission.id}}"/>
<input type="submit" class="arrowup" value=""/>
</form>
jQuery javascript:
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/button_form/",
dataType: "json",
data : {
post_id : encodeURIComponent(document.getElementById('post_id').value),
vote : encodeURIComponent(document.getElementById('vote').value),
csrfmiddlewaretoken: '{{ csrf_token }}'
},
success : function(json) {
$('#result').html( 'post id: ' + json.post_id + ' voted: ' + json.up_or_down);
},
error: function(xhr,errmsg,err) {
alert(xhr.status + ": " + xhr.responseText);
}
});
return false;
});
});
The first button works as expected and gets the server's json response, however all the other buttons don't work.
I'm led to think this might be because there are multiple vote and post_id form inputs, but can't figure out an alternative strategy, or if that's really the issue.
Any help is greatly appreciated.
Thanks
I think you can iterate through all your forms and submit each one separetely on their submit event:
$("#formID").submit(function(e) {
e.preventDefault();
var url = $(this).attr('action');
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
// All other ajax code for submitting form data
});
});

Categories