Reputation: 847
My controller has this function in it:
public function saveLeadDaysAction(){
echo "works";
}
And in the template phtml I am trying to this:
jq("#prodcal_leaddays").on("blur", function(e){
$saveurl="<?=$this->getUrl('prodcal/adminhtml_prodcaltab/saveLeadDays');?>";
console.log('$saveurl');
jq.post($saveurl,{'id':'test'},function(d){
console.log(d);
});
});
The url seems to return the entire admin dashboard page instead of the expected works
text. However if I open the url directly in the browser, it does show the expected text.
What am I doing wrong?
Oh and I have tried appending ?isAjax=true
at the end of the url, which returns:
{"error":true,"message":"Invalid Form Key. Please refresh the page."}
EDIT: Just to clarify:-
the getUrl
generates a url like http://localhost/devmagento/index.php/prodcal/adminhtml_prodcaltab/saveLeadDays/key/d3c92257c664d8d207f5a0bdeb3edebf/
in the console.
If I copy this url from the console and paste it in the browser, it works as expected and I get the works
text.
But when used with jQuery post, it fails and redirects to dashboard.
EDIT 2: It seems with post data, the key is wrong, cause if I change the above to use GET
, and put the values within the getUrl
function, it works properly, but the problem is since this is to be done by ajax, I need to change the values dynamically using javascript.
What I did for the get thing to work is:
jq("#prodcal_leaddays").on("blur", function(e){
$saveurl="<?=$this->getUrl('prodcal/adminhtml_prodcaltab/saveLeadDays',array('id'=>'test'));?>";
console.log($saveurl);
jq.get($saveurl,function(d){
console.log(d);
});
});
Upvotes: 3
Views: 6361
Reputation: 1
I had the same problem and solved it with adding the form_key to the url directly:
$saveurl="<?=$this->getUrl('prodcal/adminhtml_prodcaltab/saveLeadDays');?>form_key=" + window.FORM_KEY;
Upvotes: 0
Reputation: 434
You can use POST ajax requests but you must add ?isAjax=1 to the url and form_key to params. Example:
var values = {
'form_key': "<?php echo Mage::getSingleton('core/session')->getFormKey(); ?>"
// ...
};
$jq.post('<?php echo Mage::helper('adminhtml')->getUrl("..."); ?>?isAjax=1', values);
Upvotes: 2
Reputation: 345
The URL generated by this code:
$this->getUrl('prodcal/adminhtml_prodcaltab/saveLeadDays')
cannot be found, so you are redirected to the dashboard. If you try it manually, you don't have the key
variable that is automatically added by getUrl()
function, so you get that error. That key
is a kind of session controller, and always changes.
To get to the right controller action, you have to check your file structure. As in your getUrl
parameter, it shoul be / app / code / local (or community) / YourName / Prodcal / controllers / Adminhtml / ProdcaltabController.php
Return your response in this way:
$array = array('works');
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($array));
Upvotes: 0