Jquery – Ajax jQuery , beginner question


I'm trying to make an ajax call to grab session data to insert into my page after it's loaded like this

jQuery(function(){ // Add Answer

    var count = $(this).attr("alt");
    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);


The file i'm calling is found but its contents are not printed out by 'p_type'
and the $(this).attr("alt", count); part of the function is not executing

Note: I'm using CodeIgniter for my framework and jquery for js

Best Solution

I believe your problem has to do with the scope of $(this). Because you've got your ajax get function nested inside your livequery function, inside yet another anonymous function, I'd be willing to bet that $(this) is now refering 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:

    var add_answer = $(this);


The above code should cache the add_answer element, but my livequery knowledge is a bit rusty.

Some recommendations on your code:

  • Be consistent with the use of either jQuery() or $() shortcuts, they do the same thing.
  • What's with the anonymous function surrounding the whole snippet? Is that just for a simplified example? It should probably be replaced with a $(document).ready(function { ... });