.. include:: ../Includes.txt .. _examples_jquery_basic: ============ Basic requests ============ Simple requests without authentication using jQuery ------------ .. tip:: | **Want to play, not read?** | Here is a ready-to-go codepen that demonstrates how to use jQuery to connect to an endpoint. Run and have fun! | `nnrestapi jQuery demo `__ .. important:: | **Don't forget the @Api\Access!** | All exemples on this page will only work, if the methods have ``@Api\Access("public")`` set in the annotation. | If you need to find out, how to do that please refer to :ref:`this section ` or find out, how to create request with authentication in :ref:`this section ` Sending a GET-Request ~~~~~~~~~~~~ A very basic example of how to send a ``GET`` request using jQuery's `$.get() `__ command. .. code-block:: javascript // By default this will be routed to Index->getIndexAction() const url = 'https://www.mywebsite.com/api/index'; $.get(url).done((result) => { alert( result.message ); }).fail((error) => { alert( `Error ${error.status}: ${error.responseJSON.error}` ); }); Sending a POST-Request ~~~~~~~~~~~~ Here is a example of how to send a ``POST`` request using jQuery's `$.post() `__ command. Note that the object-data is converted to a JSON-string using `JSON.stringify() `__. This makes sure the data can be parsed by the backend. .. code-block:: javascript // By default this will be routed to Index->postIndexAction() const url = 'https://www.mywebsite.com/api/index'; const data = {title:'Test'}; const jsonData = JSON.stringify(data); $.post(url, jsonData).done((result) => { console.log( result ); }).fail((error) => { alert( `Error ${error.status}: ${error.responseJSON.error}` ); }); Sending a PUT, PATCH or DELETE request ~~~~~~~~~~~~ If you would like to send a ``PUT``, ``PATCH`` or ``DELETE`` request, you will need to use jQuery's `$.ajax() `__ method with the appropriate ``type`` in the request settings. .. code-block:: javascript // By default this will be routed to Index->putIndexAction() const url = 'https://www.mywebsite.com/api/index'; const data = {title:'Test'}; const jsonData = JSON.stringify(data); $.ajax({ url: url, type: 'PUT', // 'PATCH' or 'DELETE' data: jsonData }).done((result) => { console.log( result ); }).fail((error) => { alert( `Error ${error.status}: ${error.responseJSON.error}` ); }); jQuery 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 jQuery Demo