0

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?

Aneeez
  • 1,422
  • 3
  • 15
  • 20

2 Answers2

0
$("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

Community
  • 1
  • 1
rsudip90
  • 799
  • 1
  • 7
  • 24
-1

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');

            };
        });
`
Pa3k.m
  • 994
  • 2
  • 7
  • 22