ajax.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. /* vim: set expandtab sw=4 ts=4 sts=4: */
  2. /**
  3. * This object handles ajax requests for pages. It also
  4. * handles the reloading of the main menu and scripts.
  5. */
  6. var AJAX = {
  7. /**
  8. * @var bool active Whether we are busy
  9. */
  10. active: false,
  11. /**
  12. * @var object source The object whose event initialized the request
  13. */
  14. source: null,
  15. /**
  16. * @var object xhr A reference to the ajax request that is currently running
  17. */
  18. xhr: null,
  19. /**
  20. * @var object lockedTargets, list of locked targets
  21. */
  22. lockedTargets: {},
  23. /**
  24. * @var function Callback to execute after a successful request
  25. * Used by PMA_commonFunctions from common.js
  26. */
  27. _callback: function () {},
  28. /**
  29. * @var bool _debug Makes noise in your Firebug console
  30. */
  31. _debug: false,
  32. /**
  33. * @var object $msgbox A reference to a jQuery object that links to a message
  34. * box that is generated by PMA_ajaxShowMessage()
  35. */
  36. $msgbox: null,
  37. /**
  38. * Given the filename of a script, returns a hash to be
  39. * used to refer to all the events registered for the file
  40. *
  41. * @param key string key The filename for which to get the event name
  42. *
  43. * @return int
  44. */
  45. hash: function (key) {
  46. /* http://burtleburtle.net/bob/hash/doobs.html#one */
  47. key += '';
  48. var len = key.length;
  49. var hash = 0;
  50. var i = 0;
  51. for (; i < len; ++i) {
  52. hash += key.charCodeAt(i);
  53. hash += (hash << 10);
  54. hash ^= (hash >> 6);
  55. }
  56. hash += (hash << 3);
  57. hash ^= (hash >> 11);
  58. hash += (hash << 15);
  59. return Math.abs(hash);
  60. },
  61. /**
  62. * Registers an onload event for a file
  63. *
  64. * @param file string file The filename for which to register the event
  65. * @param func function func The function to execute when the page is ready
  66. *
  67. * @return self For chaining
  68. */
  69. registerOnload: function (file, func) {
  70. var eventName = 'onload_' + AJAX.hash(file);
  71. $(document).on(eventName, func);
  72. if (this._debug) {
  73. console.log(
  74. // no need to translate
  75. 'Registered event ' + eventName + ' for file ' + file
  76. );
  77. }
  78. return this;
  79. },
  80. /**
  81. * Registers a teardown event for a file. This is useful to execute functions
  82. * that unbind events for page elements that are about to be removed.
  83. *
  84. * @param string file The filename for which to register the event
  85. * @param function func The function to execute when
  86. * the page is about to be torn down
  87. *
  88. * @return self For chaining
  89. */
  90. registerTeardown: function (file, func) {
  91. var eventName = 'teardown_' + AJAX.hash(file);
  92. $(document).on(eventName, func);
  93. if (this._debug) {
  94. console.log(
  95. // no need to translate
  96. 'Registered event ' + eventName + ' for file ' + file
  97. );
  98. }
  99. return this;
  100. },
  101. /**
  102. * Called when a page has finished loading, once for every
  103. * file that registered to the onload event of that file.
  104. *
  105. * @param string file The filename for which to fire the event
  106. *
  107. * @return void
  108. */
  109. fireOnload: function (file) {
  110. var eventName = 'onload_' + AJAX.hash(file);
  111. $(document).trigger(eventName);
  112. if (this._debug) {
  113. console.log(
  114. // no need to translate
  115. 'Fired event ' + eventName + ' for file ' + file
  116. );
  117. }
  118. },
  119. /**
  120. * Called just before a page is torn down, once for every
  121. * file that registered to the teardown event of that file.
  122. *
  123. * @param string file The filename for which to fire the event
  124. *
  125. * @return void
  126. */
  127. fireTeardown: function (file) {
  128. var eventName = 'teardown_' + AJAX.hash(file);
  129. $(document).triggerHandler(eventName);
  130. if (this._debug) {
  131. console.log(
  132. // no need to translate
  133. 'Fired event ' + eventName + ' for file ' + file
  134. );
  135. }
  136. },
  137. /**
  138. * function to handle lock page mechanism
  139. *
  140. * @param event the event object
  141. *
  142. * @return void
  143. */
  144. lockPageHandler: function (event) {
  145. var newHash = null;
  146. var oldHash = null;
  147. var lockId;
  148. // CodeMirror lock
  149. if (event.data.value === 3) {
  150. newHash = event.data.content;
  151. oldHash = true;
  152. lockId = 'cm';
  153. } else {
  154. // Don't lock on enter.
  155. if (0 === event.charCode) {
  156. return;
  157. }
  158. lockId = $(this).data('lock-id');
  159. if (typeof lockId === 'undefined') {
  160. return;
  161. }
  162. /*
  163. * @todo Fix Code mirror does not give correct full value (query)
  164. * in textarea, it returns only the change in content.
  165. */
  166. if (event.data.value === 1) {
  167. newHash = AJAX.hash($(this).val());
  168. } else {
  169. newHash = AJAX.hash($(this).is(':checked'));
  170. }
  171. oldHash = $(this).data('val-hash');
  172. }
  173. // Set lock if old value !== new value
  174. // otherwise release lock
  175. if (oldHash !== newHash) {
  176. AJAX.lockedTargets[lockId] = true;
  177. } else {
  178. delete AJAX.lockedTargets[lockId];
  179. }
  180. // Show lock icon if locked targets is not empty.
  181. // otherwise remove lock icon
  182. if (!jQuery.isEmptyObject(AJAX.lockedTargets)) {
  183. $('#lock_page_icon').html(PMA_getImage('s_lock', PMA_messages.strLockToolTip).toString());
  184. } else {
  185. $('#lock_page_icon').html('');
  186. }
  187. },
  188. /**
  189. * resets the lock
  190. *
  191. * @return void
  192. */
  193. resetLock: function () {
  194. AJAX.lockedTargets = {};
  195. $('#lock_page_icon').html('');
  196. },
  197. handleMenu: {
  198. replace: function (content) {
  199. $('#floating_menubar').html(content)
  200. // Remove duplicate wrapper
  201. // TODO: don't send it in the response
  202. .children().first().remove();
  203. $('#topmenu').menuResizer(PMA_mainMenuResizerCallback);
  204. }
  205. },
  206. /**
  207. * Event handler for clicks on links and form submissions
  208. *
  209. * @param object e Event data
  210. *
  211. * @return void
  212. */
  213. requestHandler: function (event) {
  214. // In some cases we don't want to handle the request here and either
  215. // leave the browser deal with it natively (e.g: file download)
  216. // or leave an existing ajax event handler present elsewhere deal with it
  217. var href = $(this).attr('href');
  218. if (typeof event !== 'undefined' && (event.shiftKey || event.ctrlKey)) {
  219. return true;
  220. } else if ($(this).attr('target')) {
  221. return true;
  222. } else if ($(this).hasClass('ajax') || $(this).hasClass('disableAjax')) {
  223. // reset the lockedTargets object, as specified AJAX operation has finished
  224. AJAX.resetLock();
  225. return true;
  226. } else if (href && href.match(/^#/)) {
  227. return true;
  228. } else if (href && href.match(/^mailto/)) {
  229. return true;
  230. } else if ($(this).hasClass('ui-datepicker-next') ||
  231. $(this).hasClass('ui-datepicker-prev')
  232. ) {
  233. return true;
  234. }
  235. if (typeof event !== 'undefined') {
  236. event.preventDefault();
  237. event.stopImmediatePropagation();
  238. }
  239. // triggers a confirm dialog if:
  240. // the user has performed some operations on loaded page
  241. // the user clicks on some link, (won't trigger for buttons)
  242. // the click event is not triggered by script
  243. if (typeof event !== 'undefined' && event.type === 'click' &&
  244. event.isTrigger !== true &&
  245. !jQuery.isEmptyObject(AJAX.lockedTargets) &&
  246. confirm(PMA_messages.strConfirmNavigation) === false
  247. ) {
  248. return false;
  249. }
  250. AJAX.resetLock();
  251. var isLink = !! href || false;
  252. var previousLinkAborted = false;
  253. if (AJAX.active === true) {
  254. // Cancel the old request if abortable, when the user requests
  255. // something else. Otherwise silently bail out, as there is already
  256. // a request well in progress.
  257. if (AJAX.xhr) {
  258. // In case of a link request, attempt aborting
  259. AJAX.xhr.abort();
  260. if (AJAX.xhr.status === 0 && AJAX.xhr.statusText === 'abort') {
  261. // If aborted
  262. AJAX.$msgbox = PMA_ajaxShowMessage(PMA_messages.strAbortedRequest);
  263. AJAX.active = false;
  264. AJAX.xhr = null;
  265. previousLinkAborted = true;
  266. } else {
  267. // If can't abort
  268. return false;
  269. }
  270. } else {
  271. // In case submitting a form, don't attempt aborting
  272. return false;
  273. }
  274. }
  275. AJAX.source = $(this);
  276. $('html, body').animate({ scrollTop: 0 }, 'fast');
  277. var url = isLink ? href : $(this).attr('action');
  278. var argsep = PMA_commonParams.get('arg_separator');
  279. var params = 'ajax_request=true' + argsep + 'ajax_page_request=true';
  280. var dataPost = AJAX.source.getPostData();
  281. if (! isLink) {
  282. params += argsep + $(this).serialize();
  283. } else if (dataPost) {
  284. params += argsep + dataPost;
  285. isLink = false;
  286. }
  287. if (! (history && history.pushState)) {
  288. // Add a list of menu hashes that we have in the cache to the request
  289. params += PMA_MicroHistory.menus.getRequestParam();
  290. }
  291. if (AJAX._debug) {
  292. console.log('Loading: ' + url); // no need to translate
  293. }
  294. if (isLink) {
  295. AJAX.active = true;
  296. AJAX.$msgbox = PMA_ajaxShowMessage();
  297. // Save reference for the new link request
  298. AJAX.xhr = $.get(url, params, AJAX.responseHandler);
  299. if (history && history.pushState) {
  300. var state = {
  301. url : href
  302. };
  303. if (previousLinkAborted) {
  304. // hack: there is already an aborted entry on stack
  305. // so just modify the aborted one
  306. history.replaceState(state, null, href);
  307. } else {
  308. history.pushState(state, null, href);
  309. }
  310. }
  311. } else {
  312. /**
  313. * Manually fire the onsubmit event for the form, if any.
  314. * The event was saved in the jQuery data object by an onload
  315. * handler defined below. Workaround for bug #3583316
  316. */
  317. var onsubmit = $(this).data('onsubmit');
  318. // Submit the request if there is no onsubmit handler
  319. // or if it returns a value that evaluates to true
  320. if (typeof onsubmit !== 'function' || onsubmit.apply(this, [event])) {
  321. AJAX.active = true;
  322. AJAX.$msgbox = PMA_ajaxShowMessage();
  323. $.post(url, params, AJAX.responseHandler);
  324. }
  325. }
  326. },
  327. /**
  328. * Called after the request that was initiated by this.requestHandler()
  329. * has completed successfully or with a caught error. For completely
  330. * failed requests or requests with uncaught errors, see the .ajaxError
  331. * handler at the bottom of this file.
  332. *
  333. * To refer to self use 'AJAX', instead of 'this' as this function
  334. * is called in the jQuery context.
  335. *
  336. * @param object e Event data
  337. *
  338. * @return void
  339. */
  340. responseHandler: function (data) {
  341. if (typeof data === 'undefined' || data === null) {
  342. return;
  343. }
  344. if (typeof data.success !== 'undefined' && data.success) {
  345. $('html, body').animate({ scrollTop: 0 }, 'fast');
  346. PMA_ajaxRemoveMessage(AJAX.$msgbox);
  347. if (data._redirect) {
  348. PMA_ajaxShowMessage(data._redirect, false);
  349. AJAX.active = false;
  350. AJAX.xhr = null;
  351. return;
  352. }
  353. AJAX.scriptHandler.reset(function () {
  354. if (data._reloadNavigation) {
  355. PMA_reloadNavigation();
  356. }
  357. if (data._title) {
  358. $('title').replaceWith(data._title);
  359. }
  360. if (data._menu) {
  361. if (history && history.pushState) {
  362. var state = {
  363. url : data._selflink,
  364. menu : data._menu
  365. };
  366. history.replaceState(state, null);
  367. AJAX.handleMenu.replace(data._menu);
  368. } else {
  369. PMA_MicroHistory.menus.replace(data._menu);
  370. PMA_MicroHistory.menus.add(data._menuHash, data._menu);
  371. }
  372. } else if (data._menuHash) {
  373. if (! (history && history.pushState)) {
  374. PMA_MicroHistory.menus.replace(PMA_MicroHistory.menus.get(data._menuHash));
  375. }
  376. }
  377. if (data._disableNaviSettings) {
  378. PMA_disableNaviSettings();
  379. } else {
  380. PMA_ensureNaviSettings(data._selflink);
  381. }
  382. // Remove all containers that may have
  383. // been added outside of #page_content
  384. $('body').children()
  385. .not('#pma_navigation')
  386. .not('#floating_menubar')
  387. .not('#page_nav_icons')
  388. .not('#page_content')
  389. .not('#selflink')
  390. .not('#pma_header')
  391. .not('#pma_footer')
  392. .not('#pma_demo')
  393. .not('#pma_console_container')
  394. .not('#prefs_autoload')
  395. .remove();
  396. // Replace #page_content with new content
  397. if (data.message && data.message.length > 0) {
  398. $('#page_content').replaceWith(
  399. '<div id=\'page_content\'>' + data.message + '</div>'
  400. );
  401. PMA_highlightSQL($('#page_content'));
  402. checkNumberOfFields();
  403. }
  404. if (data._selflink) {
  405. var source = data._selflink.split('?')[0];
  406. // Check for faulty links
  407. $selflink_replace = {
  408. 'import.php': 'tbl_sql.php',
  409. 'tbl_chart.php': 'sql.php',
  410. 'tbl_gis_visualization.php': 'sql.php'
  411. };
  412. if ($selflink_replace[source]) {
  413. var replacement = $selflink_replace[source];
  414. data._selflink = data._selflink.replace(source, replacement);
  415. }
  416. $('#selflink').find('> a').attr('href', data._selflink);
  417. }
  418. if (data._params) {
  419. PMA_commonParams.setAll(data._params);
  420. }
  421. if (data._scripts) {
  422. AJAX.scriptHandler.load(data._scripts);
  423. }
  424. if (data._selflink && data._scripts && data._menuHash && data._params) {
  425. if (! (history && history.pushState)) {
  426. PMA_MicroHistory.add(
  427. data._selflink,
  428. data._scripts,
  429. data._menuHash,
  430. data._params,
  431. AJAX.source.attr('rel')
  432. );
  433. }
  434. }
  435. if (data._displayMessage) {
  436. $('#page_content').prepend(data._displayMessage);
  437. PMA_highlightSQL($('#page_content'));
  438. }
  439. $('#pma_errors').remove();
  440. var msg = '';
  441. if (data._errSubmitMsg) {
  442. msg = data._errSubmitMsg;
  443. }
  444. if (data._errors) {
  445. $('<div/>', { id : 'pma_errors', class : 'clearfloat' })
  446. .insertAfter('#selflink')
  447. .append(data._errors);
  448. // bind for php error reporting forms (bottom)
  449. $('#pma_ignore_errors_bottom').on('click', function (e) {
  450. e.preventDefault();
  451. PMA_ignorePhpErrors();
  452. });
  453. $('#pma_ignore_all_errors_bottom').on('click', function (e) {
  454. e.preventDefault();
  455. PMA_ignorePhpErrors(false);
  456. });
  457. // In case of 'sendErrorReport'='always'
  458. // submit the hidden error reporting form.
  459. if (data._sendErrorAlways === '1' &&
  460. data._stopErrorReportLoop !== '1'
  461. ) {
  462. $('#pma_report_errors_form').submit();
  463. PMA_ajaxShowMessage(PMA_messages.phpErrorsBeingSubmitted, false);
  464. $('html, body').animate({ scrollTop:$(document).height() }, 'slow');
  465. } else if (data._promptPhpErrors) {
  466. // otherwise just prompt user if it is set so.
  467. msg = msg + PMA_messages.phpErrorsFound;
  468. // scroll to bottom where all the errors are displayed.
  469. $('html, body').animate({ scrollTop:$(document).height() }, 'slow');
  470. }
  471. }
  472. PMA_ajaxShowMessage(msg, false);
  473. // bind for php error reporting forms (popup)
  474. $('#pma_ignore_errors_popup').on('click', function () {
  475. PMA_ignorePhpErrors();
  476. });
  477. $('#pma_ignore_all_errors_popup').on('click', function () {
  478. PMA_ignorePhpErrors(false);
  479. });
  480. if (typeof AJAX._callback === 'function') {
  481. AJAX._callback.call();
  482. }
  483. AJAX._callback = function () {};
  484. });
  485. } else {
  486. PMA_ajaxShowMessage(data.error, false);
  487. AJAX.active = false;
  488. AJAX.xhr = null;
  489. PMA_handleRedirectAndReload(data);
  490. if (data.fieldWithError) {
  491. $(':input.error').removeClass('error');
  492. $('#' + data.fieldWithError).addClass('error');
  493. }
  494. }
  495. },
  496. /**
  497. * This object is in charge of downloading scripts,
  498. * keeping track of what's downloaded and firing
  499. * the onload event for them when the page is ready.
  500. */
  501. scriptHandler: {
  502. /**
  503. * @var array _scripts The list of files already downloaded
  504. */
  505. _scripts: [],
  506. /**
  507. * @var string _scriptsVersion version of phpMyAdmin from which the
  508. * scripts have been loaded
  509. */
  510. _scriptsVersion: null,
  511. /**
  512. * @var array _scriptsToBeLoaded The list of files that
  513. * need to be downloaded
  514. */
  515. _scriptsToBeLoaded: [],
  516. /**
  517. * @var array _scriptsToBeFired The list of files for which
  518. * to fire the onload and unload events
  519. */
  520. _scriptsToBeFired: [],
  521. _scriptsCompleted: false,
  522. /**
  523. * Records that a file has been downloaded
  524. *
  525. * @param string file The filename
  526. * @param string fire Whether this file will be registering
  527. * onload/teardown events
  528. *
  529. * @return self For chaining
  530. */
  531. add: function (file, fire) {
  532. this._scripts.push(file);
  533. if (fire) {
  534. // Record whether to fire any events for the file
  535. // This is necessary to correctly tear down the initial page
  536. this._scriptsToBeFired.push(file);
  537. }
  538. return this;
  539. },
  540. /**
  541. * Download a list of js files in one request
  542. *
  543. * @param array files An array of filenames and flags
  544. *
  545. * @return void
  546. */
  547. load: function (files, callback) {
  548. var self = this;
  549. var i;
  550. // Clear loaded scripts if they are from another version of phpMyAdmin.
  551. // Depends on common params being set before loading scripts in responseHandler
  552. if (self._scriptsVersion === null) {
  553. self._scriptsVersion = PMA_commonParams.get('PMA_VERSION');
  554. } else if (self._scriptsVersion !== PMA_commonParams.get('PMA_VERSION')) {
  555. self._scripts = [];
  556. self._scriptsVersion = PMA_commonParams.get('PMA_VERSION');
  557. }
  558. self._scriptsCompleted = false;
  559. self._scriptsToBeFired = [];
  560. // We need to first complete list of files to load
  561. // as next loop will directly fire requests to load them
  562. // and that triggers removal of them from
  563. // self._scriptsToBeLoaded
  564. for (i in files) {
  565. self._scriptsToBeLoaded.push(files[i].name);
  566. if (files[i].fire) {
  567. self._scriptsToBeFired.push(files[i].name);
  568. }
  569. }
  570. for (i in files) {
  571. var script = files[i].name;
  572. // Only for scripts that we don't already have
  573. if ($.inArray(script, self._scripts) === -1) {
  574. this.add(script);
  575. this.appendScript(script, callback);
  576. } else {
  577. self.done(script, callback);
  578. }
  579. }
  580. // Trigger callback if there is nothing else to load
  581. self.done(null, callback);
  582. },
  583. /**
  584. * Called whenever all files are loaded
  585. *
  586. * @return void
  587. */
  588. done: function (script, callback) {
  589. if (typeof ErrorReport !== 'undefined') {
  590. ErrorReport.wrap_global_functions();
  591. }
  592. if ($.inArray(script, this._scriptsToBeFired)) {
  593. AJAX.fireOnload(script);
  594. }
  595. if ($.inArray(script, this._scriptsToBeLoaded)) {
  596. this._scriptsToBeLoaded.splice($.inArray(script, this._scriptsToBeLoaded), 1);
  597. }
  598. if (script === null) {
  599. this._scriptsCompleted = true;
  600. }
  601. /* We need to wait for last signal (with null) or last script load */
  602. AJAX.active = (this._scriptsToBeLoaded.length > 0) || ! this._scriptsCompleted;
  603. /* Run callback on last script */
  604. if (! AJAX.active && $.isFunction(callback)) {
  605. callback();
  606. }
  607. },
  608. /**
  609. * Appends a script element to the head to load the scripts
  610. *
  611. * @return void
  612. */
  613. appendScript: function (name, callback) {
  614. var head = document.head || document.getElementsByTagName('head')[0];
  615. var script = document.createElement('script');
  616. var self = this;
  617. script.type = 'text/javascript';
  618. script.src = 'js/' + name + '?' + 'v=' + encodeURIComponent(PMA_commonParams.get('PMA_VERSION'));
  619. script.async = false;
  620. script.onload = function () {
  621. self.done(name, callback);
  622. };
  623. head.appendChild(script);
  624. },
  625. /**
  626. * Fires all the teardown event handlers for the current page
  627. * and rebinds all forms and links to the request handler
  628. *
  629. * @param function callback The callback to call after resetting
  630. *
  631. * @return void
  632. */
  633. reset: function (callback) {
  634. for (var i in this._scriptsToBeFired) {
  635. AJAX.fireTeardown(this._scriptsToBeFired[i]);
  636. }
  637. this._scriptsToBeFired = [];
  638. /**
  639. * Re-attach a generic event handler to clicks
  640. * on pages and submissions of forms
  641. */
  642. $(document).off('click', 'a').on('click', 'a', AJAX.requestHandler);
  643. $(document).off('submit', 'form').on('submit', 'form', AJAX.requestHandler);
  644. if (! (history && history.pushState)) {
  645. PMA_MicroHistory.update();
  646. }
  647. callback();
  648. }
  649. }
  650. };
  651. /**
  652. * Here we register a function that will remove the onsubmit event from all
  653. * forms that will be handled by the generic page loader. We then save this
  654. * event handler in the "jQuery data", so that we can fire it up later in
  655. * AJAX.requestHandler().
  656. *
  657. * See bug #3583316
  658. */
  659. AJAX.registerOnload('functions.js', function () {
  660. // Registering the onload event for functions.js
  661. // ensures that it will be fired for all pages
  662. $('form').not('.ajax').not('.disableAjax').each(function () {
  663. if ($(this).attr('onsubmit')) {
  664. $(this).data('onsubmit', this.onsubmit).attr('onsubmit', '');
  665. }
  666. });
  667. var $page_content = $('#page_content');
  668. /**
  669. * Workaround for passing submit button name,value on ajax form submit
  670. * by appending hidden element with submit button name and value.
  671. */
  672. $page_content.on('click', 'form input[type=submit]', function () {
  673. var buttonName = $(this).attr('name');
  674. if (typeof buttonName === 'undefined') {
  675. return;
  676. }
  677. $(this).closest('form').append($('<input/>', {
  678. 'type' : 'hidden',
  679. 'name' : buttonName,
  680. 'value': $(this).val()
  681. }));
  682. });
  683. /**
  684. * Attach event listener to events when user modify visible
  685. * Input,Textarea and select fields to make changes in forms
  686. */
  687. $page_content.on(
  688. 'keyup change',
  689. 'form.lock-page textarea, ' +
  690. 'form.lock-page input[type="text"], ' +
  691. 'form.lock-page input[type="number"], ' +
  692. 'form.lock-page select',
  693. { value:1 },
  694. AJAX.lockPageHandler
  695. );
  696. $page_content.on(
  697. 'change',
  698. 'form.lock-page input[type="checkbox"], ' +
  699. 'form.lock-page input[type="radio"]',
  700. { value:2 },
  701. AJAX.lockPageHandler
  702. );
  703. /**
  704. * Reset lock when lock-page form reset event is fired
  705. * Note: reset does not bubble in all browser so attach to
  706. * form directly.
  707. */
  708. $('form.lock-page').on('reset', function (event) {
  709. AJAX.resetLock();
  710. });
  711. });
  712. /**
  713. * Page load event handler
  714. */
  715. $(function () {
  716. var menuContent = $('<div></div>')
  717. .append($('#serverinfo').clone())
  718. .append($('#topmenucontainer').clone())
  719. .html();
  720. if (history && history.pushState) {
  721. // set initial state reload
  722. var initState = ('state' in window.history && window.history.state !== null);
  723. var initURL = $('#selflink').find('> a').attr('href') || location.href;
  724. var state = {
  725. url : initURL,
  726. menu : menuContent
  727. };
  728. history.replaceState(state, null);
  729. $(window).on('popstate', function (event) {
  730. var initPop = (! initState && location.href === initURL);
  731. initState = true;
  732. // check if popstate fired on first page itself
  733. if (initPop) {
  734. return;
  735. }
  736. var state = event.originalEvent.state;
  737. if (state && state.menu) {
  738. AJAX.$msgbox = PMA_ajaxShowMessage();
  739. var params = 'ajax_request=true' + PMA_commonParams.get('arg_separator') + 'ajax_page_request=true';
  740. var url = state.url || location.href;
  741. $.get(url, params, AJAX.responseHandler);
  742. // TODO: Check if sometimes menu is not retrieved from server,
  743. // Not sure but it seems menu was missing only for printview which
  744. // been removed lately, so if it's right some dead menu checks/fallbacks
  745. // may need to be removed from this file and Header.php
  746. // AJAX.handleMenu.replace(event.originalEvent.state.menu);
  747. }
  748. });
  749. } else {
  750. // Fallback to microhistory mechanism
  751. AJAX.scriptHandler
  752. .load([{ 'name' : 'microhistory.js', 'fire' : 1 }], function () {
  753. // The cache primer is set by the footer class
  754. if (PMA_MicroHistory.primer.url) {
  755. PMA_MicroHistory.menus.add(
  756. PMA_MicroHistory.primer.menuHash,
  757. menuContent
  758. );
  759. }
  760. $(function () {
  761. // Queue up this event twice to make sure that we get a copy
  762. // of the page after all other onload events have been fired
  763. if (PMA_MicroHistory.primer.url) {
  764. PMA_MicroHistory.add(
  765. PMA_MicroHistory.primer.url,
  766. PMA_MicroHistory.primer.scripts,
  767. PMA_MicroHistory.primer.menuHash
  768. );
  769. }
  770. });
  771. });
  772. }
  773. });
  774. /**
  775. * Attach a generic event handler to clicks
  776. * on pages and submissions of forms
  777. */
  778. $(document).on('click', 'a', AJAX.requestHandler);
  779. $(document).on('submit', 'form', AJAX.requestHandler);
  780. /**
  781. * Gracefully handle fatal server errors
  782. * (e.g: 500 - Internal server error)
  783. */
  784. $(document).ajaxError(function (event, request, settings) {
  785. if (AJAX._debug) {
  786. console.log('AJAX error: status=' + request.status + ', text=' + request.statusText);
  787. }
  788. // Don't handle aborted requests
  789. if (request.status !== 0 || request.statusText !== 'abort') {
  790. var details = '';
  791. var state = request.state();
  792. if (request.status !== 0) {
  793. details += '<div>' + escapeHtml(PMA_sprintf(PMA_messages.strErrorCode, request.status)) + '</div>';
  794. }
  795. details += '<div>' + escapeHtml(PMA_sprintf(PMA_messages.strErrorText, request.statusText + ' (' + state + ')')) + '</div>';
  796. if (state === 'rejected' || state === 'timeout') {
  797. details += '<div>' + escapeHtml(PMA_messages.strErrorConnection) + '</div>';
  798. }
  799. PMA_ajaxShowMessage(
  800. '<div class="error">' +
  801. PMA_messages.strErrorProcessingRequest +
  802. details +
  803. '</div>',
  804. false
  805. );
  806. AJAX.active = false;
  807. AJAX.xhr = null;
  808. }
  809. });