Hiding html element clicked after ajax success - javascript

I'm new to Web Development and making a mock twitter application. I want the tweet box to be removed after I click on the delete button (only if it is actually deleted in the backend)
I'm using django templating to loop through each tweet:
{% for tweet in data%}
<div class="container border border-primary rounded">
<p> tweet: {{tweet.content}}</p>
<div class="row">
{{tweet.id}}
<p class = "likes" style="margin: 0px 10px;"> likes: {{tweet.likes}} </p>
<button class="btn btn-dark like" style="margin: 0px 10px;">like</button>
<p class = "retweets" style="margin: 0px 10px;" > retweets: {{tweet.retweets}}</p>
<button class = "btn btn-dark retweet" style="margin: 0px 10px;">retweet</button>
<button class="btn btn-dark float-right delete_tweet" onclick="delete_tweet('{{tweet.id}}')">delete</button>
</div>
</div>
{% endfor %}
Here's the delete_tweet function:
function delete_tweet(id){
$(document).ready(function(){
$.ajax({
url: "{% url 'deleteTweet'%}",
data: {'id':id},
dataType: 'json',
success: function(data){
console.log(data);
$(this).parent().parent().remove();
}
});
});
}
This deletes the tweet in the backend fine, but the remove method doesn't work -
I'm pretty sure that I'm this is not referring to the right scope, what should I be doing instead?

Use .closest(".your-element-name").remove();
Your Button
function delete_tweet(id, that){
$(document).ready(function(){
$.ajax({
url: "{% url 'deleteTweet'%}",
data: {'id':id},
dataType: 'json',
success: function(data){
console.log(data);
$(that).closest(".rounded").remove();
}
});
});
}

Related

jquery how remove popover parents on click confirm button?

I am trying to send ajax request and remove the parent of popover after success
the request is success
but I can't access the parent of popover to remove it that is the bottom of problem
// delete work form portfolio
$(document).on("click", "#delete-work", function(){
var id_val= $(this).attr("data-id");
$.ajax({
url: "ajax/portfoliojx.php",
type: "POST",
data: {
name : "delete_work",
id : id_val,
},
dataType: "JSON"
}).done(function(data){
// check if responed email error
$(this).parents(".work").remove();
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="work">
<div class="col-md-3">
<div class="thumbnail">
<a href="">
<img src="uploads/portfolio/251442-7.jpg" title="hello" alt="hello">
</a>
<div class="caption">
<h4 class="tite">hello</h4>
</div>
<hr>
edit <i class="fa fa-edit"></i>
<a tabindex="0" class="btn btn-danger pull-left" role="button" data-toggle="popover" data-trigger="focus" data-placement="top" title="" data-content="<button class='btn btn-defualt'>no</button><span class='pull-left'><button id= 'delete-work' data-id= '23' class='btn btn-danger'>yah</button></span>" data-original-title="are you sure from this ?"> delete <i class="fa fa-trash"></i></a>
</div>
</div>
</div>
Inside Ajax callback the scope should be Ajax so this won't be works. the below codes works for your case
$(document).on("click", "#delete-work", function(){
var _self = this;
var id_val= $(this).attr("data-id");
$.ajax({
url: "ajax/portfoliojx.php",
type: "POST",
data: {
name : "delete_work",
id : id_val,
},
dataType: "JSON"
}).done(function(data){
// check if responed email error
$(_self).parents(".work").remove();
});
})

Ajax post in Laravel blade form not submitting

I'm trying to add some additional data to a form in my laravel blade using js and ajax post, but I can't get the form to submit. I've stripped everything else out to try to find what's wrong, but I'm mystified. Can anyone help?
My blade looks like this;
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-12 col-md-6 mt-5 mb-2">
<div class="card">
<div class="card-body">
<form id="payment-form">
<button id="card-button" class="btn btn-lg btn-block btn-success">
<span id="button-text"><i class="fas fa-credit-card mr-1"></i>{{ __('Add Payment Method') }}</span>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('javascript')
<script>
const cardButton = document.getElementById('card-button');
var form = document.getElementById('payment-form');
cardButton.addEventListener('click', function(event) {
// event.preventDefault();
console.log('On click check');
var payment = '1234';
$.ajax({
type: "POST",
url: "/payment-post",
data: {
payment: payment,
'_token': $('meta[name="csrf-token"]').attr('content'),
},
});
});
</script>
#endsection
You have to use like this
var payment = '1234';
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: "POST",
url: "{{url('')}}/payment-post",
dataType: "text",
data: {
payment: payment,
_token: CSRF_TOKEN
},
success: function (response) {
//Do something
}
});
In the end I tracked this down to 'defer' being present in the script tag in the header, which was stopping all the event listeners from working. Once I changed it to this
<script src="{{ asset('js/app.js') }}"></script>
everything working fine.

Twitter share button not working correctly

Currently working on freeCodeCamp's random code generator project. I'm getting strange behavior with my "Tweet" button. If the class is "twitter-share-button", the button will display properly, but won't populate the quote in the pop-up box, but if I change the class to "button", the button has no styling but the pop-up Tweet box populates correctly with the quote and author.
Please see code below:
HTML:
<div id="quoteBox" class="col-md-6 col-md-offset-3 text-center">
<h2>“What a curious power words have.”</h2>
<p>- Tadeusz Borowski</p>
<div class="panel panel-default">
<div class="panel-body">
<p id="quote"></p>
<h4 id="author"></h4>
</div>
<div id="twitter">
<a class="twitter-share-button button" id="tweet-quote" data-show-count="false">Tweet</a>
</div>​
</div>
<button id="getQuote" class="btn btn-primary btn-lg round btn-block">New Quote</button>
JS:
$(document).ready(function() {
// Loads quote on page load
getQuote();
$("#getQuote").click(getQuote);
});
function getQuote() {
$(document.body).css('background-color',
colors[Math.floor(Math.random() * colors.length)]);
$.ajax({
type: "POST",
url: "https://andruxnet-random-famous-quotes.p.mashape.com/?
cat=famous",
responseType: "json",
success: function(response) {
showQuote(response);
$('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?
text=' + encodeURIComponent('"' + response.quote + '" - ' +
response.author));
},
error: function() {
alert('Error retrieving quote');
},
beforeSend: setHeader
});
function setHeader(xhr) {
xhr.setRequestHeader("X-Mashape-Key",
"pmTSpn6I45mshpuPkHokTQ01lAo1p1ugEH1jsnoOS19Gk3KQvB");
xhr.setRequestHeader("Content-Type", "application/x-www-form-
urlencoded");
xhr.setRequestHeader("Accept", "application/json");
}
}
function showQuote(response) {
console.log(response);
$('#quote').text(response.quote);
$('#author').text(response.author);
}
I've spent hours on Twitter's dev page without any luck. Any help would be greatly appreciated, thanks.

Django - ajax call for loading page not working

I need really help..
I'm not good at front-end and I'm very confused with Ajax.
I'm trying to do an Ajax call for when I click on a button of my table so when I hit that button my ajax should show my animation .gif so the user should know that the page is loading.
my template:
<style>
.ajaxProgress{
display:none;
text-align: center;
}
</style>
<div id="output">
<div class="ajaxProgress">
<h3>Please wait..</h3>
<img src="{% static 'img/ajax.gif' %}" alt="loading"/>
</div>
</div>
{% for item in qs %}
<tr>
<tbody>
<td
a id="mqtt" class="btn btn-xs btn-info" title="mqtt" href="javascript: startAjax(){% url 'start_mqtt' item.id %}"><span class="fa fa-signal"></span> </a> </td>
</tbody>
</tr>
{% endfor %}
</table>
<script>
function startAjax() {
$('.ajaxProgress').show();
$.ajax({
type: "GET",
dataType:"json",
async: true,
data: { csrfmiddlewaretoken: '{{ csrf_token }}' },
success: function(json){
$('#output').html(json.message);
$('.ajaxProgress').hide();
GetRating(json.message);
}
})
}
</script>
Basically what I need is when I hit on the button should start my .gif but nothing happens....
var $loading = $('.ajaxProgress').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
I like to use this way

How to use javascript to trigger a modal one after another

I want to use the code below to accomplish the following flow:
validate user's input (form in a modal pop up)
if no error, trigger another modal to show something. The content of the result modal comes from an ajax call.
The problem is the result modal never shows.
Edited: The problem seems in relation to e.preventDefault() as I tested with another version which makes the ajax call in $("#frmSchPkg").submit(function(e).
It works with preventDefefalut and doesn't work if preventDefault() is missing.
Perhaps the question is how to add preventDefault() to this posted javascript.
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
alert(data); // able to see data being expected. so the ajax call is successful
$('#text-modal').modal('hide'); // tried to comment this out for testing, 1st modal vanishes anyway at this point
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
}
});
<div class="modal fade text-modal" id="text-modal" tabindex="-1" role="dialog" aria-labelledby="smallModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-sm2">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search</b></h2>
</div>
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSchPkg">
<div class="modal-body">
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" name="pkgnum12" id="pkgnum12" type="text" placeholder="enter tracking number" data-validation="number length" data-validation-length="12-12" />
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<button name="btnfind" id="btnfind" type="submit" class="clsfind btn btn-store btn-block">
<i class="fa fa-search"></i> Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="LookupResultModal" tabindex="-1" role="dialog" aria-labelledby="LookupResultModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog ">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search Result</b></h2>
</div>
<div class="ct_schpkgresult"></div>
</div>
</div>
</div>
The JS script should be like
Ajax method should be inside validation onSuccess: function($form) { }
First modal hide and 2nd modal show should be in side Ajax method success: function(data) { }
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
alert(dataString);
$.ajax({
type: "POST",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide'); //If all good hide first modal
$('#LookupResultModal').modal('show'); //show 2nd modal
$('#LookupResultModal').find('.ct_schpkgresult').html(data); //show response in 2nd modal
},
error: function(err) {
console.log(err);
}
});
}
});
I found the following solution:
$.validate({
form: '#frmSchPkg',
onSuccess: function(form) {
return $.sendFormDataViaAJAX(form);
}
});
$.sendFormDataViaAJAX = function(form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide');
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
return false;
};

Categories