Jump to content

jQuery: error creating DOM element


Go to solution Solved by haku,

Recommended Posts

Hey guys,

 

I am sending an AJAX request with jQuery where I get JSON back. The JSON includes some HTML markup in UTF-8. For some reason, I get the following error when I try to create a DOM element with it (it used to work!):

 

 

Uncaught Error: Syntax error, unrecognized expression: <div class="message self"> <strong>Andy123 wrote:</strong> <br /><br /> Profile link: /profile/45873/Andy123 <br /><br /> fsafawfwf222222222</div>

 

Here is the code that triggers the error:

 

 

$(data.markup).hide().appendTo('#messageContainer').fadeIn(500);

 

If I put the same markup into a variable (or overwrite data.markup), without transferring over the network, it works as intended.

 

Request headers:

  1. Accept:
    application/json, text/javascript, */*; q=0.01
  2. Accept-Charset:
    ISO-8859-1,utf-8;q=0.7,*;q=0.3

Response headers:

Content-Type:
application/json; charset=utf-8

 

I am not that good with charset and things, but to me that looks OK. Here is the JSON that is returned from the web server (PHP):

 

 

{"markup":"\n\u003Cdiv class=\u0022message self\u0022\u003E\n \u003Cstrong\u003EAndy123 wrote:\u003C\/strong\u003E\n\n \u003Cbr \/\u003E\u003Cbr \/\u003E\n\n Profile link:\n\n \/profile\/45873\/Andy123\n \u003Cbr \/\u003E\u003Cbr \/\u003E\n\n fsafawfwf222222222\u003C\/div\u003E"}

 

I suspect that it has something to do with encoding, hence why I pasted the above. Any idea what is wrong? Thanks! :)

Link to comment
https://forums.phpfreaks.com/topic/276301-jquery-error-creating-dom-element/
Share on other sites

  • Solution

Try changing this:

$(data.markup).hide().appendTo('#messageContainer').fadeIn(500);
To :
$("<div/>").html(data.markup).contents().hide().appendTo('#messageContainer').fadeIn(500);
If you're lucky, it will bypass the problem. Ideally, passing the returned data through the $.html() function will parse it differently than passing it through the base $.() jquery function (which is what you are currently doing).

 

Can you show more of your code? Where exactly is the code that you showed us located? I'm assuming it in the callback of one of jQuery's Ajax functions, but maybe that assumption is mistaken.

 

The return headers indicate that you are getting what you are asking for - utf-8 with a JSON mime type. So that's not your problem there. One other thing you could maybe check is the encoding of the document of your script. For example, if your document itself (*.php) is encoded in a non-utf-8 encoding, it may be having issues with the utf-8 encoding of the return data.

 

If none of that works, do a call to console.log(data.markup); and open a javascript debugging console. That will give you a better idea of what the returned data looks like so you can maybe debug the issue.

Edited by haku

Hello haku,

 

Thank you very much for your answer. It turned out that I was lucky; your solution works!

 

I do find it a bit strange, because the HTML I get back is perfectly valid HTML. I did a console.log, and it shows the markup in the beginning of my initial post (in the error message). Before I wrote here, I did try the $.html function, but that did not work either. The encoding of my document is also correct.

 

I am quite confused as to why I got this error in the first place, so I will paste in some more code. If you can identify the problem please let me know. Otherwise thank you very much for your help! :)

 

 

// Inside a click event
 
        $.ajax({
            type: 'POST',
            url: URL_SEND_MESSAGE,
            data: ($(form).serialize() + '&include_markup=true'),
            dataType: 'json'
        }).done(function(data, textStatus, xhr) {
            // Created
            if (xhr.status == 201) {
                //$(data.markup).hide().appendTo('#messageContainer').fadeIn(500); // This doesn't work
                $("<div/>").html(data.markup).contents().hide().appendTo('#messageContainer').fadeIn(500); // This works
            }
        }).fail(function(xhr) {
            /* ... */
        });

I've never done jQuery AJAX the way you are doing it, and it may have something to do with the issue. I always use the following pattern:

 

 

$.ajax({
            type: 'POST',
            url: URL_SEND_MESSAGE,
            data: ($(form).serialize() + '&include_markup=true'),
            dataType: 'json',
            success:function(data) {
              // Success stuff here
            },
            failure:function(data) {
              // Failture stuff goes here
            }
});

 

Anyways, I'm glad it worked for you the way I showed. Weird error.

I've never done jQuery AJAX the way you are doing it, and it may have something to do with the issue. I always use the following pattern:

 

 

$.ajax({
            type: 'POST',
            url: URL_SEND_MESSAGE,
            data: ($(form).serialize() + '&include_markup=true'),
            dataType: 'json',
            success:function(data) {
              // Success stuff here
            },
            failure:function(data) {
              // Failture stuff goes here
            }
});

 

Anyways, I'm glad it worked for you the way I showed. Weird error.

 

Yes, that is the way I have always done it as well. I recently started going about it in a new way because the callback handlers you are using in your example (at least the success one) are deprecated as of jQuery 1.8 (scroll about half way down the page). Thanks again for the solution. I was going to mark the thread as solved, by the way, but I just wanted to give you another shot. :)

Edited by Andy123
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.