Thai Doan
Thai Doan

Reputation: 292

I can't get data from HTML which is created by JS

I use a jQuery to create a new HTML but when I use $.get or $.ajax methods it can't get that data ? For example I tested a simple jQuery :

$(function () {
    $(".tc3").html('<div id="test" ></div>');

    if($('.noprint a[href*="/f1-"]:first').length){
        $.ajax({
            url: '/f1-' ,
            type: 'GET',
            success: function(data) { 
                d = $('#test', data).length;
                alert(d)
            } 
        });
    }
});

But when I try it alert the result is 0 . So why ? Thanks for reply

Upvotes: 1

Views: 238

Answers (4)

Frederik.L
Frederik.L

Reputation: 5620

If I take a look in your Javascript ( codefm1.forumvi.com/99787.js ):

$(function(){

    $(".tc3").html('<div id="test" ></div>');
    if($('.noprint a[href*="/f1-"]:first').length){

        $.ajax({

            url:'/f1',
            type:'GET',
            success:function(data){

                test=$("#test").length;
                d=data.length;alert("Test length: "+test)
            }

        }
        )
    }

}
);
$(function(){
    $(".tc3").html('<div id="test" ></div>');if($('.noprint a[href*="/f4-"]:first').length){
        $.ajax({
            url:'/f4-',type:'GET',success:function(data){
                $('#test').html(data);var d=data.length;alert(d)
            }

        }
        )
    }

}
);

I see that your first alert only confirms that #test doesn't exist at this point yet. Try alerting data.length in the first ajax request instead of $('#test').length. If it still returns 0 then it means that nothing is returned.

Upvotes: 0

Brandon J. Boone
Brandon J. Boone

Reputation: 16472

Though I could be mistaken, I'm fairly certain your syntax is incorrect.

In the expression $('#test', data), you are passing in data as the context to constrain what your selector, #test, can match.

From the jQuery documentation:

By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function. For example, to do a search within an event handler, the search can be restricted like so:

$( "div.foo" ).click(function() {
  $(  "span", this ).addClass( "bar" );
});

When the search for the span selector is restricted to the context of this, only spans within the clicked element will get the additional class.

Internally, selector context is implemented with the .find() method, so $( "span", this ) is equivalent to $( this ).find( "span" ).

With this in mind, your above data object would have to be a DOM Element, Document, or jQuery object in order for it to correctly constrain the scope of the #test selector. Since data is unlikely to be any of these objects, the constraint will produce an invalid scope for #test to be found. Consequently, 0 is alerted.

Since I do not believe constraining the #test selector was your intent (after all there can only be one element with an id of test on a valid HTML page regardless of context), I can only assume you meant to append the contents of data to the test div. If my assumption is correct you should change your success method to:

success: function(data) { 
   var d = $('#test').html(data).length;
   alert(d);
} 

In this case the length will be 1 since html() is chained to the initial $('#test') selector. And since there is only one element on the page with an Id of test, 1 will be alerted.

If instead you wanted the length of data, you can interrogate it directly with data.length which should give you the appropriate result depending on the object or string returned.

success: function(data) { 
   $('#test').html(data);

   var d = data.length;
   alert(d);
} 

Lastly if data can be null, undefined, or otherwise falsy you can use var d = data ? data.length : 0; to ensure it always defaults to 0.

NOTE: Aside from addressing your syntax, much of this answer is speculative as I'm not sure what you're trying to accomplish. Adding more details to your question will help us better address your issue.

Upvotes: 3

Ashutosh Upadhyay
Ashutosh Upadhyay

Reputation: 481

What do you intend to do by passing data as second param to $('#test', data) ? The second param is the context in which the first param (selector) is evaluated. What are you returning from server in data? It has to be a parent of the '#test' selector for it to work.

Upvotes: 0

Jason
Jason

Reputation: 11363

Why do you have both #test and data in the same jQuery selector?

Try

success : function(data){
   test = $("#test").length;
   d = data.length;
   alert("Test length: " + test + "\nData length: " + data);
}

Upvotes: 0

Related Questions