1

I want to upload image from frontend custom module using ajax method.

Filepath : app/code/Chirag/Userform/view/frontend/templates/insert.phtml

<?php
$blockObj= $block->getLayout()->createBlock('Chirag\Userform\Block\Insert');
echo $blockObj->getEventsTxt();
?>
<form 
    class="" 
    name="eventform" 
    id="eventform" 
    <?php /*action="<?php echo $blockObj->getEventsPostURL();?>" */ ?>
    method="post" 
    accept-charset="utf-8"  
    data-mage-init='{"validation":{}}'>
    <table width="60%">
        <tr>
            <td colspan="2" align="center">User Form</td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('User First Name :'); ?></span></td>
            <td><input type="text" name="fname" id="fname" placeholder="Enter User First Name" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('User Last Name :') ?></span></td>
            <td><input type="text" name="lname" id="lname" placeholder="Enter User Last Name" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('Address :') ?></span> </td>
            <td><textarea name="address" id="address" placeholder="Details of Address" class="input-text" cols="5" rows="3" data-validate="{required:true}"></textarea></td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('City :') ?></span></td>
            <td><input type="text" name="city" id="city" placeholder="Enter User City Name" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('User Mobile Number :') ?></span></td>
            <td><input type="text" name="mobilenumber" id="mobilenumber" placeholder="Enter User Mobile Number" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>

        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('File Name :') ?></span></td>
            <td><input type="text" name="filename" id="filename" placeholder="Enter File Name" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('File Upload Here :') ?></span></td>
            <td><input type="file" name="filepath" id="filepath" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>
        <tr>
            <td colspan="2" align="center"><button type="submit" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>" class="action submit primary">
                <span><?php /* @escapeNotVerified */ echo __('Submit') ?></span>
            </button></td>
        </tr>
    </table> 
</form>


<script>
require(['jquery'],function(){
    jQuery(document).ready(function() {
        jQuery("#eventform").submit(function(){
            if (jQuery('#eventform').valid()) {
                jQuery('.page.messages').html('');
                var event_fname = jQuery("input[name='fname']").val();
                var event_lname = jQuery("input[name='lname']").val();
                var event_address = jQuery("textarea[name='address']").val();
                var event_city = jQuery("input[name='city']").val();
                var event_mobilenumber = jQuery("input[name='mobilenumber']").val();

                var event_filename = jQuery("input[name='filename']").val();
                //var filepath = this.files[0];
                //formdata = new FormData();
                //var file = this.files[0];
                var url = "<?php echo $block->getBaseUrl().'userform/index/ajaxsave/' ?>";
                jQuery.ajax({
                    url: url,
                    type: "POST",
                    dataType: "JSON",
                    data: {fname:event_fname,lname:event_lname,address:event_address,city:event_city,mobilenumber:event_mobilenumber,filename:event_filename},
                    //data: formdata,
                    showLoader: true,
                    cache: false,
                    success: function(response){
                        //console.log(response.output);
                        //jQuery('.page.messages').html(response);
                        if(response == "1"){
                            //alert("Saved!");
                            jQuery(".page.messages").html('<div role="alert" class="messages"><div class="message-success success message" data-ui-id="message-success"><div >You saved the data.</div></div></div>');
                            jQuery('#fname').val('');
                            jQuery('#lname').val('');
                            jQuery('#address').val('');
                            jQuery('#city').val('');
                            jQuery('#mobilenumber').val('');
                        }else{
                            //alert("Not Saved!");
                            jQuery(".page.messages").html('<div role="alert" class="messages"><div class="alert danger alert-danger" data-ui-id="message-danger"><div >Data could not saved ! .</div></div></div>');
                        }
                        jQuery(".page.messages").delay(200).fadeIn().delay(4000).fadeOut();
                    }
                });
                return false;
            }

        });
    });
});
</script>

In controller, i wrote like this: File : Chirag/Userform/Controller/index/Ajaxsave.php

<?php
namespace Chirag\Userform\Controller\Index;

use Magento\Framework\App\Action\Context;
use Chirag\Userform\Model\ForminitFactory;
class Ajaxsave extends \Magento\Framework\App\Action\Action
{
    /**
     * @var Test
     */
    protected $_test;

    public function __construct(
        Context $context,
        ForminitFactory $test
    ) {
        $this->_test = $test;
        parent::__construct($context);
    }
    public function execute()
    {
        $data = $this->getRequest()->getParams();
        //print_r($_FILES);
        //print_r($data); exit();
        /*$reason = $this->getRequest()->getParam('reason');
        $contentdata = $this->getRequest()->getParam('contentdata');*/
        $test = $this->_test->create();
        $test->setData($data);

        if($test->save()){
            //$this->messageManager->addSuccessMessage(__($test['fname']. ' ! You saved the data.'));
            //$this->messageManager->addSuccessMessage(__('You saved the data.'));
            $res = "1"; //echo "1";
        }else{
            //$this->messageManager->addErrorMessage(__('Data was not saved.'));
            $res = FALSE; //echo "0";
        }
        //$resultRedirect = $this->resultRedirectFactory->create();
        //$resultRedirect->setPath('events');
        //echo $test;
        echo json_encode($res);

        //create log
        /*$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $logger = $objectManager->create('\Psr\Log\LoggerInterface');
        $logger->debug(100,print_r($test,true));*/
    }
}
?>

I use this code. I saw that firstname, lastname, address, city, mobilenumber, filename these fields are saved in database. When I trying to upload image or trying to get file with jQuery or javascript, it refresh the page and nothing saved in database.

Anyone guide me that how to do it and upload file with ajax? Thanks in advance.

0

I found solution. I uploaded image file successfully with AJAX. Answer is here.

Filepath : app/code/Chirag/Userform/view/frontend/templates/insert.phtml

<?php
$blockObj= $block->getLayout()->createBlock('Chirag\Userform\Block\Insert');
echo $blockObj->getEventsTxt();
?>
<?php //echo "formm"; ?>
<!-- <h3><a href="index/listdata">Show All Events</a></h3> -->
<form 
    class="" 
    enctype="multipart/form-data" 
    name="eventform" 
    id="eventform" 
    <?php /*action="<?php echo $blockObj->getEventsPostURL();?>" */ ?>
    method="post" 
    accept-charset="utf-8"  
    data-mage-init='{"validation":{}}'>
    <table width="60%">
        <tr>
            <td colspan="2" align="center">User Form</td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('User First Name :'); ?></span></td>
            <td><input type="text" name="fname" id="fname" placeholder="Enter User First Name" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('User Last Name :') ?></span></td>
            <td><input type="text" name="lname" id="lname" placeholder="Enter User Last Name" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('Address :') ?></span> </td>
            <td><textarea name="address" id="address" placeholder="Details of Address" class="input-text" cols="5" rows="3" data-validate="{required:true}"></textarea></td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('City :') ?></span></td>
            <td><input type="text" name="city" id="city" placeholder="Enter User City Name" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('User Mobile Number :') ?></span></td>
            <td><input type="text" name="mobilenumber" id="mobilenumber" placeholder="Enter User Mobile Number" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>

        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('File Name :') ?></span></td>
            <td><input type="text" name="filename" id="filename" placeholder="Enter File Name" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>
        <tr>
            <td><span><?php /* @escapeNotVerified */ echo __('File Upload Here :') ?></span></td>
            <td><input type="file" name="filepath" id="filepath" data-validate="{required:true}" value="" class="input-text" ></td>
        </tr>
        <!-- <tr>
            <td><span><?php /* @escapeNotVerified */ //echo __('Event Date :') ?></span> </td>
            <td><input type="date" name="date" id="date" placeholder="Event Date" value="" class="input-text"  data-validate="{required:true, 'validate-date':true}" ></td>
        </tr> --> 
        <tr>
            <td colspan="2" align="center"><button type="submit" title="<?php /* @escapeNotVerified */ echo __('Submit') ?>" class="action submit primary">
                <span><?php /* @escapeNotVerified */ echo __('Submit') ?></span>
            </button></td>
        </tr>
    </table> 
</form>


<script>
require(['jquery'],function(){
    jQuery(document).ready(function() {
        jQuery("#eventform").submit(function(){
            if (jQuery('#eventform').valid()) {
                jQuery('.page.messages').html('');
                var event_fname = jQuery("input[name='fname']").val();
                var event_lname = jQuery("input[name='lname']").val();
                //var event_address = jQuery("input[name='address']").val();
                var event_address = jQuery("textarea[name='address']").val();
                var event_city = jQuery("input[name='city']").val();
                var event_mobilenumber = jQuery("input[name='mobilenumber']").val();

                var event_filename = jQuery("input[name='filename']").val();

                var formData = new FormData(this);
                var file_obj = document.getElementById("filepath");
                formData.append('filepath', file_obj.files[0]);

                var url = "<?php echo $block->getBaseUrl().'userform/index/ajaxsave/' ?>";
                jQuery.ajax({
                    url: url,
                    type: "POST",
                    dataType: "JSON",
                    contentType: false,
                    enctype: 'multipart/form-data',
                    processData: false,
                    //data: {fname:event_fname,lname:event_lname,address:event_address,city:event_city,mobilenumber:event_mobilenumber,filename:event_filename},
                    data: formData,
                    showLoader: true,
                    cache: false,
                    success: function(response){
                        //console.log(response.output);
                        //jQuery('.page.messages').html(response);
                        if(response == "1"){
                            //alert("Saved!");
                            jQuery(".page.messages").html('<div role="alert" class="messages"><div class="message-success success message" data-ui-id="message-success"><div >You saved the data.</div></div></div>');
                            jQuery('#fname').val('');
                            jQuery('#lname').val('');
                            jQuery('#address').val('');
                            jQuery('#city').val('');
                            jQuery('#mobilenumber').val('');
                        }else{
                            //alert("Not Saved!");
                            jQuery(".page.messages").html('<div role="alert" class="messages"><div class="alert danger alert-danger" data-ui-id="message-danger"><div >Data could not saved ! .</div></div></div>');
                        }
                        jQuery(".page.messages").delay(200).fadeIn().delay(4000).fadeOut();
                    }
                });
                return false;
            }

        });
    });
});
</script>

File : Chirag/Userform/Controller/index/Ajaxsave.php

<?php
namespace Chirag\Userform\Controller\Index;

use Magento\Framework\App\Action\Context;
use Chirag\Userform\Model\ForminitFactory;
use Magento\Framework\App\Filesystem\DirectoryList;
use Magento\MediaStorage\Model\File\UploaderFactory;
use Magento\Framework\Image\AdapterFactory;
use Magento\Framework\Filesystem;
class Ajaxsave extends \Magento\Framework\App\Action\Action
{
    /**
     * @var Test
     */
    protected $_test;
    protected $uploaderFactory;
    protected $adapterFactory;
    protected $filesystem;

    public function __construct(
        Context $context,
        ForminitFactory $test,
        UploaderFactory $uploaderFactory,
        AdapterFactory $adapterFactory,
        Filesystem $filesystem
    ) {
        $this->_test = $test;
        $this->uploaderFactory = $uploaderFactory;
        $this->adapterFactory = $adapterFactory;
        $this->filesystem = $filesystem;
        parent::__construct($context);
    }
    public function execute()
    {
        $data = $this->getRequest()->getParams();

        if(isset($_FILES['filepath']['name']) && $_FILES['filepath']['name'] != '') {
            try{
                $uploaderFactories = $this->uploaderFactory->create(['fileId' => 'filepath']);
                $uploaderFactories->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
                $imageAdapter = $this->adapterFactory->create();
                $uploaderFactories->addValidateCallback('custom_image_upload',$imageAdapter,'validateUploadFile');
                $uploaderFactories->setAllowRenameFiles(true);
                $uploaderFactories->setFilesDispersion(true);
                $mediaDirectory = $this->filesystem->getDirectoryRead(DirectoryList::MEDIA);
                $destinationPath = $mediaDirectory->getAbsolutePath('chirag/userform');
                $result = $uploaderFactories->save($destinationPath);
                if (!$result) {
                    throw new LocalizedException(
                        __('File cannot be saved to path: $1', $destinationPath)
                    );
                }

                $imagePath = 'chirag/userform'.$result['file'];
                $data['filepath'] = $imagePath;
                //echo $data['filepath'];
            } catch (\Exception $e) {
                echo $e->getMessage();
            }
        }else{
            echo $msg = "File not found!";
        }

        $test = $this->_test->create();
        $test->setData($data);

        if($test->save()){
            //$this->messageManager->addSuccessMessage(__($test['fname']. ' ! You saved the data.'));
            //$this->messageManager->addSuccessMessage(__('You saved the data.'));
            $res = "1"; //echo "1";
        }else{
            //$this->messageManager->addErrorMessage(__('Data was not saved.'));
            $res = FALSE; //echo "0";
        }

        echo json_encode($res);

    }
}
?>
| improve this answer | |

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.