Skip to main content
edited tags
Link
Source Link

Is it possible to upload file using Joomla Ajax Interface (com_ajax)

I am using com_ajax in a module. I have a form with text inputs which I can pass through to the method and store to database but I am struggling to upload a file.

Code that works fine for text inputs is as follows

tmpl/default.php

<div id="resultsDiv"></div> <form name="form1" method="post" action="" id="form1"> <input type="text" name="text1" id="text1"> <input type="text" name="text2" id="text2"> <button type="button" id="btnAdd">Save</button> </form> 

mod_ajax_test.php

// Include the helper. require_once __DIR__ . '/helper.php'; // Instantiate global document object $doc = JFactory::getDocument(); $js = <<<JS (function ($) { $(document).on('click', '#btnAdd', function () { var value = {text1:$("#text1").val(),text2:$("#text2").val()}; request = { 'option' : 'com_ajax', 'module' : 'ajax_text', 'method' : 'addRecord', 'data' : value, 'format' : 'raw' }; $.ajax({ type : 'POST', data : request, success: function (response) { $("#resultsDiv").html(response); } }); }); })(jQuery) JS; $doc->addScriptDeclaration($js); require JModuleHelper::getLayoutPath('mod_ajax_test'); 

helper.php

public static function addRecordAjax() { $input = JFactory::getApplication()->input; $formData = new JInput($input->get('data', '', 'array')); $text1 = $formData->getString('text1'); $text2 = $formData->getString('text2'); $db = JFactory::getDbo(); // Create a new query object. $query = $db->getQuery(true); // Insert columns. $columns = array( 'text1', 'text2' ); // Insert values. $values = array( $db->quote($text1), $db->quote($text2) ); // Prepare the insert query. $query ->insert($db->quoteName('table1')) ->columns($db->quoteName($columns)) ->values(implode(',', $values)); // Set the query using our newly populated query object and execute it. $db->setQuery($query); $result = $db->execute(); if ($error = $db->getErrorMsg()) { throw new Exception($error); } } 

If it is possible to do so how might I go about:

  1. Upload file to directory on server and store location in database

  2. Upload file and store binary data to database blob field

Please provide examples.

Thanks