Ajax request works with dataType: 'text' fails with dataType: 'text / xml; encoding = UTF-8 '

When I try to execute an Ajax request with the data type 'text / xml; charset = utf-8 '... I get parsererror.

  • Xml answer is valid xml
  • The response header shows Content-Type 'text / xml; encoding = UTF-8 '.
  • This is not a cross-domain request.

These three problems were answers in other questions of parserror.

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 answer 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 make this work?

+7
xml ajax xml-parsing
source share
2 answers

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

Changing your request to the following should produce the expected result:

 url: url, type: "POST", dataType: 'xml', 
+4
source share

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

+1
source share

All Articles