views:

3791

answers:

3

Hi,

I want to fire a function when an image is clicked, and that function will hit a URL passing it a parameter and then update the containing div's class with the value I get back from the URL.

Can someone help me with code for this?

My DOM looks like:

<div class="c1"><img src="/images/hello.jpg"/></div>

My URL is http://www.example.com/ajax/image.aspx?className=c1.

So I want to go to that url using a ajax request passing it the current class name, and then it will return e.g. c2. I then update the div's class to c2 using a callback.

+1  A: 

This is assuming that your only returning plain text from your service. It might be useful to include a sample of the format of the return content in your question. I'm also not sure if you need the removeClass function, but I added it anyways.

$('c1 > img').click(function() {
  var img = $(this);
  $.get('http://www.example.com/ajax/image.aspx?className=c1', null, function(data){
    img.closest('div').removeClass('c1').addClass(data);
  });
});
bendewey
The addition of closest makes traversal up the tree much easier.
Mark
A: 

I assume you wish to keep updating the class on each new click (c1, c2, c3, ...)?

var classname = 'c1';
$('div.' + classname + ' > img').click(function() {
  var div = $(this).closest('div');
  var url = 'http://www.example.com/ajax/image.aspx?className=' + classname;
  $.get(url, null, function(data){
    div.removeClass(classname).addClass(data);
    classname = data;
  });
});

Also, you may want to do the click check on the whole div rather than just the image:

var classname = 'c1';
$('div.' + classname).click(function() {
  var div = $(this);
  var url = 'http://www.example.com/ajax/image.aspx?className=' + classname;
  $.get(url, null, function(data){
    div.removeClass(classname).addClass(data);
    classname = data;
  });
});
waqas
A: 

This assumes that the div starts out with only one class. If it has more than one, you're going to need to do some work to get the class you're after.

$('img').click(function() {
  var $img = $(this);
  var $div = $(this).parent();
  var divClass = $div.attr('class');
  var url = 'http://www.example.com/ajax/image.aspx';

  $.ajax({
    'type' : 'get', // change if needed
    'dataType' : 'text', // data type you're expecting
    'data' : { 'className' : divClass },
    'url' : url,
    'success' : function(newClass) {
      $div.removeClass(divClass); // if needed
      $div.addClass(newClass);
    }
  });
});
rmurphey