I am using this piece of code in Javascript. Backend-wise things are organized in an organization like MVC, so things affecting one module are usually grouped together. In general, I also first create a module for a separate model, but in some cases you can deviate from this principle.
My setup with symfony on the back and simple jquery in the front. There are several approaches that automate this part, for example http://javascriptmvc.com/ , and I find it too limited in many parts. Here is my workflow for integrating php and jquery.
Php
Execute part of the code and wrap it in a try / catch block. Thus, error messages can be transmitted to the external interface. This method helps to convert exceptions into a readable error in this regard. (for debugging from json).
try { //... execute code .. go about your buisness.. $this->result = "Moved " . count($files) . " files "; // result can be anything that can be serialized by json_encode() } catch (Exception $e) { $this->error = $e->getMessage() . ' l: ' . $e->getLine() . ' f:' . $e->getFile(); // return an error message if there is an exception. Also throw exceptions yourself to make your life easier. } // json response basically does something like echo json_encode(array("error" => $this->error, "result" => $this->result)) return $this->jsonResponse();
For error handling, I often use this to analyze errors.
public function parseException($e) { $result = 'Exception: "'; $result .= $e->getMessage(); $trace = $e->getTrace(); foreach (range(0, 10) as $i) { $result .= '" @ '; if (!isset($trace[$i])) { break; } if (isset($trace[$i]['class'])) { $result .= $trace[$i]['class']; $result .= '->'; } $result .= $trace[$i]['function']; $result .= '(); '; $result .= $e->getFile() . ':' . $e->getLine() . "\n\n"; } return $result; }
Javascript side
jQuery.doRequest = function (action, data, successCallback, errorCallback) { if (typeof(successCallback) == "undefined") { successCallback = function(){}; } if (typeof(errorCallback) == "undefined") { errorCallback = function(data ){ alert(data.error); }; } jQuery.log(action); jQuery.post(action, data, function (data, status) { jQuery.log(data); jQuery.log(status); if (data.error !== null || status != 'success') {
Note: error callbacks are very nice if you combine them with something like pNotify
source share