Invalid XML while AJAX return is valid

1.3k views Asked by At

I do use jQuery Form Plugin and ajaxSubmit. But when it comes to the return value, I get this one (with two blank rows in front, but they got cut off here).

<?xml version="1.0" encoding="UTF-8"?>
<elements>
 <success>
  <value>282</value>
 </success>
</elements>

The ajaxSubmit call has a dataType: "xml" and the header on return is correct, but the ajax stops with a "Invalid XML" error. I thought the two blank lines are incorrect, but even a trim won't remove them. XML Generation looks like this btw:

$output = new XMLWriter();
$output->openMemory();
$output->setIndent(true);
$output->startDocument('1.0', 'UTF-8');
$output->startElement("elements");

if (isset($theID)) {
  $output->startElement("success");
  $output->startElement('value');
  $output->text($theID);
  $output->endElement(); //value
  $output->endElement();
}

$output->endElement(); //elements
$output->endDocument();
$xml = $output->outputMemory(true);
header('Content-type: text/xml; charset=utf-8');
print trim($xml);

Anyone has an idea what could possible be wrong here?

EDIT: Here is the Javascript, but as it is doing fine (even with headers, I didn't show it in the first place):

$('#formNewForm').ajaxSubmit({
        dataType: 'xml',
        beforeSubmit: function () {
          // something
        },
        error: function (jqXHR, textStatus, errorThrown) {
          // something
        },
        success: function (responseXML) {
          // something
        }
      });
2

There are 2 answers

0
Andi On

The solution is quite simple as it has nothing to do with the script or the generated xml at all. It is caused by php closing tags ("?>") used in some included php files when a new-line is after it.

1
leoap On

I lied in comments, i made an update to your javascript. Here's my working code:

<form id="formNewForm" action="ajax-test.php" method="post">
    <input type="text" name="name">
    <input name="submit" type="submit">
</form>
<script>
    // bind to the form's submit event
    $('#formNewForm').submit(function() {
        // inside event callbacks 'this' is the DOM element so we first
        // wrap it in a jQuery object and then invoke ajaxSubmit
        $(this).ajaxSubmit({
            dataType: 'xml',
            beforeSubmit: function () {
                // something
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // something
            },
            success: function (responseXML) {
                alert(responseXML);
            }
        });

        // !!! Important !!!
        // always return false to prevent standard browser submit and page navigation
        return false;
    });
</script>