I have been stuck on trying to make an ajax call to a custom plugin controller in Craft 2 for a few days after trying everything from following the documentation for Craft 2 as well as looking up other posts that basically reiterate what the documentation says, but nothing seems to work. According to the documentation for Craft 2, I should be able to use:
[PluginHandle]/[ControllerName]/[ActionName]
in a hidden field. I've even tried using the full method name, actionGetLocations, just to rule that out. Here is what I have:
<input type="hidden" name="action" value="/actions/googleMap/getLocations">
<input type="hidden" name="redirect" value="{{ siteUrl }}map-test">
Here is my controller:
<?php
namespace Craft;
class GoogleMap_MapController extends BaseController
{
public function actionGetLocations()
{
$this->requireAjaxRequest();
return $this->returnJson([
'success' => [
'state' => "This would be states",
'locations' => "This would be locations"
]
]);
}
}
My controller file is named GoogleMap_MapController.php
to follow the naming scheme. I also have my ajax request, which needs to be written in vanilla javascript for this site:
var xhr = new XMLHttpRequest();
xhr.open('POST', '/actions/googleMap/getLocations');
xhr.onreadystatechange = function() {
if(xhr.status === 200) {
console.log(xhr);
}
else {
console.log("The request failed, returned status of " + xhr.status);
console.log(xhr);
}
};
xhr.send(data);
I get a 404 error for page not found, which makes sense since it's not really a page, but the documentation says that it will attempt to determine if the request URL is an action first. I tried changing the ajax call to post to '/' instead, but that returns the HTML from the page '/' successfully, which is not what I'm trying to get at all. I've tried sticking my hidden input tags in a form tag, however the submit causes the page to redirect to this non-existent route. I added in onsubmit="event.preventDefault();"
to my form tag, and while it doesn't redirect, I still get a 404 error response. I'm completely at a loss at this point any help is greatly appreciated.