2

I'd like to use the Element API plugin. I've follow the instructions mentioned here: ElementAPI - Can I use javascript/ajax to load json

Here is my config/elementapi.php file :

<?php
namespace Craft;

return [
    'endpoints' => [
        'news.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'news'],
            'transformer' => function (EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                    'jsonUrl' => UrlHelper::getUrl("news/{$entry->id}.json"),
                ];
            },
        ]
    ]
];

and here my ajax request:

    $(function () {
        var data = {
            'CSRF': $('input[name="CRAFT_CSRF_TOKEN"]').val(),
        };

        $.ajax({
            'type': 'post',
            'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
            'cache': false,
            'data': data,
            'url': 'news.json',
            'dataType': 'json',
            'timeout': 50000
        }).done(function (response) {
           console.log(response);
        }).fail(function (error) {
                console.log('totalfail')
            });
        });

But it always returns a 400 error (as the JSON file looks like it doesn't exist).

What have I missed? Could someone provide a working example?

Thanks!

9
  • Have you enabled ElementAPI plugin in the settings/plugin admin ui? May 30 '16 at 14:00
  • Yes I did. Also I'm running craft locally with Mamp. Don't know if that could cause any trouble... May 30 '16 at 15:00
  • Another dev is using Mamp and it runs fine. May 30 '16 at 15:11
  • I've just realized that I'm able to reach the json file by entering its url in the browser. My ajax function still returns a 400 error though... May 30 '16 at 15:34
  • Servers see Ajax requests almost identically to "regular" HTTP requests (they just come with 1 extra header) so I doubt it’s something server-side. Double-check that you're pointing the Ajax request to the right URL. May 30 '16 at 15:48
1

There was a mistake in the ajax request.
I was using POST instead of GET.

1) After installing the plugin :

Add elementapi.php to your /craft/config/ directory

<?php
namespace Craft;

return [
    'endpoints' => [
        'news.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'news'],
            'transformer' => function (EntryModel $entry) {
                return [
                    'title' => $entry->title,
                    'url' => $entry->url,
                    'jsonUrl' => UrlHelper::getUrl("news/{$entry->id}.json")
                ];
            },
        ]
    ]
];

2) Enabling CSRF Protection add 'enableCsrfProtection' => true to your /craft/config/general.php file.

3) getting entries with ajax :

_layout.html

<head>
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js">  </script>
<script>
    $(function () {
        var data = {
            'CSRF': $('input[name="CRAFT_CSRF_TOKEN"]').val(),
        };

        $.ajax({
            'type': 'get',
            'contentType': 'application/x-www-form-urlencoded; charset=UTF-8',
            'cache': false,
            'data': data,
            'url': 'news.json',
            'dataType': 'json',
            'timeout': 50000
        }).done(function (response) {
            console.log(response);
        }).fail(function (error) {
                // Total fail.
            });
        });
    </script>
</head>

<body>
<div id="container">
    {{ getCsrfInput() }}
...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.