[nycphp-talk] Ajax 101: what to return from a POST
Mark Armendariz
lists at enobrev.com
Thu May 3 15:56:10 EDT 2007
>>> From: talk-bounces at lists.nyphp.org [mailto:talk-bounces at lists.nyphp.org]
On Behalf Of David Mintz
>>> I have experimented with converting a PHP array of error messages
(fieldName => errorMessage, etc) into JSON and sending that back, then doing
DOM scripting to stick the error messages into some DIVs. Kind of a lot of
work, but it's efficient in the sense that you only send data that the front
end needs.
I like the previously mentioned ideas of returning an error code in the
header. I currently just return an error array in the returned data. I
definitely agree that sending back an entire form that already exists is too
much.
I do something very similar to your method. If your fields have id's based
on their names you can manipulate them pretty easily to show the error.
Here's something similar to how I do it...
/*
* ids are field_<field_name> so an email field would have an id of
field_email
*** oReturnedData would be a JSON object from the server
*/
// example var
var oReturnedData = {
errors : [
{field: 'email', message: 'we do not accept hotmail
accounts'},
{field: 'age', message: 'you must be over 21 to
register'}, {field: 'phone', message:
'we both know this is not a phone number'}
],
otherstuff : []
}
if (oReturnedData.errors !== undefined)
&& oReturnedData.errors.length) {
$A(oReturnedData.errors).each(
function(oError) {
if ($('field_' + oError.field) !== null) {
var sField = '<p class="error">' + oError.message + '</p>'
new Insertion.After($(oError.field), sField);
}
}.bind(this)
);
}
I usually manipulate the field labels, but I figured this shows the general
idea best and simplest.
Mark
More information about the talk
mailing list