api.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /**
  2. * @description This module communicates with Lychee's API
  3. * @copyright 2015 by Tobias Reich
  4. */
  5. api = {
  6. path: 'php/api.php',
  7. onError: null
  8. }
  9. api.post = function(fn, params, callback) {
  10. var success,
  11. error;
  12. loadingBar.show();
  13. params = $.extend({function: fn}, params);
  14. success = function(data) {
  15. setTimeout(function() { loadingBar.hide() }, 100);
  16. // Catch errors
  17. if (typeof data==='string'&&
  18. data.substring(0, 7)==='Error: ') {
  19. api.onError(data.substring(7, data.length), params, data);
  20. return false;
  21. }
  22. // Convert 1 to true and an empty string to false
  23. if (data==='1') data = true;
  24. else if (data==='') data = false;
  25. // Convert to JSON if string start with '{' and ends with '}'
  26. if (typeof data==='string'&&
  27. data.substring(0, 1)==='{'&&
  28. data.substring(data.length-1, data.length)==='}') data = $.parseJSON(data);
  29. // Output response when debug mode is enabled
  30. if (lychee.debugMode) console.log(data);
  31. callback(data);
  32. }
  33. error = function(jqXHR, textStatus, errorThrown) {
  34. api.onError('Server error or API not found.', params, errorThrown);
  35. }
  36. $.ajax({
  37. type: 'POST',
  38. url: api.path,
  39. data: params,
  40. dataType: 'text',
  41. success,
  42. error
  43. });
  44. }