
Magento 1.x – How to make an ajax call in a backend fieldset field
If you are making a backend admin form, and you need to make an ajax call to retrieve some information, the following tutorial will help you:
In this particular case, we are going to find an sku thumbnail and show it up next to a search button.
1- Add an input where we are going to find the sku on our admin form:
1 2 3 4 |
$event = $fieldset->addField('content_sku', 'text', array( 'name' => 'content_sku', 'label' => $this->__('Product'), )); |
2- Add the after html behaviour to our fieldset, here we are going to add:
- A button to call our ajax function.
- An spam where we are going to put the results.
- The javascript function itself with the Ajax request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
$event->setAfterElementHtml(" <button type=\"button\" name=\"some_name\" class=\"some class\" onclick=\"checkSelectedItem(document.getElementById('content_sku').value)\">Search</button> <br><span id=\"results\"></span> <script type=\"text/javascript\"> function checkSelectedItem(value){ var reloadurl = '". $this->getUrl('*/*/loadcategoryproductthumbnail')."'; new Ajax.Request(reloadurl, { method: 'get', parameters: {content_sku: value}, //onComplete: function(selectElement) { // Some on complete behaviour }, onSuccess: function(selectElement) { var results = JSON.parse(selectElement.responseText); if(typeof results.error != 'undefined') { document.getElementById('results').innerHTML = results.error; return; } document.getElementById('results').innerHTML = results.image; } }); } </script>"); |
3- Create a new action called loadcategoryproductthumbnail under controllers/Adminhtml/MyModuleController with the logic we need, in this case:
- Get a product from an sku that came from the call request.
- Get the product thumbnail.
- Report an error via json in case the product do no exists.
- Return the full product image tag in case that it exists.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public function loadcategoryproductAction() { $productSku = $_REQUEST['content_sku']; $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$productSku); if(!$product){ $returnData['error'] = "There are no products matching this selection"; echo json_encode($returnData); return false; } $returnData['image'] = '<img src="'.Mage::getModel('catalog/product_media_config') ->getMediaUrl($product->getThumbnail()).'"/>'; echo json_encode($returnData); } |
And that’s it, don’t forget to clean cache, and you will see something like that: