Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax() function is ignoring dataType parameter in Firefox

I'm trying to use jQuery.ajax() to fetch some html, but Firefox is giving me a "junk after document element" error message. As explained here and here the problem seems to be that Firefox is expecting XML from the server, and when it doesn't parse correctly it throws the error. Here's my ajax code:

jQuery.ajax({
    url: name,
    dataType: "html",
    success: function(result) {
        console.log(result);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});

The server returns the html with these response headers:

Accept-Ranges   bytes
Content-Length  2957
Last-Modified   Tue, 02 Jul 2013 16:16:59 GMT

Note that there's no content-type header. I'm sure that adding one would solve the problem, but that's not an option.

The real problem is that Firefox appears to be ignoring the dataType: parameter in the ajax call. I've also tried adding contentType: and accepts: parameters, but it doesn't help.

What am I missing here? How do I force Firefox to process the response as plain text?

like image 666
ccleve Avatar asked Nov 24 '25 17:11

ccleve


1 Answers

The above code is working fine.

you can use the below code. As I noticed your file should be saved in .txt format.

 jQuery.ajax({
    url: "https://www.w3schools.com/jquery/demo_test.txt",
    dataType: "html",
    success: function(result) {
        console.log(result);
        const parser = new DOMParser();
        const res = parser.parseFromString(result, 'text/html');
        console.log(res);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});

I have tested this code in Firefox and it's working fine.

enter image description here

like image 180
Negi Rox Avatar answered Nov 26 '25 07:11

Negi Rox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!