api.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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==='true') data = true
  21. else if (data==='false') 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. callback(data)
  27. }
  28. const error = (jqXHR, textStatus, errorThrown) => {
  29. api.onError('Server error or API not found.', params, errorThrown)
  30. }
  31. $.ajax({
  32. type: 'POST',
  33. url: api.path,
  34. data: params,
  35. dataType: 'text',
  36. success,
  37. error
  38. })
  39. }