| Wednesday, 29 October 2014
I recently encountered a problem with the Ajax calls in our PrestaShop modules. The method we were using would not work at all if the store was set to maintenance mode, and for importing and exporting tools it is crucial that they work while the store is in maintenance mode. I discovered a work around for this issue, and it makes things pretty simple.
These steps are for our backoffice modules, and I have not tested them for frontend ajax calls but I assume they should work there too. (If anyone discovers otherwise then let me know and I will update this.)
Step 1) Add an ajax handler function to your modules class file, the naming of this function is important. You need to prefix your method name with ajaxProcess.
In this case our Ajax handler is called MyAjaxMethod.
Step 2) Add your ajax call to one of your displayed pages
The URL for this call is important, it calls your main controller which would usually trigger a full page refresh, however if you specify ajax = true in the data parameters then your request is sent to the appropriate ajaxProcess function.
You won't always be working with simple static data, so to make your ajax handler more interactive you can simply pass it some variables with the data parameters of your ajax call.
Step 1) Edit your ajax handler to accept your data parameters
The PrestaShop function for getting post/get data also accepts an optional default value as the second parameter if the variable is not set.
Step 2) Add your desired variables to the ajax calls data parameters
...and that's it! Your ajax call will now prompt the user for their name, and respond with a personalized greeting.
Once you start writing more complex ajax calls, you will probably want to have your handler respond with json.
This is a very simple change, you just need to use json_encode on your ajax handlers output:
and modify your ajax call so it expects an ajax response by adding: dataType: 'json'
That's all for now, get in touch if you have any comments about this guide.
Phone Us: (408) 675-5884