Jquery update div content with multiple same class - javascript

I'm builing a simple "like" service on my website. I'd like users to be able to click on link to like something, get the total likes (returned from php script)
I have problem getting the data from script to update div. This is what I have:
<div id="112" class="like">Like it</div>
<div id="113" class="like">Like it</div>
<div id="114" class="like">Like it</div>
<script>
$(".like" ).click(function() {
var idl = $(this).attr("id");
$.ajax({type:"POST", data: likeid=idl, url:"ajax/publike.php",
success: function(data){
$(this).html(data);
},
error: function(){
alert ("Error");
}
});
return false;
});
</script>
I just would like to update the div with content I get from (data) but no update. If I change to $(".like").html(data); it works, but I have many class like, I only when to have the clicked div to update.
Thanks

Do this:
<script>
$(".like" ).click(function()
{
var idl = $(this).attr("id");
var link = $(this);
$.ajax({type:"POST", data: likeid=idl, url:"ajax/publike.php",
success: function(data)
{
link.html(data);
},
error: function()
{
alert ("Error");
}});
return false;
});
</script>

try this
<script>
$(".like" ).click(function() {
var idl = $(this).attr("id");
$.ajax({type:"POST", data: likeid=idl, url:"ajax/publike.php",
success: function(data){
$('#'+idl).html(data);
},
error: function(){
alert ("Error");
}
});
return false;
});
</script>

By the time the AJAX callback runs, this is no longer in scope as the element which triggered the event. You need to hold a reference to it:
$(".like" ).click(function() {
var likedElement = $(this);
var idl = $(this).attr("id");
$.ajax({type:"POST", data: likeid=idl, url:"ajax/publike.php",
success: function(data){
likedElement.html(data);
},
error: function(){
alert ("Error");
}
});
return false;
});

Set the context to the element when you make the ajax call. This is safer than just relying on a scope variable. If a second div is clicked before the first ajax call is returned, only the last divs html would get updated. This method will update both divs correctly.
<script>
$(".like" ).click(function() {
var div$ = $(this);
$.ajax({type:"POST", data: likeid=div$.attr("id"), url:"ajax/publike.php", context: div$,
success: function(data){
this.html(data);
},
error: function(){
alert ("Error");
}
});
return false;
});
</script>

Related

Link click event by class in javascript doesnt work

I have a table with some <td>s and I have a link to delete each row with the class of '.DeleteMe'.
I have an AJAX post call in jQuery, but when I click on a link, it does nothing (click event doesn't work).
$(document).ready(function() {
$(".DeleteMe").click(function() {
var button = $(this);
var DeleteId = $(this).data("deleteid");
debugger;
$.ajax({
url: "/Merchant/DeleteProduct/" + DeleteId,
type: "Post"
}).done(function() {
$(button).parents("tr").remove();
}).error(function() {
alert("Something Went Wrong.");
})
})
});
And here is the link on the each row:
<a class="btns delete-icon DeleteMe" data-deleteid="#item.id">Delete</a>
How can I get these links to work?
I guess, that your rows are created dynamically after your event has been attached. In this case I would recommend to use event-delegation instead:
$(document).ready(function() {
$(document).on('click', '.DeleteMe', function() {
var button = $(this);
var DeleteId = $(this).data("deleteid");
debugger;
$.ajax({
url: "/Merchant/DeleteProduct/" + DeleteId,
type: "Post"
}).done(function() {
$(button).parents("tr").remove();
}).error(function() {
alert("Something Went Wrong.");
})
})
});

nesting ajax post in json get

function test() {
$.getJSON("/Home/GetAp", function (result) {
$.each(result, function () {
if (this.is_disabled == "False") {
var a = $("#MainDiv")
.append('<div id="imagewrap"><img id="infobutton" src="/Content/information%20icon.png" /></div>')
.val(this.id);
} else if (this.is_disabled == "True") {
var a = $("#MainDiv")
.append('<div id="imagewrap"><img id="infobutton2" src="/Content/information%20icon.png" /></div>')
.val(this.id);
} else {
return null;
}
})
})
}
How would I nest and ajax function be able to POST the a.val() so that when a user clicks on any $("#infobutton") they will be able to use the val of that button which would be an id specific to that button
$("#infobutton").click(function () {
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "/Home/setID",
data: JSON.stringify({ id: this.id }),
success: function (result) {
}
});
});
Do not make your logic depend on duplicate ids of DOM elements, use class instead.
Use event delegation to register event handlers for elements that exist at the time of event registration and for elements that will be created later.
.append('<div id="imagewrap"><img class="infobutton" src="/Content/information%20icon.png" /></div>')
$(document).on("click",".infobutton",function () {
$.ajax({
...
});
});
No need to nest ajax call. Just ensure click events bind to new elements appended and get the id in click event handler. Similar example (without ajax call)
$(document).ready(function(){
$(document).on('click', '.info', function(e) { alert("clicked div # " + $(e.target).text()); });
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 1.</div>"); }, 1000);
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 2.</div>"); }, 2000);
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 3.</div>"); }, 3000);
});
<div id="d1">
</div>
Let me know if you need more details or example with ajax call.
For id you can use
$(document).on('click', '.info', function(e) { alert("clicked div # " + e.target.id); });

Run JS function on .load() content

I have a function called timepicker which is usually called by using
$(document).ready(function() {
$('#timepicker').timepicker();
});
But I have been unable to make it work on content that is displayed using jQuery .load().
I have tried several methods including using the below but nothing happens?
$(document).ready(function() {
var $parent = $('#small_container');
var time = $parent.find('#timepicker');
time.timepicker();
});
The #small_container is the ID of the DIV that the content is loaded into and the #timepicker is the id of the input that should call the function when it is clicked on.
Have I added it to the correct place in the callback?
$('.edit_job').on("click", function(){
var week_start = $('input[name=week_start]').val();
var job_id_del= $('input[name=job_id]').val();
var user_id = $('input[name=user_id]').val();
$('#small_container').load('ajax/edit_weekly_job_load.php?job_id='+job_id_del+'&week_start='+week_start+"&user="+user_id);
$('#timepicker').timepicker();
$('#small_container').on("click", '#edit_job_submit', function(){
jQuery.ajax({
type: "POST",
url: "ajax/edit_weekly_job_ajax.php",
dataType: "json",
data: $('#edit_job_form').serialize(),
success: function(response){
if(response.success === 'success'){
window.opener.$("#diary").load("ajax/diary_weekly_load.php?week_start="+week_start+"&user="+user_id);
window.close();
}
},
});//end ajax
});//save_job_edit_submit
});//end edit job
The content is loaded asynchronously to the element #small_container. The timepicker function is gets called before the content is actually loaded. Try to call the function in the callback of load() method:
$('#small_container').load('ajax/edit_weekly_job_load.php?job_id='+job_id_del+'&week_start='+week_start+"&user="+user_id ,function(){
$('#timepicker').timepicker();
} );
Also validate that element #timepicker is actually appended to the element #small_container.

Javascript onclick change button text for a few seconds

Trying to change the text on a button to processing for a few seconds when it is click
<div id="send"></div>
<button id="button">Send</button>
<script>
$(document).on("click", "#button", function() {
var Path = $('#send').html();
var success = function() { alert("Successful"); };
var error = function(message) { alert("Oopsie! " + message); };
</script>
You're close, you just need to do this $('#button').html("Processing");
Then in the success and error functions, you'll probably want to modify the button text to something else so that it no longer displays "Processing".
This is what you are probably looking for:
$(document).on("click", "#button", function() {
var defaultBtnValue = $('#send').html();
$('#send').html("Processing...");
$.ajax({
url: your_url,
type: "GET",
success: function() {
alert("Successful");
},
error: function(message) {
alert("Oopsie! " + message);
},
complete: function() {
$('#send').html(defaultBtnValue);
}
});
});
I'm assuming you wan't this "Processing" to show while something is.. well, processing, like doing an ajax call (this may be a setTimeout function as well). Good practice is to first save the default value of the button and make sure to reset it once an action is complete (succes or not) in case something goes wrong.

Default select issue for JQuery UI 'selectable'

Below is my JS. When the page loads, I want it to automatically run the function as if its being clicked on. The default selection makes it started selected, but doesn't initiate the function. Any idea on how to make that work?
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
function updatefilters(ev, ui){
// get the selected filters
var template, html;
var pagego;
if(! pagego){
var page = 0;
}
var $selected = $('#selectable').children('.ui-selected');
// create a string that has each filter separated by a pipe ("|")
var filters = $selected.map(function(){return this.id;}).get().join("\|");
$.ajax({
type: "POST",
url: 'updatefilters',
dataType: 'json',
data: { filters: filters, page: page },
success: function(data){
html = "Do Something";
$('#board').html(html);
}
});
}
$('#lets').addClass('ui-selected')
});
Thanks!
Just call the function after declaring it:
$(function() {
$( "#selectable" ).selectable({
selected: updatefilters
});
function updatefilters(ev, ui){
...
}
$('#lets').addClass('ui-selected');
// none of your params are consumed in the function anyways, so you don't need to pass anything
updatefilters();
});
Try to run function in the body tag
<body onload="name_of_function()">

Categories