0

I am showing/hiding divs with jQuery. The following code works on a normal page, but does not work in my page that is loaded with AJAX in a new <div>:

 <script>
    $(document).ready(function (){
        $("#pic_video").change(function() {
            // foo is the id of the other select box
            if ($(this).val() == 1) {
                $("#pic_amount_id").show();
                $("#vid_duration_id").hide();
            }
            else if ($(this).val() == 2) {
                $("#pic_amount_id").hide();
                $("#vid_duration_id").show();
            }
            else if ($(this).val() == 3) {
                $("#pic_amount_id").show();
                $("#vid_duration_id").show();
            }
        });
    });
</script



 <p style="margin-top:15px;"><b>Select</b></p>
 <span class="small"></span>
 <select name="pic_video" id="pic_video" style="width:95%;margin-top:6px;">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
 </select>


 <div id="pic_amount_id">TEST</div>
 <div id="vid_duration_id">TEST2</div>

The above is placed in my page that is loaded with Ajax. The ajax script (JavaScript) is a bit long to add here, but maybe the jQuery has to be loaded during/after the ajax?

The ajax is triggered with normal JavaScript during a onclick='' event and loaded into a new <div id='result'>

<a href onclick="loadAjax2(...)"...>Click here</a>.

And the loadAjax2() script triggers the usual ajax javascript:

function loadAjax(...) {
 if (window.XMLHttpRequest)
 {// code for IE7+, Firefox, Chrome, Opera, Safari
 xmlhttp=new XMLHttpRequest();
 }
 else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
 {
 if (xmlhttp.readyState==4 && xmlhttp.status==200)

 ...

 xmlhttp.open("GET",strURL+'&'+Math.random(),true);
 xmlhttp.send();
 }

What am I forgetting? Or is mixing jQuery/JavaScript not a good idea here?

Nicolas.
  • 453
  • 1
  • 5
  • 27
  • By loading the page through AJAX, do you mean that the HTML part of your document containing `#pic_video` is being loaded by AJAX? – Shekhar Chikara May 03 '17 at 20:53
  • Do you have an example of a generated `
    `?
    – apires May 03 '17 at 20:53
  • $(document).ready will not fire when loaded by AJAX [Does AJAX loaded content get a "document.ready"?](http://stackoverflow.com/questions/20246299/does-ajax-loaded-content-get-a-document-ready) – Fabian Horlacher May 03 '17 at 20:58
  • Are you really supporting IE6 or less? Because damn. Also, jQuery's ajax method abstracts a lot of that code away, even for those older browsers (although you'll need to use a pretty old version of jQuery too). – Heretic Monkey May 03 '17 at 21:23
  • It's impossible to say without knowing what parts of the HTML code is added via ajax. If the code given in the answers you've received aren't fixing the problem, you're likely not giving us a [mcve]. – Heretic Monkey May 03 '17 at 21:25
  • when you `onclick` the `select` is loaded from `page.php`? – Junius L May 03 '17 at 21:28

3 Answers3

1

To listen for events from elements loaded after DOM, try:

$(document).on("change", "#pic_video", function() {....
Sterling Beason
  • 622
  • 6
  • 12
1

When adding events to dynamically added element you need to use $(document).on('event', 'selector', function() {}); Use jQuery for your AJAX request.

<a href id="get-page-data">Click here</a>
<div id="result"></div>
<script>
    $(document).ready(function () {
        $(document).on('change', '#pic_video', function () {
            // foo is the id of the other select box
            if ($(this).val() == 1) {
                $("#pic_amount_id").show();
                $("#vid_duration_id").hide();
            }
            else if ($(this).val() == 2) {
                $("#pic_amount_id").hide();
                $("#vid_duration_id").show();
            }
            else if ($(this).val() == 3) {
                $("#pic_amount_id").show();
                $("#vid_duration_id").show();
            }
        });
    });

    // AJAX using jQuery
    $('#get-page-data').on('click', function (e) {
        e.preventDefault(); // prevents the default behaviour of <a>
        var strURL = 'http://localhost/stack-delete/page.php?';
        // you can pass variables to PHP by using an object like {random: Math.random()}
        // this $.get() can now be like $.get(strURL, {random: Math.random()} , function (response) {
        // in your PHP, you can get the value like $random = $_GET['random']
        // this Math.random() seems odd as you are not using it in your page.php,
       // and the correct url should be strURL + '&random=' + Math.random()
        $.get(strURL + '&' + Math.random(), function (response) {
            $('#result').html(response);
        });
    });
 </script>
Junius L
  • 15,881
  • 6
  • 52
  • 96
0

Javascript code loaded as DOM Element through an AJAX request will not get executed. However, there are two ways to accomplish this-

  1. Dynamically binding elements

In this approach, the idea is to keep the Javascript code in the page where you are requesting the data from AJAX, and then bind the events for the elements existing in your AJAX data to the parent elements present on the current page. For example, in your case here - <div id="result"></div> already exists on the page initially. So you can move your Javascript code to this page, and bind the change event on #pic_video element fetched dynamically to the #result div using .on().

<script>
    $(document).ready(function (){
        $("#result").on('change', '#pic_video', function() {
            // foo is the id of the other select box
            if ($(this).val() == 1) {
                $("#pic_amount_id").show();
                $("#vid_duration_id").hide();
            }
            else if ($(this).val() == 2) {
                $("#pic_amount_id").hide();
                $("#vid_duration_id").show();
            }
            else if ($(this).val() == 3) {
                $("#pic_amount_id").show();
                $("#vid_duration_id").show();
            }
        });
    });
</script>
  1. Evaluate the loaded DOM element on AJAX Complete

In this case, you can execute the <script> element loaded in the DOM through the AJAX request in the following manner-

var arr = $('#result').getElementsByTagName('script');
for (var n = 0; n < arr.length; n++)
    eval(arr[n].innerHTML)//run script inside div

Hope this helps!

Shekhar Chikara
  • 3,786
  • 2
  • 29
  • 52
  • I tried this, but this doesn't seem to make it work. Maybe due to my Ajax code – Nicolas. May 03 '17 at 21:14
  • @Nicolas. So, initially when your page loads, is the element `
    ` loaded on your page? I mean before clicking on the `loadAjax2(...)` link.
    – Shekhar Chikara May 03 '17 at 21:15
  • Yes but it is empty. When the Ajax is triggered, the div is filled with the new page.php with all the html/jquery code – Nicolas. May 03 '17 at 21:17
  • Got it. So for the above code to work, you need to move your Javascript code to the initial page where you have the `#result` element. If you keep this in the html/jquery data you're getting from your AJAX request, then the click event won't get bound to the element. – Shekhar Chikara May 03 '17 at 21:19
  • @Nicolas. I have updated the answer with 2 approaches that you can take. Please check if it helps – Shekhar Chikara May 03 '17 at 21:50
  • Awesome, that was it! Placing the (adapted) script in the initial page. Thanks! – Nicolas. May 04 '17 at 15:48