Hot answers tagged

19

Disabling the CSRF protection is probably a bad idea... it's in there for a reason. But you can easily add your CSRF data to an AJAX call, and it works very well! The key is to make your CSRF token name & value available in your front-end JS. You can then pass that into your AJAX call as an additional value. There are a few ways to push the CSRF data ...


10

There is a new RESTful plugin which might be what you need: Rest-Easy from Wes Rice. But you could also make use of Twig's extends functionality: _ajax.html: {% block ajax %} { success: false } {% endblock %} entry.html: {% extends craft.request.isAjax ? "_ajax" : "_main" %} {% block ajax %} { success: true } {% endblock %} {% block normal %} ...


9

Hey So here is what i came up with, curious if anyone has a more streamlined approach. https://gist.github.com/keithmancuso/17619fc405a621b4a11e {% if craft.request.isAjax %} {% set layout = "_ajaxLayout" %} {% else %} {% set layout = "_layout" %} {% endif %} {% extends layout %} {% set limit = 10 %} {% set params = { section: 'news', limit: ...


9

Unlike Vue Resourse (if you've used it), Axios does not have a good way to emulateJSON on legacy servers or frameworks that do not understand submissions sent as application/json. Your data gets to Craft but it is not understood, leaving POST empty. You would need to have Axios submit to your own controller, where you can read the raw data, JSON decode it, ...


8

One method is to build your params before performing the search. {# set base params #} {% set params = { section: 'portfolio', limit: null } %} {% set relatedParams = ['and'] %} {# status #} {% if craft.request.getParam('status') %} {% set status = craft.request.getParam('status') %} {% set params = params|merge({'companyStatus':status}) %} ...


7

This is the syntax for Craft 3: <script type="text/javascript"> window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName }}"; window.csrfTokenValue = "{{ craft.app.request.csrfToken }}"; </script>


7

There's a ton of ways to pull this off, but in my opinion setting up pages/URLs for each category is probably a good idea, for SEO and sharing reasons. It's not something that requires a lot of work and would make implementing the AJAX part a breeze. Another win is that you're going to have a solution which will actually work without AJAX or JavaScript, too –...


7

Yes, you can do all the normal commerce actions via ajax. A basic recipe is this... HTML: <form method="POST" id="addToCartForm"> {{ getCsrfInput() }} <input type="hidden" name="action" value="commerce/cart/updateCart"> <input type="hidden" name="redirect" value="/cart"> <input type="hidden" ...


7

There is no real difference between a "normal" ajax request and an ajax request in Craft. You just leave the url blank, and insert an action parameter for your route. Craft 3 uses snake-case routes instead of camelCase. So when you want to access your plugin you would do. action = "plugin-handle/controller-name/function-name I full example as a CP request ...


6

Thanks to Kieth for posting an ajax solution. I just wanted to expand on it a little bit to figure out when we are at the end of the entries etc so we can hide loading more buttons etc. Here is what I did. In my example I am only loading 2 entries for each click so I'm setting the count to 2, and then incrementing the count on each click by 2. Here I am ...


6

So I just went through my article step-by-step and I indeed missed adding the new content into $main. I think there may have been a versioning mistake in the article's code as I definitely tested it. Anyways, here's an updated loadPage function for you. Which I will be adding to the article tomorrow. I've added a few extra things to ensure that there's no ...


6

Is it best to use jQuery for the Ajax-request?` Not necessarily. jQuery provides an easy-to-use ajax function, but nowadays it's perfectly simple to make an AJAX call with vanilla JS. How can I load the "next" five entries in a news-feed, so the call doesn't load the latest five entries over and over? You will need to pass an offset and limit to your ...


5

That looks perfect! Obviously this code doesn't prompt the user to confirm deletion, but that can easily be added. (Or perhaps you stripped that out of your example.) You are specifically doing two things right here: Hitting deleteEntry directly. This ensures that Craft follows all of its necessary internal procedures to properly delete the entry (and ...


5

If you want the error messages to be displayed identical to P&T's template/macro default, this should do the trick: $(function(){ $('#ajax-form').submit( function(ev) { // Prevent the form from actually submitting ev.preventDefault(); // Remove any existing error messages from previous attempts $(this).find( '....


5

I believe HeaderHelper::setHeader() is what you're looking for in the context of a plugin.


5

It's actually quite easy and you don't really need json or a plugin to do it. If you really need it as a plugin, then that's a whole different thing that would need a separate answer. In your search template file: <div id="contacts"><!-- results will get inserted here. --></div> <form id="find-contact-form" data-url="/contacts"> ...


5

I am just starting out on a project using both Craft and Angular. I ran into an early issue because both Angular and Twig use the {{ }} braces, but that was quickly fixed by changing Angular’s settings like in this Stackover flow post. As Christian noted in the comments, though, you could also use the {% verbatim %} tag to keep Craft from parsing Angular ...


5

EDIT Craft 2.4 is now available, and the users/saveUser action will now return a JSON response for AJAX requests. The original answer is still valid for <2.4 builds: No, there's no way to trigger a JSON response for the users/saveUser action. Other UsersController actions (such as users/login do return JSON for AJAX requests, so it might be an idea to ...


5

You need to pass the token and name into javascript. Easiest is to just have a script tag somewhere. <script type="text/javascript"> window.csrfTokenName = "{{ craft.config.csrfTokenName }}"; window.csrfTokenValue = "{{ craft.request.csrfTokenValue }}"; </script> Now they will be available to your ajax call.


5

I think I got this resolved the proper way... looks like you just need to make sure that your AJAX calls are localized. In my main _layout template: <script type="text/javascript"> window.siteUrl = "{{ siteUrl }}"; </script> Then in my JS, I have this: $.post( siteUrl + 'actions/myPlugin/myAction', ... ); As long as your siteUrl is ...


5

95% of the time you see a 400 Bad Request error, it's because it's a CSRF token validation error (or you're just missing the token all-together). Craft 3 has CSRF validation enabled by default. Here's how to pass the CSRF token to your JS in Craft 2: https://craftcms.com/support/csrf-protection#updating-your-javascript Here's the CSRF token changes in ...


4

I would use Craft's built in paginate tag. You just add the page number (p2, p3, p4, etc.) to the end of the url in your ajax call and output the template like this: {% paginate craft.entries.section('blog').limit(10) as entries %} {% for entry in entries %} <h1>{{ entry.title }}</h1> {{ entry.body }} {% endfor %} {% ...


4

Any properties of the object you pass into Craft.postActionRequest()’s second argument will be available to Craft as POST parameters, so you can get to them with HttpRequestService::getPost(): $sData = craft()->request->getPost('Data'); foreach ($sData as $temp) { $wine = $temp['wine']; // ... }


4

Disclaimer: I haven't ever used structure, but hopefully the method described below also works for that section type. You can do this quite easily with URL-segments Consider a URL like so: http://www.domain.com/section/entry/ http://www.domain.com/section/entry/subview-1 And so on. The section/entry route will hit your entry template, but you can ...


4

In one of your plugin services, you can render a template that handles the markdown filter and return the results as an HTML string. You can then send that HTML to wherever you want to preview. In your controller: public function actionPreviewContentAjax() { $this->requireAjaxRequest(); $content = craft()->request->getPost('...


4

Sure, you can do something like {% if not craft.request.isAjax() %} {% redirect siteUrl %} {% endif %}


4

Okay so you can either do this through ajax or through a page reload, a page reload is going to be much easier, but you can get it to work without reloading the page... Reloading the page You can basically make it so that when a user selects an option, use jQuery to redirect to the current page and append the <option> value to append as a query ...


4

This is actually a pretty simple task. Create a template that your JS will reach out to returning the total number of entries. First create a template folder called "ajax" with an index.html file inside. Within that file put (replacing blogs with the name of your channel): {{ craft.entries.section("blogs") | length }} Inside your javascript, add this: ...


4

I found the solution by making an application of Front end login form with ajax and Posting to controller actions. Here is what is really important to understand with Craft controller call: Most of the time, you’ll want to access controller actions via HTML forms over POST. To do this, we recommend that you leave your form’s ‘action’ attribute blank, and ...


4

This is the syntax for Craft 3: <script type="text/javascript"> window.csrfTokenName = "{{ craft.app.config.general.csrfTokenName }}"; window.csrfTokenValue = "{{ craft.app.request.csrfToken }}"; </script>


Only top voted, non community-wiki answers of a minimum length are eligible