javascript - Ajax is working only the first time -


this situation:

in codeigniter app, kind of social network demo, developing button.

when reading through posts using foreach loop, button displayed after each post. first time work properly: ajax sends data codeigniter method, data inserted table , button become green (succesfull). stops work. if refresh page, call not triggered anymore.

what have tried do:

have seen other answers in stack overflow , other forums, no 1 fixed problem. anyway codeigniter part correct, problem ajax calling.

have simplify debug purpose , right have very simple ajax function server side disable, thing should make buttons green when clicking on them. , again works first time , not work anymore...

this html:

<button id="button_like" type="submit" class="btn btn-primary"><span class="glyphicon glyphicon-thumbs-up"></span> like</button> 

this ajax call:

$('#button_like').click(function(e) {  e.preventdefault();  // alert('click');  var data = {   user_id: '5',  // debug   post_id: '6',  // debug   ajax: '1'   };  $.ajax({    url: "<?php echo site_url('post/like'); ?>",   type: 'post',   data: data,   success: function() {    $('#button_like').replacewith('<button type="submit" class="btn btn-success"><span class="glyphicon glyphicon-thumbs-up"></span></button>');   },   error: function(xmlhttprequest, textstatus, errorthrown) {              alert("status: " + textstatus); alert("error: " + errorthrown);          },   });  //  return false; 

});

this question:

how can make simple ajax call working every time?

thank much!

edit:

thanks guys answers. have made button_like class instead of id.

 <button type="submit" class="btn btn-primary button_like"><span class="glyphicon glyphicon-thumbs-up"></span> like</button> 

and call function in way:

  $('.button_like').on('click', function(e) { 

and success in way:

  success: function() {    $('.button_like').replacewith('<button type="submit" class="btn btn-success"><span class="glyphicon glyphicon-thumbs-up"></span></button>');   }, 

but now, after clicking on 1 button, makes green buttons. how can make green 1 click on? thank you!

edit 2:

i have recreated situation in jsbin:

http://jsbin.com/xulaxowa/1/edit

you're using id element in attach event. mean you're having same id repeated several times on page? if that's case, jquery add event first 1 finds... because expects 1 id per page.

try using classes instead, see how goes.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -