Problem with jquery $.ajax function

I am using $().append() to append some css / divs to a page. In this appended content there is an id that I am trying to use for an $ajax call when user clicks, however it seems to only work if I hardcode the css directly into the page but not if I append… any ideas??

In fact when I append and look into source, there is no div… is this how $().append() works?

MY CODE

$('.out-div').append('<p class="reward"><input type="text" name = "login"/><br/><input type="submit" name="ajax_call" class ="ajax_call"/></form></p>');	

AJAX CODE

$(document).ready(function(){
			   
		  $(".ajax_call").click(function(){
											 
				  $.ajax({
						 
						 url: 'http://localhost/places/password/12345/format/jsonp',
						 dataType: 'jsonp',
						 type: 'GET',
						 success: function(){
							 
						  setCookie('user_id',5,7);
						  
						  
						  
						 // window.location.reload(true);
							 
						 }

					   
					});
			  
		  });
							   }); 

If the ajax_call class has not been appended when you try to set up the click event, there won’t be any element there on which to attach the click event so the attempt will fail.

One way to deal with that is to append the content before associating an event to it.
Another way is to make use of jQuery’s on() method, which replaces the events and delegates and bind and live methods.

For example, to have the document watch for and attach an event to ajax_call now and in the future, whenever that class name is added, you now do that with:


$('document').on('click', '.ajax_call', function () {
    ...
});

Im not 100% sure where to put this code, do I replace the click function in my initial code, or the entire document ready function?

Just the click code should do.

thanks that worked!

thanks again… not sure if you can help me with this also http://www.sitepoint.com/forums/showthread.php?858225-Problem-with-calling-ajax-function&p=5129028#post5129028

sorry I created two seperate threads as it is slightly different…but based on the code in this thread