user3553866
user3553866

Reputation: 326

Elements not present after the loading of my page

We are creating an administration console, the client will udpate his site by himself.

To do that, we creating div with js and PHP (ajax) :

    $(document).ready(function($)
    {
    function loadContent(page)
        {

            $.ajax(
            {
                url: 'contenu/contenu.php',
                type: 'POST',
                dataType: 'html',
                data:
                {
                    'onglet': page
                },
                success:function(contenu)
                {
                    console.log("success");
                    $("div."+page).html(contenu);   
                }
            })
        };
});

And the PHP code (just a part of it) :

$reponse = $db->query('SELECT * FROM philosophie');
$data = $reponse->fetch();
//maj de la version FR de philosophie
echo '<form action="#" method="POST">
<label>Texte en français :</label><br/>
<textarea  name="texte_fr">'.$data["texte_fr"].'</textarea><br/>
<br />
<input type="button" id="maj_philosophie_fr" value="Mettre à jour ce texte" />
<br /><br />';

The form appears on the site, it's working great.

After, I want to know how many button with id beginning with "maj_" are inside the site with this code :

alert($("[id^='maj_']").length);

I still have 0 as reply.

The element is not ready and I'm not able to get a change event on my divs.

I see the elements in firebug (DOM section), the are in red characters.

Have you an idea please ?

Upvotes: 2

Views: 41

Answers (1)

azium
azium

Reputation: 20634

Looks like your alert is running before your success function has been called. Try moving your alert inside there, and better yet, throw it in the next event cycle with a setTimeout.

$(document).ready(function () {
  function loadContent (page) {
    $.ajax({
      url: 'contenu/contenu.php',
      type: 'POST',
      dataType: 'html',
      data: { 'onglet': page },
      success: function (contenu) {
        console.log("success")
        $("div."+page).html(contenu)

        setTimeout(function () {
          alert($("[id^='maj_']").length)
        }, 100)
        // might even work with 0, if the dom render function 
        // is the very next thing in the queue
      }
    })
  }
})

If you have to work with many nested ajax calls, you probably want to look into using the promise api. Here are the docs for the jQuery implementation of $.promise()

Making sure your code runs after a success function has been called is not something that can be worked around. The code can't know about the data ahead of receiving it, this means either nesting your success callbacks, or using other solutions like chaining named function callbacks, or preferably promises.

Upvotes: 1

Related Questions