Brian Rice
Brian Rice

Reputation: 3257

Ajax query works with dataType:'text' fails with dataType:'text/xml; charset=utf-8'

When I try to do an Ajax query with dataType of 'text/xml; charset=utf-8'... I get a parsererror.

  1. The xml response is valid xml
  2. The response header shows a Content-Type of 'text/xml; charset=utf-8'.
  3. It's not a cross domain request

These three problems were answers in other parsererror questions.

My ajax looks like this:

        $('#submitLogin2').click(function (e) {
            e.preventDefault();
            var formData = $('#loginForm2').serialize();
            var url = 'http://somewhere.com/Api2.0/Session_Create.aspx';
            $.ajax({
                url: url, type: "POST", dataType: 'text/xml; charset=utf-8',
                data: formData, contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                success: function (data) {
                    $('#loginResult').html(data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;').replace(/\n/g, '<br />'));
                },
                error: function (textStatus, errorThrown) {
                    alert(errorThrown);
                    alert(JSON.stringify(textStatus));
                }
            });
        });

And the response is:

<Response><Error code='0'>Invalid User Name or Password</Error></Response>

It's great that the 'text' request works... but it would be nice to let Ajax parse the xml for me. Any ideas on how to get this to work?

Upvotes: 8

Views: 1170

Answers (2)

Noli
Noli

Reputation: 614

You have also to parse the XML response to process it as string with something like $.parseXML(data) or a XMLSerializer. I think this is even more important, hence the response dataType should be automatically determined by the MIME type.

Upvotes: 1

Mirec Miskuf
Mirec Miskuf

Reputation: 1695

Looking at http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings - dataType "xml" is supported.

Changing your query to following should give you expected result:

url: url, type: "POST", dataType: 'xml',

Upvotes: 5

Related Questions