Somename
Somename

Reputation: 3444

Whats the error in this AJAX jQuery?

I'm trying to removeClass and addClass on the jQuery $.get success. But it doesn't seem to work with $.get and works only if i include the entire $.ajax which i dont want to do.

The following code works:

$(".result").on("click", ".myul li",  function(){
    var mydiv = $(this).data("id");
    var enumgroup = {};
    enumgroup["id"]=mydiv;

         $.ajax({
         type: 'POST',
         url: 'checkenumresult.php',
         context:this,
         data: {id: mydiv},
         success: function (data) {
               $(this).removeClass("forseen0").addClass("forseen1");
         }
      });
 });

The following code doesnt work:

$(".result").on("click", ".myul li",  function(){
    var mydiv = $(this).data("id");
    var enumgroup = {};
    enumgroup["id"]=mydiv;

    $.get("checkenumresult.php", enumgroup, function(){
    context:this,    //tried without this too.
    success: function(data){
       $(this).removeClass("forseen0").addClass("forseen1");
    }
    });
});

Both the codes are working with respect to posting data to the php page. Only the 2nd code is not changing class of the element on success. What is wrong with the second code?

Upvotes: 0

Views: 70

Answers (3)

Victor
Victor

Reputation: 5131

There are two points to note:
1 - On your $.ajax call you're making a POST request, while in the other you're trying to make a GET request. You need to check your endpoint if he accepts both POST and GET;

2 - The success callback of your $.get request is the third argument, so your request should be something like:

$.get("checkenumresult.php", enumgroup, function(data) {
  $(this).removeClass("forseen0").addClass("forseen1");
});

If your endpoint only accepts POST, just change $.get to $.post: https://api.jquery.com/jquery.post/

FYK: https://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

Upvotes: 1

palaѕн
palaѕн

Reputation: 73966

You can post data to server in proper format using $.post() like:

$(".result").on("click", ".myul li", function() {
  vat $this = $(this);
  var mydiv = $this.data("id");
  var enumgroup = {};
  enumgroup["id"] = mydiv;

  $.post("checkenumresult.php", {id: mydiv}, function(data) {
    $this.removeClass("forseen0").addClass("forseen1");
  });
});

Upvotes: 1

Naga Srinu Kapusetti
Naga Srinu Kapusetti

Reputation: 1641

$(".result").on("click", ".myul li",  function(){
    var mydiv = $(this).data("id");
    var enumgroup = {};
    enumgroup["id"]=mydiv;    
    $.get("checkenumresult.php", enumgroup, function(data){
       $(mydiv).removeClass("forseen0").addClass("forseen1");        
    });
});

the third argument in the above get call is the callback for the response

Upvotes: 1

Related Questions