How do I stop ajax call from refreshing my page? - javascript

<form id="review" method="post">
{% csrf_token %}
<button type="submit" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
<span class="icon text-white-50">
<i class="fas fa-poll-h"></i>
</span>
<span class="text">Fetch Reviews</span>
</button>
</form>
This is my html form on a Django rendered page
<script type="text/javascript">
$(document).on('submit','#review'.function(e){
e.preventDefault();
e.stopPropagation();
$.ajax({
type:'POST',
URL:'/reviews/',
data:{
asin:$('#sbtn').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
beforeSend:function() {
$('#loader').removeClass('hidden');
},
complete : function() {
$('#loader').addClass('');
}});
return false;
});
This is the ajax function on the page.
The problem is...the current page is the result of a form on a previous page so as soon as the form-submit event is invoked the page refreshes and data on the page is lost. I tried both
e.preventDefault()
and
e.stopPropagation()
but that doesn't help. I'd like to know if you have some approach or a workaround..Thank you!

To make this work change this part of code:
<button type="submit" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
Like that:
<button type="button" id="sbtn" class="btn btn-primary btn-icon-split btn-lg" value="{{ Asin }}" >
<button type="submit" id="submit_sbtn" class="d-none">
The submit button is not necessary.
Then change your script to send an ajax request to $('#sbtn') click event. And then submit your form.

$(document).on('submit','#review', function() {
$('#loader').removeClass('hidden');
$.ajax({
method: "POST",
type: "POST",
url: "/reviews/",
data: {
asin:$('#sbtn').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
}
}).done( function( msg ) {
$('#loader').addClass('');
console.log(msg)
}).fail( function(error) {
console.log(error)
})
return false;
})

Related

Django, Ajax and JS Toggle Like and Unlike Icon on Button Click

0
I followed a solution on how to get Django Like and Unlike button not to reload the page on click. The solution i found works but only with TEXT toggle (Like and Unlike) and i want an Icon Toggle (Like and Unlike Icon).
I am new to Django Backend and Ajax, i will be happy if someone can help on how to deal with this. Thanks in Advance.
$( document ).ready(function() {
$('.like-form').submit(function(e){
e.preventDefault()
const post_id = $(this).attr('id')
const likeText = $(`.like-btn${post_id}`).text()
const trim = $.trim(likeText)
const url = $(this).attr('action')
let res;
const likes = $(`.like-count${post_id}`).text()
const trimCount = parseInt(likes)
$.ajax({
type: 'POST',
url: url,
data: {
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
'post_id':post_id,
},
success: function(response) {
if(trim === 'Unlike') {
$(`.like-btn${post_id}`).text('Like')
res = trimCount - 1
} else {
$(`.like-btn${post_id}`).text('Unlike')
res = trimCount + 1
}
$(`.like-count${post_id}`).text(res)
},
error: function(response) {
console.log('error', response)
}
})
});
});
<!-- Like Button -->
<li class="list-inline-item">
<form action="{% url 'posts:like-post-view' %}" method="POST" class='like-form' id='{{obj.id}}'>
{% csrf_token %}
<input type="hidden" name="post_id" value={{obj.id}}>
<button type="submit" class="btn btn-link g-color-gray-dark-v5 g-color-red--hover text-red p-0 border-0 btn-outline-light like-btn{{obj.id}}">
{% if user not in obj.liked.all %}
Like
<i class="align-middle mr-1 icon-heart u-line-icon-pro g-font-size-25"></i>
{% else %}
Unlike
<i class="align-middle mr-1 icon-like u-line-icon-pro g-font-size-25"></i>
{% endif %}
</button>
<span class="g-color-gray-dark-v5 g-font-size-15 like-count{{obj.id}}"> {{obj.num_likes}}</span>
</form>
</li>
<!-- End Like Button -->
You can append icons as well inside your success function with text . Also , put like and unlike inside span so that it would be easy to change value .
Demo Code :
$('.like-form').submit(function(e) {
e.preventDefault()
const post_id = $(this).attr('id')
const likeText = $(".like-btn"+post_id).find("i").hasClass("fa-heart-o") ? "Unlike":"Like"//check for class and if true then set value as unlike or like..
const trim = $.trim(likeText)
const url = $(this).attr('action')
let res;
const likes = $(`.like-count${post_id}`).text()
const trimCount = parseInt(likes)
/* $.ajax({
type: 'POST',
url: url,
data: {
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val(),
'post_id': post_id,
},
success: function(response) {*/
if (trim === 'Unlike') {
//use .html to add htmls codes
$(`.like-btn${post_id}`).html('<i class="fa fa-heart" aria-hidden="true"></i>')
res = trimCount - 1
} else {
$(`.like-btn${post_id}`).html('<i class="fa fa-heart-o" aria-hidden="true"></i>')
res = trimCount + 1
}
$(`.like-count${post_id}`).text(res)
/* },
error: function(response) {
console.log('error', response)
}
})*/
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="{% url 'posts:like-post-view' %}" method="POST" class='like-form' id='1'>
<input type="hidden" name="post_id" value=1>
<button type="submit" class="btn btn-link g-color-gray-dark-v5 g-color-red--hover text-red p-0 border-0 btn-outline-light like-btn1">
<!--put texxt inside span-->
<i class="fa fa-heart" aria-hidden="true"></i>
</button>
<span class="g-color-gray-dark-v5 g-font-size-15 like-count1">12</span>
</form>
<form action="{% url 'posts:like-post-view' %}" method="POST" class='like-form' id='2'>
<input type="hidden" name="post_id" value=2>
<button type="submit" class="btn btn-link g-color-gray-dark-v5 g-color-red--hover text-red p-0 border-0 btn-outline-light like-btn2">
<i class="fa fa-heart-o" aria-hidden="true"></i>
</button>
<span class="g-color-gray-dark-v5 g-font-size-15 like-count2">5</span>
</form>

How do i get the id to be added and removed from the particular button clicked?

<script>
$(document).ready(function() {
$("button").on('click', function(argument) {
$("button").attr('id', 'addtocart');
var product_id = $("#product_id").val();
if (product_id!="") {
$.ajax({
type : "POST",
url : "manage-cart.php",
data : 'product_id='+product_id,
success : function (response) {
// action to be performed if successful
$('#addtocart').removeAttr('id');
}
})
}
})
});
</script>
<div class="buttons">
<button class="" type="submit" >
<i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<input type="hidden" id="product_id" value ="5">
<div class="buttons">
<button class="" type="submit" >
<i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<input type="hidden" id="product_id" value ="6">
<div class="buttons">
<button class="" type="submit" >
<i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<input type="hidden" id="product_id" value ="7">
<div class="buttons">
<button type="submit" >
<i class="fa fa-shopping-cart"></i>Add to Cart</button>
</div>
<input type="hidden" id="product_id" value ="8">
this is the script and HTML code I'm working with. When the button is clicked the id is added to all the buttons and that's not the idea I want the id to be added to just the clicked button and removed after execution of the ajax script.
you need to use $(this)
$(document).ready(function() {
$("button").on('click', function(argument) {
var _t = $(this);
_t.attr('id', 'addtocart');
var product_id = $("#product_id").val();
if (product_id!="") {
$.ajax({
type : "POST",
url : "manage-cart.php",
data : 'product_id='+product_id,
success : function (response) {
// action to be performed if successful
_t.removeAttr('id');
}
})
}
})
});
</script>

Form submission works with html but not javascript at the same time

I want to achieve that the user can search on the website and then filter his search results by clicking on a link (which triggers javascript) so he gets people instead of articles. In terms of database and PHP it works, but when I try to submit this code:
<form id="searchform" class="navbar-form" role="search" method="post" action="/search">
{{ csrf_field() }}
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="<?php if(isset($searchterm)) { echo $searchterm; } ?>">
<div class="input-group-btn">
<button class="btn btn-default" type="submit"><i class="glyphicon glyphicon-search"></i></button>
</div>
</div>
</form>
... with this code:
function submit() {
document.getElementById("searchform").submit();
}
this is what I use to communicate with my database initially, the url leads to a PHP function that returns the users. (works)
The following code only gets submitted with HTML button, but not with the link which will submit the form through javascript.
$("#searchform").submit(function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url : "/search/people",
data : form.serialize(),
dataType : "json",
success : function(data){
if(data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});
I get no results in the console when I press the link, BUT with the search bar button (html) I get something in the console.
So what I want to do is with the second link in this code:
<div class="list-group">
sounds
<a id="people" onclick="submit()" href="#" class="list-group-item">people</a>
requests
</div>
I will submit the javascript that part is not working.
Any suggestions on what I can try?
Here's a working example of your code:
https://jsfiddle.net/jonva/x99nxz0h/1/
It seems perfectly fine.
<form id="searchform" class="navbar-form" role="search" method="post" action="/echo/json">
abc
<div class="input-group">
<input type="text" class="form-control" style="width: 300px;" placeholder="Search" name="searchterm" id="srch-term" value="">
<div class="input-group-btn">
<button class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
$("#searchform").submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "/echo/json",
data: form.serialize(),
dataType: "json",
success: function(data) {
if (data.length > 0) {
console.log(data);
} else {
console.log('Nothing in the DB');
}
}
}, "json");
});

Submit form via Enter key and Submit button both

Hi I have form and following things are bothering me:
1. Form does not submit on pressing enter.
2. When i press enter in input field then Search Now button needs to be pressed
twice to search places.
Form is displayed as below:
<form method="POST" id="mylocform" action="">
<h3 class="animated slideInLeft delay-2">
<input type="text" placeholder="Start Typing Your Location" id="geocomplete"
style="color:black;width:100%;padding:5px;height:45px;border-radius:5px"
autocomplete="off" class="chkmeloc" onblur="checkmylocform()"/></h3>
<input type="submit" class="btn btn-default btn-lg animated fadeInUpBig delay-3"
style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>
</form>
Validation goes like below:
$(document).ready(function(){
$("form#mylocform").submit(function(event) {
event.preventDefault();
validate();
});
});
function checkmylocform(){
var checkOdlen = $(".chkmeloc").val().length;
if(checkOdlen==0){
$(".chkmeloc").css("border-color","#F05F68");
$(".chkmeloc").focus();
$(".chkmelocmess").html('<button type="submit" class="btn btn-default
btn-lg" style="background: #FFF;color:red">
<i class="fa fa-warning text-red"></i>
Select Your Location</button>');
return false;
}
else{
$(".chkmeloc").css("border-color","#0C9");
$(".chkmelocmess").html('<input type="submit" class="btn btn-default
btn-lg" style="color: black;background-color: #FFF;border-color: #FFF;"
value="Search Now!"/>');
return true;
}
}
function validate(){
$.each($('form :input'),function(){
$(this).blur().change();
});
if(!checkmylocform()){
return false;
}
else{
submitform();
}
}
Submit Form has code to submit form via ajax as below. Please help me to get out of this situation.
$("Your selector").keypress(function (e) {
var key = e.which;
if(key == 13) // the enter key code
{
$(input[type = submit]).click();
return false;
}
});
look at this site:
http://tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
the site says that enter key is automaticly a submit in al browser
Try This
File index.html :
<form class="form-inline" action="" method="POST">
<input type="password" name="token" placeholder="Enter Facebook access token..." class="subscribe-email">
<button type="submit" class="btn">Start!</button>
</form>
<div class="success-message"></div>
<div class="error-message"></div>
File script.js :
$('.get_token form').submit(function(e) {
e.preventDefault();
var postdata = $('.get_token form').serialize();
$.ajax({
type: 'POST',
url: 'assets/submit_token.php',
data: postdata,
dataType: 'json',
success: function(json) {
if(json.valid == 0) {
$('.success-message').hide();
$('.error-message').hide();
$('.error-message').html(json.message);
$('.error-message').fadeIn();
}
else {
$('.error-message').hide();
$('.success-message').hide();
$('.get_token form').hide();
$('.success-message').html(json.message);
$('.success-message').fadeIn();
}
}
});
});

x-editable resetting fields

i have the following html/php code (php tag ommited)
$user = array(
'name' => Null,
'address' => Null
);
<div id="user">
<a href="#" id="cust_name" data-type="text"
data-pk="'.$user['ag_id'].'" title="Enter customer name">'.$user['name'].'</a>
<a href="#" id="cust_addr" data-type="text"
data-pk="'.$user['ag_id'].'" title="Enter customer address">'.$user['address'].'</a>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="ResetButton">Reset</button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="SaveButton"
data-dismiss="modal">Save changes</button>
</div>
</div>
could you please complete my resetbutton script, the purpose is to assign null to cust_name and cust_addr after the click.. here's the script
<script>
$.fn.editable.defaults.mode = 'inline';
$(function(){
$('#user a').editable({
url: 'post.php'
});
});
$("#SaveButton").click(function() {
$.ajax({
url: 'db.php',
type: 'POST',
data: {}
});
});
$('#ResetButton').click(function() {
// $('#cust_name').editable('setValue', null); // did not worked
// didn't worked even i added class="myeditable" in my <a> tag
/*
$('.myeditable').editable('setValue', null)
.editable('option', 'pk', null)
.removeClass('editable-unsaved');
*/
});
</script>
This seemed to work.
http://jsfiddle.net/U33kT/
I'm not sure the difference, except that I chose all editables (JS line 6):
$('#user a').editable('setValue', null);
But, I tried with single items:
$('#cust_name').editable('setValue', null);
and it seemed to work as well.
Hope this helps.

Categories

Resources