← Back to the notebook

· 3 min read

Easy JSONP web services and AJAX iframe in CodeIgniter

JSONP and iframe file upload techniques, plus the Spark/ajax library for generating responses in CodeIgniter.

#php#codeigniter#javascript#ajax

Episode rescued from the SeViR Notes archive and translated from Spanish. Originally published on January 8, 2015.

Although this goes back quite a while, it’s still very useful. It has become the norm for web applications to be full of AJAX queries and requests: a template is loaded first, and the content is then updated through asynchronous queries or requests.

When we want to upload files in the background without reloading the page, however, we can’t use AJAX. We either have to turn to the HTML5 File API or find an alternative technique that lets us submit a multipart form in the background. This can be done with iframes. The technique is based on creating an invisible iframe (invisible, not hidden: if it’s set to display:hidden it won’t work). With a size of 0 pixels and no borders we get a working iframe that the user can’t see. If we set this iframe as the target of a multipart form, we can upload a file without reloading the page.

The problem then is knowing when the file has finished uploading. For that, the response loaded into the iframe must call a JavaScript function defined in the parent window, which runs like a callback once the file has been uploaded.

Being able to fetch data in JavaScript across different domains makes it easy to build web services in JSON format. This technique is called JSONP, and it consists of returning not a JavaScript object, but a call to a function with whatever name we choose (the callback function), passing that object as its parameter. When we load a URL that calls the service, it triggers the callback function with the data we expect as the response. jQuery already does this behind the scenes when we call $.getScript, generating a function with a random name.

For all of this there’s a library that helps us generate responses in JSON, JSONP and XML, as well as responses through iframes. If you use CodeIgniter 2 or later, Spark/ajax gives you a set of helper functions and handy methods to generate valid JSONP responses, send responses inside an iframe, or return XML.

With a single method, $this->ajax->response(), we can generate responses to be sent as JSON or JSONP, extend a JS object with jQuery, assign the generated data to a variable, or produce XML responses from a PHP object.

For example, say we want to load the translation strings from a PHP array into a JavaScript variable. We could add a script tag to the HTML

<script type="text/javascript" src="http://url/controller/method">

and have that PHP method return the data in a variable:

$this->ajax->response($array_traduccion, null, TRUE, "varjs");

This loads the data into varjs so it can be used from JavaScript. It would also work from any domain, so it’s cross-domain.