Delete single item using Ajax and jQuery - javascript

Please I need to delete item from my website using jQuery and ajax but I don't know how to get the particular id of what I want to delete or less is single see below example:
HTML CODE
<span id="file-1">Orange</span> <a id="delete-1">Delete</a>
<span id="file-2">Orange</span> <a id="delete-2">Delete</a>
<span id="file-3">Orange</span> <a id="delete-3">Delete</a>
<span id="file-4">Orange</span> <a id="delete-4">Delete</a>
<span id="file-5">Orange</span> <a id="delete-5">Delete</a>
<!--Next item will have id of 6 is looping...-->
AJAX JQUERY
<script>
$(document).ready(function(e){
$("#delete-").click(function(){
//Am confused here how to know which id need to be deleted?
var id = $('#file-').val();
$.ajax({
url:'/delete_reply.php',
data:'id='+id,
type: "POST",
beforeSend: function(){
$('#comment-'+id'').attr('class', 'deleting');
},
success: function(data){
$('#comment-'+id'').hide();
$(#comment-'+id'').css('display','none');
}
});
});
});
</script>
Please I don't know how to pass the id of the content I want to delete to the ajax can someone help me?

UPDATE:
It's good approach to assign value to HTML element using data
attributes. For that HTML and jQuery both would look something like
follow.
HTML:
<span id="file-3">Orange</span> <a data-fileid="3" class="cmnDeleteFile">Delete</a>
JQUERY
$(".cmnDeleteFile").click(function(e){
e.preventDefault();
var id=$(this).data('fileid');
// This is how you get id of the file from same element using data attribute.
});
Old answer:
You're following wrong method.
Give every link common CSS class and fire trigger event on click of a link like this.
HTML:
<span id="file-3">Orange</span> <a id="3" class="cmnDeleteFile">Delete</a>
JQUERY
$(".cmnDeleteFile").click(function(e){
e.preventDefault();
var id=$(this).attr('id');
// This is how you get id of the file from same element.
});

Replace your
var id = $('#file-').val();
with
var id=$(this).attr('id').split("-")[1];
Btw, I haven't tested rest of your code. Particularly, your #delete- selector that you have used for binding click event.

Related

How to Call Ajax With Same Div Multiple Times

I am calling ajax with below code in my index.php file.
<script type="text/javascript">
$(document).ready(function(){
$("#counting").click(function(){
$.ajax({
type: 'POST',
url: 'https://example.com/update.php',
data: {url: '<?=$url?>'},
success: function(data) {
// alert(data);
//$("p").text(data);
}
});
});
});
</script>
It's working perfectly, but the issue is
I have div called counting multiple times on the page.
example
<div id="counting">
example
</div>
<div id="counting">
example
</div>
Issue - Ajax call only works with first div, not below divs.
How to make it work with all divs with id counting
Id attributes are supposed to be unique. You're only ever going to get the first div called because once the DOM sees that, it's met it's requirement and doesn't search further. I suggest you give you divs unique ids and then use a class that is the same for all of them.
<div id="div1" class="counting_class">
example
</div>
<div id="div2" class="counting_class">
example
</div>
Then your jQuery would look something like this:
$(".counting_class").click(function(){
var id = $(this).attr('id');
//then call ajax based on the individual ID
}

How to reload jquery on onclick event?

I've got a table row where it retrieves data from MySQL and I have included a .onclick function where it opens up a text editor with data inside, but the text editor is only opening for the first row and not the rest in the table.
This is the jQuery code: The first opens the text editor and the second switches the textarea for the text editor which is ckeditor.
<script type="text/javascript">
$(document).ready(function()
{
$(".trClass").click(function()
{
var id = $(this).attr('id');
$('#d_'+id).css("display", "block");
$('#table_id').css("display", "none");
});
});
window.onload = function()
{
CKEDITOR.replace("editor1");
};
</script>
and this here is echo for the table, I am using a foreach.
echo '
<tr class="trClass" id="'.$counter.'">
<td class="marker">
<i class="fa fa-align-left"></i>
</td>
<td class="title">
'.$article_title.'
</td>
<td class="content">
'.$article_content.'
</td>
</tr>
<section id="d_'.$counter.'" style="display:none;">
<textarea id="editor1">
<div style="width:468px;">
'.$article_content_full.'
</div>
</textarea>
</section>
';
$counter++;
}
I cannot figure out how to make the CKEDITOR.replace("editor1"); load for every table, I tried using .click function within it but it does not work as it doesn't load. Here is the problem, if you click on the first row it opens the text editor if you click on the second it does not; http://www.goo.gl/dQrLPN
Typically the id attribute should be unique for each element. Applying properties across multiple elements is usually accomplished with a class. Knowing this, CKEditor is probably just grabbing the first instance of an object with the given id (probably using document.GetElementById behind the scenes).
(According to the documentation, CKEDITOR.replace(var) will either take a DOM element, ID, or name.)
Given that, you have a couple of options. One is to defer loading the CKEditor until you actually click on the table row. This would look something like this... (note how each textarea has a unique id)
<section id="d_' . $counter . '" style="display:none;">
<textarea id="editor_'.$counter.'">
<div style="width:468px;">
'.$article_content_full.'
</div>
</textarea>
$(document).ready(function()
{
$(".trClass").click(function()
{
var id = $(this).attr('id');
$('#d_'+id).css("display", "block");
$('#table_id').css("display", "none");
CKEDITOR.replace('editor_'+id);
});
});
The second option would be to loop through all of the textarea elements and call replace on each one of them on-load. I wouldn't really recommend this, unless there's some specific reason you want to load everything up-front.
EDIT: Although this should fix your issue, you should look in to the HTML issues the other answerers have put forward. <section> doesn't belong as a child of <table> :-)
Try targeting the table and filtering by the rows using the .on() method.
$(document).ready(function()
{
$('#table_id').on('click','.trClass',function() {
var id = $(this).attr('id');
$('#d_'+id).css('display', 'block');
$('#table_id').css('display', 'none');
});
});
Details on .on() are here: https://api.jquery.com/on/
And as noted in the comments above, there are some overall issues with your HTML that you should probably fix before proceeding further.

Dynamically load link in rel attribute.

I want to dynamically load content using jquery's .load() function. Im storing the links in the .rel attribute of the links. I've got it setup like this:
<script>
$(document).ready(function(){
$('.sidebar_link').click(function(){
var link = this.attr('rel');
event.preventDefault();
$('#content').empty();
$('#content').load(link '#content');
});
});
</script>
<div class="main_menu">
<a class="sidebar_link" href="#" rel="photos.htm">Photography</a>
<a class="sidebar_link" href="#" rel="furniture.htm">Furniture</a>
<a class="sidebar_link" href="#" rel="services.htm">Services</a>
</div>
</div>
Its not working - It doesn't seem to be grabbing the link out of the rel attribute and Im not sure why. Any ideas?
Try this:
var link = $(this).attr('rel');
.attr is not a native JavaScript function, it is from jQuery so you have to wrap this with jQuery
And this:
$('#content').load(link);
You can pass an id for loading fragments, however the url and the id need to be a string literal like so $('#content').load('photos.htm #content') The photos.htm page would need to have an element on the page with id content. If you just want to display the entire contents of the page, just use the url.
In your click handler this is a pure dom element; you need to call the jQuery function on it before accessing the rel attribue
$('#content').load($(this).attr("rel"));
$('#content').load(link '#content');
This is almost certainly throwing a syntax error -- check your JavaScript console. I think you just want .load(link);.

Using jQuery to update the st_url attribute of the sharethis chicklet button?

I am dynamically updating the attribute 'st_url' of all of the sharethis spans to the url of a video clicked with jQuery. In firebug you can see it is updating the st_url attribute of my spans, however I the sharethis button is still tied to the initial url. I read I may have to reinit the elements, but I am unsure of the best way to do this? Has anyone done this or have any idea of the best way to re-initialize the buttons with the updated url? Thanks!
Sharethis includes and init:
<script type="text/javascript">
var switchTo5x=true;
</script>
<script type="text/javascript" src="http://w.sharethis.com/button/buttons.js"></script>
<script type="text/javascript">
stLight.options({publisher:'xxxx'});
</script>
My markup:
<span st_url="http://sharethis.com" class='st_stumbleupon' ></span>
<span st_url="example" class='st_facebook' ></span>
<span st_url="example" class='st_twitter' ></span>
<span st_url="example" class='st_email' ></span>
My jQuery to update the attr="st_url" when a user clicks on a video:
//note: this is triggered by .bind('click')
var youtubeID = $(this).attr('id');
$('#container div > span').each(function(){
//update sharethis to current video
$(this).attr('st_url','http://www.youtube.com/watch?v=' + youtubeID);
});
Here is a code from my project. Hope, you could use it.
// define attributes for buttons
settings.share_buttons = [
['facebook','st_facebook_large','Facebook','Share on Facebook'],
['twitter','st_twitter_large','Tweet','Share on Twitter'],
['pinterest','st_pinterest_large','Pinterest','Share on Pinterest'],
['linkedin','st_linkedin_large','LinkedIn','Share on LinkedIn'],
['googleplus','st_googleplus_large','Google +','Share on Google +']
]; //[service,class,displayText,title]
// all code under could be placed into a function and bind on a click event
// (don't forget about variable with URL, 'our_link_to_share').
//if block with buttons already exists
if (document.getElementById('share_this_id')){
$('#share_this_id' > span').each(function(){
$(this).removeAttr('st_url').attr('st_url',our_link_to_share).empty();
stWidget.addEntry({
"service":$(this).prop('service'),
"element":this,
"url":$(direct_link).prop('value'),
"title":$(this).prop('title'),
"type":"large",
"text":$(this).prop('displayText'),
"image":"http://www.softicons.com/download/internet-icons/social-superheros-icons-by-iconshock/png/256/sharethis_hulk.png",
"summary":"My site"
});
});
}// if not, we'll create it
else{
$('body').append($('<div>').prop('id', share_this_id).prop('class', 'share_this'));
var share_this = document.getElementById('share_this_id');
for(i=0; i&ltsettings.share_buttons.length; i++){
$(share_this).append($('<span>').attr('st_url', our_link_to_share).prop('class', settings.share_buttons[i][1]).prop('displayText', settings.share_buttons[i][2]).prop('title', settings.share_buttons[i][3]).prop('service', settings.share_buttons[i][0]));
}
}
if (stButtons){stButtons.locateElements();},
Because there's no updateEntry call in ShareThis you need to use jQuery's .html() to recreate your elements inside your container, then repopulate each one using individual calls to stWidget.addEntry against the span's ID.
I use the following snippet to reinitialize ShareThis buttons after loading in a new page via ajax. Just make sure to add in your publisher key:
$.ajax({
url: 'http://w.sharethis.com/button/buttons.js',
dataType: 'script',
success: function(){
stLight.options({
publisher: 'xxx',
onhover: false
});
},
cache: true
});
I originally found the snippet, at the location I link to below below, after searching for a long time for a good solution. Reposting here because it was buried in a mass of other overly complicated code: http://forums.sharethis.com/topic.php?id=3937#post-84933
Eventually I also ended up rewriting the whole block. I did it like this
<div id="share-buttons">
<button>custom stuff</button>
</div>
<div id="share-template" style="display:none">
<span class='st_facebook_large' displayText='Facebook'></span>
<span class='st_twitter_large' displayText='Twitter' st_via="Myself"></span>
<span class='st_linkedin_large' displayText='LinkedIn'></span>
<span class='st_email_large' displayText='Email'></span>
</div>
everytime the url to share changed:
var url=newurl, title = newtitle;
$('#share-buttons > span.st_dynamic').remove();
$('#share-template > span').empty().unbind().removeAttr('st_processed').each(function(){
$(this).clone().prependTo('#share-buttons')
.attr('st_url',url)
.attr('st_title',title)
.addClass('st_dynamic');
});
if (window.stButtons) stButtons.locateElements();
all the empty().unbind.removeCrap() appeared necessary. also necessary to reset the st_title - it was cached somewhere.
YMMV, especially since the buttons.js is external and this undocumented stuff changes :-/

jQuery problem, jQuery takes over all links on page

<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
$("#results").load( "jquery-routing.php", { pageNo: $(this).text(), sortBy: $("#sortBy").val()} );
return false;
});
});
</script>
<div id="results"> </div>
1
2
that code works fine, only problem that after I run it all my a href links stop to work! The links become jquery ajax calls.. why?
You're $("a") selector matches all <a ...> tags, you need to change it to something more specific:
$("a#someid")
$("a.someclass")
$("div#somecontainer a")
To target specific links, use the id or class tag on your anchor tags.
E.g.
<a class="link1" href=""></a>
<a id="link2" href-""></a>
Do note that id tags are unique within a page and can only be used once.
Reference those links in jQuery using:
$('a.link1').click(function() {}
$('#link2').click(function() {}
or you can combine both:
$('a.link1, #link2').click(function() {}
What you need to do is assign an id or class tag to the link that will call the ajax request. E.g. <a class="ajax" href="">ajax</a> and referencing it with $('a.ajax').click(function () {}
Your setting the onclick event of all anchor tags on the page. Try only selecting the link that you want instead of the more general $("a")
Your selector $("a") indicates all the hiperlink in your page.
You may need to give a specific id to the hiperlink where you want your ajax call to work and then change the selector based on that.
ex:
<a id= "my-link" href="" >ddd</a>
$("a#my-link").click()

Categories