Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Line breaks in jQuery ajax html callback cause errors

Tags:

jquery

ajax

I am returning a large chunk of HTML from an $.ajax call. The string coming from PHP has two line breaks at the beginning, e.g.

$data = "

<div>
     <p>Here is some text</p>
</div>";

Here is the $.ajax call:

$('form#form_id').submit(function(e){
    e.preventDefault();
    $form = $(this);
    $.ajax({
        url: $form.attr('action'),
        type: $form.attr('method'),
        data: $form.serialize(),
        dataType: 'html',
        success: function(data) {
            var $html = $($.parseHTML(data));
            $html.appendTo('#container_id').hide().fadeIn(300);
        }
    });
});

Everything works until I add the .hide().fadeIn(300) at which point it throws: TypeError: 'undefined' is not an object (evaluating 'hooks.cur = fn') jquery.js:1925. If I remove the line breaks it works. I am using the $.parseHTML because jQuery says:

If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString)).

Any idea what’s going on?

like image 625
Andrew Tibbetts Avatar asked Mar 06 '13 21:03

Andrew Tibbetts


1 Answers

The problem seems to be caused by the text node in the collection you can filter it out with .filter('*')

var $html = $($.parseHTML(data)).filter('*');
like image 102
Musa Avatar answered Sep 28 '22 02:09

Musa