Monday, 11 December 2017

JQuery not working after inserting DIV content using AJAX





I am using JQuery (1.10.1) to run an AJAX call and insert content
into a DIV.

Any click on an li tag within the ajax DIV should
trigger an alert as well as the AJAX method. The first time this is run it works, but
subsequent calls fail and I do not get an
alert.



I think that I should be binding the ajax
DIV after a successful AJAX call but I am not sure. I have experimented with the .on
method, and then .bind, but without detailed JQuery understanding, I can't go any
further. There could be something far more basic that I have
overlooked.



test1.php:




"http://www.w3.org/TR/html4/loose.dtd">




http-equiv="Content-Type" content="text/html;
charset=utf-8">
Test
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">

type="text/javascript">

$(document).ready(function() {


$('#ajax li').click(function() {



alert("Clicked");

$.ajax({
type: "post",

cache: false,
success: function(data){

$('#ajax').load("test2.php");
},
error:function(){

$("#ajax").html('Submission Error');

}
});



});

});







id='ajax'>


  • Example list item
    #1

  • Example list item #2


  • Example list item
    #3










test2.php






  • Red

  • data-val='100008'>Blue
    data-val='100007'>Green



Answer




You must delegate from the elements existing
when you do the binding, you can use on for
that.



Change




$('#ajax
li').click(function() {



to



$('#ajax').on('click',
'li', function() {


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...