1

I have created a Custom Module for admin in Magento.

I am using a form and I have a file field in that form.

How I can upload image using Ajax in my custom module in Magento.

I have searched on Google but didn't find any perfect solution.

Somebody please suggest me what to do.?

2

First thing is first. You cannot upload images through AJAX.
You have to trick the browser (or the user).
take a look at how the category images are uploaded in app/design/adminhtml/default/default/template/catalog/category/edit/form.phtml.
The idea is to have an iframe in your DOM with and id (let's say 'trickIframe') and make that form submit to that iframe.

<iframe name="trickIframe" style="display:none; width:100%;" src="<?php echo $this->getJsUrl() ?>blank.html"></iframe>
<form target="trickIframe" id="some_id_here" action="<?php echo $this->getSaveUrl() ?>" method="post" enctype="multipart/form-data">
  ....
</form>

Then you can handle the post request in the save method and that method should return some javascript code for refresing (or replace page content or what ever) just like Mage_Adminhtml_Catalog_CategoryController::saveAction does.

$this->getResponse()->setBody(
        '<script type="text/javascript">parent.updateContent("' . $url . '", {}, '.$refreshTree.');</script>'
    );
5
  • Thank You @marius for your answer. As I am new to magento. I understood what you have told above but how can I create a another form for upload image and submit it without submitting main form.? Dec 5 '14 at 13:19
  • use the same method as described above, just make sure the image upload form is not inside the main form. Try to replicate at least partially the behavior of the category save form.
    – Marius
    Dec 5 '14 at 13:26
  • Sorry @marius ..not getting any idea, how to use above method in my module. Dec 5 '14 at 14:32
  • It's kind of hard and maybe pointless to explain without having the code you got so far. Please add some code to the question.
    – Marius
    Dec 5 '14 at 14:43
  • Hello marius, To upload file using AJAX, I have used AjaxFile Upload library in my module. Now I am getting a strange problem that you can find at this URL magento.stackexchange.com/questions/46549/… Dec 6 '14 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.