[jQuery] How does the form plugin (or jquery?) determine if a server response is an error or success?
In my particular scenario, the form plugin <http://www.malsup.com/
jquery/> is triggering the specified success function, despite the
server returning a 409 conflict error (as seen in Firebug). The error
itself is okay - that’s what I am expecting given the content of the
form. I’m trying to understand why the plugin reports success despite
the 4xx error.
I’m using the form plugin to submit a form that includes a file input
and a hidden field. As described by the documentation, the plugin
conceals the required page reload when uploading a file by directing
form submission response to a generated iframe, thus giving the
appearance of AJAX.
The docs <http://www.malsup.com/jquery/form/#code-samples> explain to
handle json server responses it is necessary to wrap them in a
textarea at the server end. Before I dig deeper into my options there
(I’m playng with CouchDB <http://couchdb.org>) I have done some
experiments I was hoping someone could help me understand:
$('#upload-file').ajaxForm({
dataType: 'html',
success: function(response) {
console.log('success:',response);
},
error: function(xmlobj,textStatus, errorThrown){
// ...
},
iframe: true,
target: '#target'
});
As I expected, the POST appears red in Firebug’s net listing - marked:
409 Conflict
This is the server response text according to Firebug:
{"error":"conflict","reason":"Document update conflict."}
Although this is the response that is written to the console is:
success: <pre>{"error":"conflict","reason":"Document update
conflict."} </pre>
If I set the dataType to 'json' the defined error function is fired -
to be expected as the plugin is expecting <textarea> rather than json
wrapped in <pre>…
SyntaxError: missing } in XML expression message=missing } in XML
expression
So I tried hacking the form plugin a little myself. Changing (around
line 300):
var ta = doc.getElementsByTagName('textarea')[0];
xhr.responseText = ta ? ta.value : xhr.responseText;
to:
var ta = doc.getElementsByTagName('pre')[0];
xhr.responseText = $(ta).text();
With this change in jquery.form.js and setting dataType to 'json' the
console looks a bit like:
success: Object error=conflict reason=Document update conflict.
Where Firebug has recognised the server response text as json - but
the form plugin (or jquery) is still reporting success.
Obviously there is more to this than I understand. All clues and
guesses are very welcome as this is new territory for me.
Cheers
Ollie