Ajax jQuery starter question

I am trying to make an ajax call to grab session data in order to insert it into my page after loading it like this

jQuery(function(){ // Add Answer

  jQuery(".add_answer").livequery('click',function(){
    var count = $(this).attr("alt");
    count++;
    var count1 = count-1;

    $.get('quiz/select', function(p_type){  // Ajax Call for Select Data

      $(this).parents('div:first').find('.a_type_'+count1+'').after('' + p_type + '');
      $(this).attr("alt", count);

    });
  });
});

      

Found a file that I am calling, but its contents are not printed 'p_type' and $(this).attr("alt", count);

part of the function is not executed

Note. I am using CodeIgniter for my framework and jquery for js

+1


source to share


2 answers


I believe your problem is related to the scope of $ (this). Since you have an ajax get function embedded in your livequery function inside another anonymous function, I bet $ (this) now refers to your $ .get () call or something.

You need to cache $ (this) as soon as possible at the point where you know it has the correct object selected:

jQuery(".add_answer").livequery('click',function()
{
    var add_answer = $(this);

    $.get(...)
    {
        add_answer.parents('div:first')...
    }
}

      



The above code should cache the add_answer element, but my real-time knowledge is a little rusty.

Some guidelines for your code:

  • Be aware of using jQuery () or $ () shortcuts, they do the same.
  • What about the anonymous function that spans the entire snippet? Is this just for a simplified example? It should probably be replaced with $ (document) .ready (function {...});
+3


source


"this" is a special keyword in Javascript. In your outer function, this refers to the .add_answer element. And in your inner function, this refers to the window.



jQuery(".add_answer").livequery('click',function(){
  var self = this;
  // ...
  $.get('quiz/select', function(p_type){
    // ...
    $(self).attr("alt", count);

      

0


source







All Articles