Errors when downloading a file on page submit in Oracle Application Express 5.1 or later…
Error: SyntaxError: Unexpected token < in JSON at position 0
Recently, Sharon Kennedy from our team approached me for some help with file download in Oracle Application Express (APEX). Sharon is the primary developer of Oracle Live SQL (among many of her other responsibilities), and she wanted to initiate a file download in a page process, after page submission. Since I’ve done this 100 times in APEX applications, should be easy, right?
Back in 2014, I wrote a short blog post showing how to generate a link to download a file from a BLOB stored in a table. But this problem was slightly different. The application flow was:
- In Oracle Live SQL Administration, an administrator would click the button “Download Oracle Content”
- The page would then be submitted, and a PL/SQL page process would fire, which would query all of the static scripts and tutorials from Live SQL, zip them up using APEX_ZIP, and initiate a file download.
However, when the button was clicked, the page would be submitted, no file download would be initiated, and the following error was displayed on the page:
After spending more than an hour debugging the Live SQL application, I resorted to a simpler test case. I created a trivial application with a button on the first page, which would submit and invoke the PL/SQL page process:
With my test case, it was exactly the same error encountered, the meaningless error message of “Error: SyntaxError: Unexpected token r in JSON at position 0”.
I finally gave up and contacted Patrick Wolf on the APEX product development team, who helped me solve this problem in one minute. Granted…Patrick was both the creator of the problem and the creator of the solution!
To resolve this problem:
- Open the page in Page Designer in Application Builder
- Edit the page attributes
- In the Advanced section of the page properties on the right hand side of Page Designer, change “Reload on Submit” to “Always” (changing it from “Only for Success” to “Always”)
Setting “Reload on Submit” to “Always” will POST the page and render the result using the behavior as it was in APEX 5.0 and earlier. In APEX 5.1, if Reload on Submit is set “Only for Success” (the default), it will use the new optimized page submission process, and expect a specifically formatted JSON result returned from the APEX engine. Obviously, when I employ a page process which overrides the HTP buffer and emit binary content (instead of a well-formed JSON result), the libraries on the page don’t know how to deal with that, and thus, results in this obtuse “Unexpected token r…” message.