.. include:: ../Includes.txt .. _examples_legacy: ============ Basic requests ============ .. warning:: | This example uses an JavaScript with a very "old" way of creating and sending XHR-requests. | You will only need this, if you are still forced to optimize for **Internet Explorer 11 and below**. For a more modern approach we would recommend using the promise-based :ref:`fetch() ` or a library that saves a lot of headaches like :ref:`Axios ` How to make a request with pure JavaScript (no libraries) that supports older browsers (like Internet Explorer 11 and below). ------------ .. tip:: | **Want to play, not read?** | Here is a ready-to-go codepen that demonstrates how to use VanillaJS to make requests. Run and have fun! | `nnrestapi vanillajs demo `__ Sending a simple request (for older browsers) ~~~~~~~~~~~~ If you can drop support for IE11 and below, the easiest way to send a request is using the promise-based ``fetch()`` command that comes with ES6+. Let's create a ``GET`` request to the nnrestapi backend: .. code-block:: javascript // By default this will be routed to Index->getIndexAction() var url = 'https://www.mywebsite.com/api/index'; var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = function () { var data = JSON.parse( xhr.responseText ); if (xhr.status != 200) { alert("Error " + xhr.status + ": " + data.error ); return false; } console.log( data ); }; xhr.onerror = function () { alert('Some other error... probably wrong url?'); }; xhr.send(); Of course you can also send a payload / JSON data using a ``POST``, ``PUT`` or ``PATCH`` request: .. code-block:: javascript // By default this will be routed to Index->postIndexAction() var url = 'https://www.mywebsite.com/api/index'; var json = { title: 'My Title', text: 'And some text' }; var xhr = new XMLHttpRequest(); xhr.overrideMimeType('application/json'); xhr.open('POST', url); xhr.onload = function () { var data = JSON.parse( xhr.responseText ); if (xhr.status != 200) { alert("Error " + xhr.status + ": " + data.error ); return false; } console.log( data ); }; xhr.onerror = function () { alert('Some other error... probably wrong url?'); }; xhr.send(JSON.stringify(json)); VanillaJS Starter Template ~~~~~~~~~~~~ Here is a full example you can copy and paste to get you started. You can also test and play with it on `this codepen `__ .. code-block:: html nnrestapi VanillaJS Demo
Result