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");
}
}
})
})
Related
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
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("")
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})
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
});
});
I have this form, user login form in django
<form method="post" id="loginSubmit" action="{% url 'auth_login' %}">{% csrf_token %}
<table>
<tr>
<td>{% trans form.username.label_tag %}</td>
<td>{{ form.username }}</td>
<td><i class="fi-torso"></i></td>
</tr>
<tr>
<td>{% trans form.password.label_tag %}</td>
<td>{{ form.password }}</td>
<td><i class="fi-key"></i></td>
</tr>
<tr>
<td colspan="3"><input type="submit" id="Login" class="button expand" value="{% trans "Login" %}" /></td>
</tr>
</table>
</form>
I have to call two urls on click of submit button, as through action it send one url and another through ajax as bellow:
<script type="text/javascript">
$(document).ready(function() {
$("#Login").click(function() {
$.ajax({
type: "POST",
url: "{% url 'user_group' group_name %}",
datatype: "html",
data: $("#loginSubmit").serialize(),
success: function(data) {
}
});
});
});
</script>
What happens is, when i click submit button in login form it takes first action url i.e. auth_login and redirects to it and doesn't call ajax url.
As I know the reason that form submits at its action url this action happens at server side and ajax call happens at client side and server side redirection happens first then client side. but how to tackle such situation, as I want to call two urls on same submit button.
Please suggest.
<script type="text/javascript">
$(document).ready(function() {
$("#Login").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "{% url 'user_group' group_name %}",
datatype: "html",
data: $("#loginSubmit").serialize(),
success: function(data) {
}
});
$("#loginSubmit").submit();
});
});
</script>
if that doesn't work then put $("#loginSubmit").submit() on ajax's success function, but this time form will be submit after ajax response, you know.
EDIT: using complete callback function of JQuery.ajax instead of successis more accurate here.
Try this sunny
$(document).ready(function()
{
$("#Login").click(function() {
$.ajax({
// create an AJAX call...
data: $("#loginSubmit").serialize(), // get the form data
type: 'GET', // GET or POST
url: '{% url 'user_group' group_name %}', // the file to call
success: function (data) {
$("#state_table").html(data);
//alert('ajax call suceessfully');
},
error: function(data) {
$("#state_table").html("Something went wrong!");
}
});
});
});