Are there any standards or messaging environments for AJAX?
Right now I have one page that loads content using Ajax. Since I had a complicated form for entering data as part of my content, I need to check out some events that may occur in my form. Therefore, after some adjustments due to my tests:
asyncShould("search customer list click", 3, function() { stop(1000); $('#content').show(); var forCustomerList = newCustomerListRequest(); var forShipAndCharge = newShipAndChargeRequest(forCustomerList); forCustomerList.page = '../../vt/' + forCustomerList.page; forShipAndCharge.page = 'helpers/helper.php'; forShipAndCharge.data = { 'action': 'shipAndCharge', 'DB': '11001' }; var originalComplete = forShipAndCharge.complete; forShipAndCharge.complete = function(xhr, status) { originalComplete(xhr, status); ok($('#customer_edit').is(":visible"), 'Shows customer editor'); $('#search').click(); ok($('#customer_list').is(":visible"), 'Shows customer list'); ok($('#customer_edit').is(":hidden"), 'Does not show customer editor'); start(); }; testController.getContent(forShipAndCharge); });
Here is the controller to get the content:
getContent: function (request) { $.ajax({ type: 'GET', url: request.page, dataType: 'json', data: request.data, async: request.async, success: request.success, complete: request.complete }); },
And here is the request event:
function newShipAndChargeRequest(serverRequest) { var that = { serverRequest: serverRequest, page: 'nodes/orders/sc.php', data: 'customer_id=-1', complete: errorHandler, success: function(msg) { shipAndChargeHandler(msg); initWhenCustomer(that.serverRequest); }, async: true }; return that;
}
And here is the success handler:
function shipAndChargeHandler(msg) { $('.contentContainer').html(msg.html); if (msg.status == 'flash') { flash(msg.flash); } }
And on my server side, I get a JSON structure that looks like this:
$message['status'] = 'success'; $message['data'] = array(); $message['flash'] = ''; $message['html'] = ''; echo json_encode($message);
So, loading content consists of two parts:
- HTML is a representation of the form.
- DATA, this is any data that must be loaded for the form
- FLASH, any validation or server errors
- STATUS tells the client what happened on the server.
My question is: Is this a legitimate way to handle event messages on the client side, or am I on the path of suffering and pain?