-4

In my php page i append new buttons and information when press the button with JQuery Ajax,however when i click the new button which came with ajax , its JQuery does not work but old button's JQuery works,i mean new button does not see the javascript file of my php page.

My JQuery Ajax Codes;

$("button[name='addnewelement']").click(function() {




$.ajax({    


    type: "POST",
    url: "addelement.php",

    cache: false,
    success: function(html){


    $("#new").append(html);// add new element into index.php
  });
  });

addelement.php;

  echo "
      .......
     <button id="<?php echo $row['id']; ?>" name="addnewelement"  >Add</button>
     ....... 
   " ;

How can i solve this problem?

Thanks.

gzml
  • 103
  • 1
  • 1
  • 5

2 Answers2

1

Your echo in the addelement.php page would be like

echo '<button id="'.$row['id'].'" name="addnewelement"  >Add</button>';
exit;

And also better to put the exit after the echo.Make sure that you follow the syntax and use a good IDE to find the syntax errors.

GautamD31
  • 28,552
  • 10
  • 64
  • 85
1

You should use on click event handler instead of click event handler.
Here is the link : http://api.jquery.com/on/
eg.

$( document).on( "click", "button[name='addnewelement']", function() {
$.ajax({    
    type: "POST",
    url: "addelement.php",
    cache: false,
    success: function(html){
    $("#new").append(html);// add new element into index.php
  });
});
Akshay Vanjare
  • 655
  • 3
  • 10
  • The important thing is to use `.on()` with delegation, like you do in your answer. `.on()` without delegation is just the same as using `.click()` and won't work for dynamically added elements. – Peter Herdenborg Nov 07 '14 at 07:51
  • it does not add new element but it enters when clicking the button,why would not work ajax? – gzml Nov 07 '14 at 08:07
  • add `return false;` before closing on click function – Akshay Vanjare Nov 07 '14 at 09:05
  • i have already added it before,the problem is that,element which is created with ajax, cannot run ajax again.What am i missing? – gzml Nov 07 '14 at 09:08
  • 1
    Try adding click event on class instead of name. Name consider to be a unique value in HTML. I think that causing the problem. – Akshay Vanjare Nov 07 '14 at 09:50