-1

I have an Index.php file that makes an ajax call and loads a php page Within that php page that is loaded using ajax I have a html form. I am trying to do another ajax call from Index.php that if a select box is changed a new ajax call is made.

Everything works fine but the ajax on change for the select box.

I think it has something to do with the fact that the form is loaded in with ajax and the on change is using ajax.

Is this possible to do?

$(document).ready(function() {

    $("#message-loading").show();

    var dataString = 'id='+ id;

    $.ajax
    ({
        type: "POST",
        url: "details.php",
        data: dataString,
        success: function(html)
        {
            document.getElementById('message-box-body').innerHTML = html;   
            $("#message-loading").hide();
        }       
    }); 

This is the select change code

$(".selectbox").change(function()
    {
        var id=$(this).val();
        var dataString = 'id='+ id;
        $.ajax
        ({
            type: "POST",
            url: "another-page.php",
            data: dataString,
            cache: false,
            success: function(html)
            {
                $(".another-selectbox").html(html);
            } 
        }); 
    });

The select box is located inside the php page of the first ajax call. The ajax change should load new values for another select box within the first php page.

I have this working if I don't load the php page using ajax.

2 Answers2

1

jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM, for example - via AJAX, are unrecognized by jQuery.

To combat that either re-bind your jQuery function or use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.

Community
  • 1
  • 1
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
1

You can access newly created element on the pages using $(document).on.
$(document).ready is only aware of elements that existed when the page was loaded.

So, for an element that existed when you you loaded the page you would use:

$(document).ready(function(){   
    $("#element").click(function() {
       alert("You clicked an element that existed when you loaded this page.");
    });
});

For an element that did not exist when you loaded the page, you would use the following:

$(document).on({
    click: function () {
       alert("You clicked an element that DID NOT exist when you loaded this page.");
    },
}, '#element');
Calvin
  • 197
  • 2
  • 11