api.js 1.2 KB

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