Hide a button in jQuery after an AJAX call [duplicate] - javascript

This question already has answers here:
$(this) inside of AJAX success not working
(2 answers)
Closed 2 years ago.
enter code hereI have a list of items from a database displayed thanks to a for-loop in Django.
I have a "save button" next to each one to save them to a favorite database thanks to an AJAX call. Everything works like a charm.
But I want the "save button" to .hide() whenever the AJAX call is a "success". But if I do so, every "save button" from the page is hidden.
So I tried to use .parent() or .closest() to select only the <div> where my "save is button" with no luck.
My HTML:
{% for sub_product in products %}
<div class='sub_button'>
<form class="add_btn" method='post'>{% csrf_token %}
<button class='added btn' value= '{{product.id }} {{ sub_product.id }}' ><i class=' fas fa-save'></i></button>
</div>
{% endfor %}
My AJAX:
$(".added").on('click', function(event) {
event.preventDefault();
var product = $(this).val();
var url = '/finder/add/';
$.ajax({
url: url,
type: "POST",
data:{
'product': product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
$(this).parent('.sub_button').hide();
}
});
});

Your code failing because you are in different scope, $(this) will refer to the success function you are calling, not the element clicked, you should have a reference to the button once you execute the click event listener, the following should work for you:
$(".added").on('click', function(event) {
let addedBtn = $(this); // Here is a reference
event.preventDefault();
var product = $(this).val();
var url = '/finder/add/';
$.ajax({
url: url,
type: "POST",
data:{
'product': product,
'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
},
datatype:'json',
success: function(data) {
if (data['success'])
addedBtn.parent('.sub_button').hide();
}
});
});

Related

Looking to rename Django Ajax "like" button, but not working

Currently my button functions, but I've placed it inside of a django for loop. I'd like to move the js logic to a separate file, but first I need to give it a better name. Here is a snippet of my code:
{% for post in posts %}
.....
<script type="text/javascript">
function toggleLike{{post.id}}(){
$.ajax({
url: "{% url 'photo_blog-post_like_api' post.id %}",
success: function(data) {
$("#likeCount{{post.id}}").html(data.like_count + ' likes');
$('#imageElement{{post.id}}').html(data.img);
}
});
};
</script>
<a id=imageElement{{post.id}} onclick="toggleLike{{post.id}}()"><img src="/media/nav_buttons/liked.svg" height="17" width="17"></a>
....
<post info here>
....
{% endfor %}
When I remove the {{post.id}} from the function name, and onclick call, the button only functions for the post on the bottom of the page. All of the other buttons toggle the information for that one post. How can I give this function a general name, but still have it interact uniquely with each post?
You shouldn't be doing this as part of the name anyway. The post id is a parameter. The only collocated part is working out how to pass it to the Django URL tag
function toggleLike(post_id){
$.ajax({
url: "{% url 'photo_blog-post_like_api' "00000" %}".replace("00000", post_id)
success: function(data) {
$("#likeCount" + post_id).html(data.like_count + ' likes');
$('#imageElement' + post.id).html(data.img);
}
});
};
</script>
<a id=imageElement{{post.id}} onclick="toggleLike({{post.id}})"><img src="/media/nav_buttons/liked.svg" height="17" width="17">

Submit form and call Ajax on <a> click

I want to add something to database using Ajax. I have a link which submits the form and then Ajax call should work, but it's not. I use this same Ajax call on different page, but in that form I'm using simple button with type submit. But on this page, I want to submit with ...
This is the form
{!! Form::open(['id' => 'ajax-form', 'style' => 'float:right']) !!}
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idCampaign" id="idCampaign" value="{{$campaign->id}}">
<a class="fa fa-bookmark fa-2x" onclick="document.getElementById('ajax-form').submit();" aria-hidden="true" href="javascript:{}" style="color:#fd8809"></a>
{!! Form::close() !!}
This is the Ajax:
$("#ajax-form").submit(function(event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: form.serialize(),
success: function(data){
if(data.status == 'failedd'){
swal("Error!", "You have already added this campaign to favorites! If you want to remove it, go to your Favorites list page", "error")
}
else{
swal("Success!", "You added the campaign "+ data.idCampaign + " to favorites!", "success")
}
},
error: function(data){
swal("Error!", "error")
},
complete: function (data) {
}
});
});
When I click on this link, it redirects me to another page which throws: MethodNotAllowedHttpException.
Change your ajax url to this:
url: '/addFavorites',
and your route to this:
Route::post('/addFavorites', 'SearchController#addFavorites');
Just to make sure you point at the same url
EDIT:
make sure that you have one route with get and the same route with post. see bellow:
Route::get('/addFavorites', 'SearchController#loadFavorites'); <-to load the page
Route::post('/addFavorites', 'SearchController#submitFavorites'); <-to submit the data
Change this: $("#ajax-form").submit(function(event) {
To this: $('#yourid').click(function(){
Remove the onclick in the 'a' element and add the id='yourid' with the name you want.
MethodNotAllowedHttpException usually comes when you haven't defined route or you have defined route for get method and you are using the route for post method. please check your routes.php

Jquery Load specific div make button not work

get a problem with after success ajax and load the div.
Here's the code:
<script>
$('.delete').click(function(e){
e.preventDefault();
var id = $(this).attr('id');
if (confirm('Delete this user?') == true) {
$.ajax({
type: "POST",
data: {_method: "DELETE"},
url: 'manage-staff-roles/' + id, //resource
beforeSend: function(){
$('.loader-wrap').removeClass('hiding hide');
},
success: function() {
$('.loader-wrap').addClass('hiding hide');
$('#table').load(location.href + " #table");
Messenger().post({
message: 'Success.',
type: 'success',
showCloseButton: true
});
}
});
}
else
{
return;
}
});
</script>
Here is my html:
<div id="table">
#foreach($staffroles as $staffrole)
{{ $staffrole->id }}
{{ $staffrole->name }}
<a class="edit" id="staffroles/{{ $staffrole->id }}/edit" href="manage-staff-roles/{{ $staffrole->id }}/edit">
Edit </a>
|
<a class="delete btn" id="{{ $staffrole->id }}" >
Delete </a>
#endforeach
</div>
after the ajax success and do all the function perfectly (including reload the specific div). But the problem is my div that contain a delete button is become unusable but the edit button is working).
You need to add click handler using .on() for dynamically created buttons. Modify your delete button click handler as shown below
$(document).on('click','.delete',function(e){
e.preventDefault();
var id = $(this).attr('id');
if (confirm('Delete this user?') == true) {
$.ajax({
type: "POST",
data: {_method: "DELETE"},
url: 'manage-staff-roles/' + id, //resource
beforeSend: function(){
$('.loader-wrap').removeClass('hiding hide');
},
success: function() {
$('.loader-wrap').addClass('hiding hide');
$('#table').load(location.href + " #table");
Messenger().post({
message: 'Success.',
type: 'success',
showCloseButton: true
});
}
});
}
else
{
return;
}
});
The problem is that the .load method of jQuery, will add new html and this will override any event handlers that were added previously, you will need to re-add the event handlers for button (in case it is overriden by .load) so as to continue being re-usable.
Another alternative is to add the event handlers (for button) on parent element and delegate (via jQuery.on method with selector)
Hope this helps, comment for further info if needed

How to check if a link is clicked using AJAX/jQuery

I am trying to delete a link without a page refresh, and I would like to jQuery to capture and send http request to a specific URL that does the deleting. But, for this to work, I need to be able to use jQuery/Ajax to get the clicked link and send it as an http request.
this is the link:
<a href='http://example.com/delete.php?id=243'> <span class='delete'>delete this</span> </a>
Now, this is the jQuery and Ajax in twig template to get the clicked link and send httprequest to delete.php with the id, so that id can be deleted.
$(document).ready(function() {
$(".delete").click(function(){
$.ajax({
type: "GET",
url: "{{ path('http://example.com/delete.php?id=243'}}",
cache: "false",
dataType: "html",
success: function(result){
$(".success").append(result);
}
});
});
}
But the above function only makes the page navigate to the link when clicked.
You need to preventDefault.
$(".delete").click(function(e){
e.preventDefault()
$.ajax({
..
I don't know if I got you right here, but this may help you: http://api.jquery.com/event.preventDefault/
$( "a" ).click(function( event ) {
event.preventDefault();
//your code
}
Prevent default behaviour of link using jQuery's preventDefault().
Having:
<a class='delete' href='http://site.com/delete.php?id=243'> delete this </a>
Try:
$(".delete").click(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: "{{ path('http://site.com/delete.php?id=243'}}",
cache: "false",
dataType: "html",
success: function(result){
$(".success").append(result);
}
});
});

Allowing only one of three buttons to submit a web form

If i have something like:
<form method="post" id="customForm" action="">
//stuff
<div id="copiar">
<button class="button" href="#" id="btnAdd0">
<span class="icon icon3"> </span>
</button>
<button class="button" href="#" id="btnDel0">
<span class="icon icon58"> </span>
</button>
<button class="submeter">
<span class="label">Send</span>
</button>
</div>
</form>
and:
<script type="text/javascript">
$(document).ready(function() {
$("#customForm").submit(function() {
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
});
return false;
});
});
</script>
At the moment, the three buttons send the form. My idea is only permit the submit action in this button:
<button class="submeter">
<span class="label">Send</span>
</button>
I already tried $("#customForm > #copiar > button.submeter").submit(function() {
but the page is reloaded. So isn't working.
Any idea ?
You have to stop the other buttons from submitting first and then do your submit. Also when using an ID for your selector there really isn't any need to combine it with another ID like #customForm > #copiar "
Try this:
$(document).ready(function() {
$("#customForm").submit(function(e) {
e.preventDefault();
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
}
});
});
$("#customForm button").click(function(e) {
var me = $(this);
e.preventDefault();
if(me.hasClass("submeter")) $("#customForm").submit();
});
});
And as has already been pointed out, you don't need/want the href="#"
In order to prevent the default behavior of the form, you must use preventDefault() as follows:
$(document).ready(function() {
$("#customForm").submit(function(e) {
e.preventDefault();
var formdata = $("#customForm").serializeArray();
$.ajax({
url: "validation.php",
type: "post",
dataType: "json",
data: formdata,
success: function(data, data1) {
//stuff
});
});
$("#customForm button.submeter").click(function() {
$("#customForm").submit();
});
});
What is exactly the purpose of first two button element with the href attribute? I suspect you're using a button instead of a regular link only for a formatting/visual reason.
Anyway for your purpose, just add the attribute type="submit" to the last button and remove the submit handler you've defined for this button, it should work fine.
edit. you also need to call the preventDefault() method to stop page reload, as pointed out by phil klein

Categories