1

I have added one ajax validation for a custom section in magento checkout page as below,

Validation.js :

['validate-otp', 'Please enter valid OTP.', function(v) { var url = 'customsect/processing/test?code='+v; new Ajax.Request(url, { method: 'get', onSuccess: function(response){ alert(response.responseJSON); }, onComplete: function(res){ alert("complete"); }, onFailure: function(err){ alert("Error"+err); } }); }] 

app/code/local/myaddon/customsect/controllers/ProcessingController.php :

public function testAction() { $code = $this->getRequest()->getParams('code'); $itemArr = array('res' => $code); // $data = json_encode($itemArr); $this->getResponse()->setHeader('Content-type','application/json'); $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($itemArr)); } 

But am getting alert as "null". When i run below url I'm getting the json response displayed.

http://127.0.0.1/mage3/index.php/customsect/processing/test?code=ADXWZ

{"res":{"code":"ADXWZ"}} 

2 Answers 2

1

Please update code

['validate-otp', 'Please enter valid OTP.', function(v) { var url = 'http://127.0.0.1/mage3/index.php/customsect/processing/test?code='+v; new Ajax.Request(url, { method: 'get', dataType: 'json', onSuccess: function(response){ alert(response); }, onFailure: function(err){ alert("Error"+err); } }); }] 
3
  • I tried this. But getting an empty alert first then "complete" alert. Commented Feb 16, 2016 at 17:59
  • I have updated code please try with this Commented Feb 16, 2016 at 18:43
  • I removed the dataType json and then used "echo" in controller side. Now getting the response as "response.responseText". Commented Feb 17, 2016 at 9:52
1

Your Ajax request url should dynamic.

Define a java script which is content request url val at head.phtml

var OtpUrl="<?php echo $this->getUrl('RouteId/process/test')?>";

and call this variable instead of variable url at validation.js

Change new Ajax.Request(url, { to new Ajax.Request(OtpUrl, {

And send parameter list

 parameters: {code: v} 

Code may like:

new Ajax.Request(OtpUrl, { method:'get', parameters: {code: v}, requestHeaders: { Accept: 'application/json' }, onSuccess: function(transport) { var response = transport.responseText.evalJSON(true); }, onFailure: function(){ alert('Something went wrong...') } }); 
6
  • Php tag will work in .js file? Commented Feb 16, 2016 at 18:41
  • no, It need to define at phtml or php file and i have update it Commented Feb 16, 2016 at 18:43
  • I am getting [object object] when alerting the response.but unable to fetch the exact value of response. Commented Feb 16, 2016 at 18:45
  • use alert(response.res ) Commented Feb 16, 2016 at 18:46
  • It's a blank alert. Commented Feb 16, 2016 at 18:48

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.