How to Select Clicked Link Class or ID After AJAX Callback - javascript

I have a Like button. When the button is clicked one record is inserted into the DB via Ajax. If the insert is successful I change the name of the button to Unlike.
In the page I have 10+ like button and I want to select the clicked button.
I'm trying Using $(this) but that's not working for this specific code.
Here is the code.
$('.content').on('click', '.like_music', function(){
var music_id = $(this).parents('.music-item').attr('id');
$.ajax({
type:'POST',
url:'add_like_music.php',
data:{'music_id':music_id},
success:function(data){
alert(data);
if (data == "YES"){
$(this).html('unlike')
}
}
})
What am I doing wrong?

Use context option of ajax method:
$.ajax({
context: this,
...
});

$(this) is accessible inside the function itself, but not in the callback. You could store it in a variable outside the ajax call:
$('.content').on('click','.like_music',function(){
var $this = $(this);
var music_id = $this.parents('.music-item').attr('id');
$.ajax({
type:'POST',
url:'add_like_music.php',
data:{'music_id':music_id},
success:function(data){
alert(data);
if(data=="YES"){
$this.html('unlike');
}
}
});

try this code:
$('.content').on('click','.like_music',function(){
var music_id = $(this).closest('.music-item').attr('id');
^-----i change this
$.ajax({
type:'POST',
url:'add_like_music.php',
data:{'music_id':music_id},
success:function(data){
alert(data);
if(data=="YES"){
$this.html('unlike');
}
}
});

Related

Set interval to ajax form

So I'm trying to send the form info to php with ajax form every second, but for some reason it doesn't want to.
Here is my latest attempt, I tried every other similar combination(like put everything in the function or just put everything into the setInterval).
$(document).ready(function() {
var ajaxCall=function() {
$("#myForm").ajaxForm(function(e) {
$.ajax({
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data) {
document.getElementById("result").innerHTML=data;
}
});
});
}
setInterval(ajaxCall,1000);
});
EDIT
Solved with M.M answer, thank you for the help!
Simply change ajaxForm to ajaxSubmit
See this (question) and this (documentation) for more information on AjaxForm vs AjaxSubmit
Essentially AjaxForm submits when the user clicks the button and AjaxSubmit does it immediately so your code should be:
$(document).ready(function()
{
var ajaxCall=function()
{
$("#myForm").ajaxSubmit(function(e)
{
$.ajax(
{
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data)
{
document.getElementById("result").innerHTML=data;
}
});
});
}
setInterval(ajaxCall,1000);
});
Update after comment explanation
$(document).ready(function(){
//live feed
var ajaxCall=function(){
$("#myForm").ajaxSubmit(function(e){
ajax_submit();
});
}
setInterval(ajaxCall,1000);
//real submit
$("#myForm").ajaxForm(function(e){
ajax_submit();
});
function ajax_submit(){//ajax_code
$.ajax({
type:'post',
url:'php1.php',
data:$("#myForm").serialize(),
success:function(data) {
document.getElementById("result").innerHTML=data;
}
});
}
});
If you wish to differentiate the feed from the submit you can pass a parameter to the ajax_submit function
Getting rid of the ajaxForm() call seems to accomplish what you are trying to do:
$(document).ready(function() {
var ajaxCall = function() {
$.ajax({
type: 'post',
url: 'php1.php',
data: $("#myForm").serialize(),
success: function(data) {
document.getElementById("result").innerHTML = data;
}
});
}
setInterval(ajaxCall, 1000);
});

Ajax request with on method of jquery

I have a doubt, I use Jquery to load dynamic wall posts of people who follow me. Now since Jquery dosent work on dynamic content in the tradition click method I use on method for the response.If i dont trigger a Jquery method but do other things it works. I want to know how to launch Ajax method.
My Code:
$('body').on('click','.likebutton', $.ajax({
method:"POST",
url:"../assets/backend/likepost/index.php",
data:"postid="+$('.likebutton').attr('id'),
success:function(response) {
$(this).find(".liketext").html("<p class='liketext'><span class='glyphicon glyphicon-ok'></span> You like this</p>");
}
Any improvment to the code would be greatly appreciated. Thnx
Use following format:
$('body').on('click','.likebutton', function(){
var that = this;
/*
place code of other processing
*/
$.ajax({
method:"POST",
url:"../assets/backend/likepost/index.php",
data:"postid="+$(that).attr('id'),
success:function(response) {
$(that).find(".liketext").html("<p class='liketext'><span class='glyphicon glyphicon-ok'></span> You like this</p>");
}
});
}
You need to wrap ajax function call in an anonymous functions.
Use
$('body').on('click', '.likebutton', function() {
//Store the reference in a variable
var _this = $(this);
$.ajax({
method: "POST",
url: "../assets/backend/likepost/index.php",
data: "postid=" + this.id, //fetch id using this
success: function(response) {
//Use the refrence to set html
_this.find(".liketext").html("<p class='liketext'><span class='glyphicon glyphicon-ok'></span> You like this</p>");
}
});
});

Jquery AJAX calls in a loop

In my app, a displays available timeslots (for appointment). I want to add a class 'taken' to the slots () which are already taken. For this I wrote the following code.
$("td").each(function(){
var send = $(this).text();
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get',
success: function(result){
console.log(result);
if (result.status === "taken") {
$(this).addClass('taken');
};
}
});
});
It's supposed to perform an ajax call, and if the result for a slot is 'taken', add the class 'taken' to corresponding . It does the ajax call part, but adds the class to all td elements in the table, not just the taken ones.
the check-availability.php, returns 'taken' when called it in browser but nothing happens. Also, when the condition is changed into result.status === "notTaken", all the s are added the class 'taken'
How do I fix this?
$("td").each(function(){
var that = this;
var send = $(this).text();
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get',
success: function(result){
console.log(result);
if (result.status === "taken") {
$(that).addClass('taken');
};
}
});
});
see this for more reference:
$(this) inside of AJAX success not working
Ajax jquery success scope
instead of success, try using .done()
example
`
$.ajax({
url:'ajax/check-availability.php',
context: this,
data:{"slot":send},
dataType:'json',
type:'get'
}).done(function(result) {
console.log(result);
if (result.status === "taken") {
$(this).addClass('taken');
};
});
`

Getting a success info after submitting form via $.ajax in jquery

I have a few forms on my single page and I'm submitting them by this method:
$(function() {
$(".button").click(function() {
var upform = $(this).closest('.upform');
var txt = $(this).prev(".tekst").val();
var dataString = 'tekst='+ txtr;
$.ajax({
type: "POST",
url: "http://url-to-submit.com/upload/baza",
data: dataString,
success: function() {
upform.html("<div class='message'></div>");
$('.message').html("<h2>FORM SUBMITTED</h2>")
.append("<p>THANKS!!</p>")
.hide()
.fadeIn(1500, function() {
$('.message').append("<img src='http://my-images.com/i/check.png' />");
});
}
});
return false;
});
});
As you can see, after submit a form, message div appears instead of submitted form.
It works perfectly, when I submit only one form - then it changes to my message div, but when I submit second, and next and next - every time ALL of my already submitted form's messages refreshing.
It looks bad. I want to operate only on actually submitting form. How to fix it?
Well you're setting the message of every .message div by using $('.message').html(). Try this:
upform.find('.message').html(...)
Hard to tell without seeing how your HTML looks but i'm guessing it's this bit,
$('.message')
Should be something like,
$('.message', upForm).
First you have to find out the message div (upform.find('.message')) and than add any html to it. i think your code should be
$(function() {
$(".button").click(function() {
var upform = $(this).closest('.upform');
var txt = $(this).prev(".tekst").val();
var dataString = 'tekst='+ txtr;
$.ajax({
type: "POST",
url: "http://url-to-submit.com/upload/baza",
data: dataString,
success: function() {
upform.html("<div class='message'></div>");
upform.find('.message').html("<h2>FORM SUBMITTED</h2>")
.append("<p>THANKS!!</p>")
.hide()
.fadeIn(1500, function() {
upform.find('.message').append("<img src='http://my-images.com/i/check.png' />");
});
}
});
return false;
});
});
Another way without editing more in your current code just add few lines.
var msgbox = $("<div class='message'></div>");
upform.html(msgbox);
msgbox.html("<h2>FORM SUBMITTED</h2>")
.append("<p>THANKS!!</p>")
.hide()
.fadeIn(1500, function() {
$(this).append("<img src='http://my-images.com/i/check.png' />");
});

the id of the element won't change in jquery?

i.e.
$("#savenew").live('click', function(e) {
var user=<?php echo $user?>;
$.ajax({
type: "POST",
url: "actions/sub.php",
data:{user: user} ,
success: function(){
$('#savenew').html('<span>Unsubscribe</span>');
$(this).attr('id', 'clean'); // this my problem my problem
}
});
});
the id after the ajax request, is not changing from savenew to clean, but the html is perfectly fine, so i know the ajax request is working. what do u thiunk the problem is?
You just need to save the context (via the context option for $.ajax()) so this still refers to #savenew, like this:
$("#savenew").live('click', function(e) {
var user=<?php echo $user?>;
$.ajax({
context: this, //add this!
type: "POST",
url: "actions/sub.php",
data:{user: user} ,
success: function(){
$(this).attr('id', 'clean').html('<span>Unsubscribe</span>');
}
});
});
Also note that this allows you to chain and clean things up a bit.
$(this) inside success: function(){ does not refer to $('#savenew').
As you do in the line above, you need to reference it by id:
$('#savenew').attr('id', 'clean');

Categories