api.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. }
  8. api.post = function(fn, params, callback) {
  9. var success,
  10. error;
  11. loadingBar.show();
  12. params = $.extend({function: fn}, params);
  13. success = function(data) {
  14. setTimeout(function() { loadingBar.hide() }, 100);
  15. // Catch errors
  16. if (typeof data==='string'&&
  17. data.substring(0, 7)==='Error: ') {
  18. lychee.error(data.substring(7, data.length), params, data);
  19. return false;
  20. }
  21. // Convert 1 to true and an empty string to false
  22. if (data==='1') data = true;
  23. else if (data==='') data = false;
  24. // Convert to JSON if string start with '{' and ends with '}'
  25. if (typeof data==='string'&&
  26. data.substring(0, 1)==='{'&&
  27. data.substring(data.length-1, data.length)==='}') data = $.parseJSON(data);
  28. // Output response when debug mode is enabled
  29. if (lychee.debugMode) console.log(data);
  30. callback(data);
  31. }
  32. error = function(jqXHR, textStatus, errorThrown) {
  33. lychee.error('Server error or API not found.', params, errorThrown);
  34. }
  35. $.ajax({
  36. type: 'POST',
  37. url: api.path,
  38. data: params,
  39. dataType: 'text',
  40. success,
  41. error
  42. });
  43. }