3

How can I achieve a database insert using AJAX?

I've created a module and I'm using AJAX post to insert a record into the database but seem to get a silent error and no database update; I know the insertdata.php file is called as I get a syntax error recorded in my php_error_log.

  1. Any idea where I when wrong with my insert?
  2. Is there any way to show error log or console log in the insertdata.php file?
    error_log('My Error: ', 0); doesn't seem to work.

Below is the content of my default.php:

<div id="update_dialog" title="Update Details" style = "display:none">
    <form method="post" id="my_form" action="modules/mod_myPage/insertdata.php">
        <label>Company Name :</label><input id="Company_Name" type="text"></input>
        <label>Company Address :</label><input id="Company_Address" type="text"></input>
        <input id="submit" type="button" value="Submit">
    </form>
</div>

<script>
jQuery(document).ready(function () {
    jQuery("#submit").click(function () {

        _Company_Name = jQuery("#Company_Name").val();
        _Company_Address = jQuery("#Company_Address").val();

        jQuery.post("modules/mod_myPage/insertdata.php",
            {
                Company_Name: _Company_Name,
                Company_Address: _Company_Address
            },
            function (data, status) {
                alert("Data: " + data + "\nStatus: " + status);
            });
    });
});
</script>

And that of my insertdata.php file:

<?php
defined ( '_JEXEC' ) or die ();


if( isset( $_POST['Company_Name'] ) )
    {
        $_Company_Name = $_POST['Company_Name'];
        $_Company_Address = $_POST['Company_Address'];

        $insert_query = "INSERT INTO #__myCompany (Company_Name, Company_Address, Create_Date)
        VALUES('".$_Company_Name."','".$_Company_Address."','".date("Y-m-d H:i:s")."')";

        $db = JFactory::getDbo();
        $query = $db->getQuery(true);

        try
        {
            $db->setQuery($insert_query);
            $db->query();
        }
        catch (RuntimeException $e)
        {
            $e->getMessage();
            error_log('This query failed: '.$insert_query, 0);
            error_log($e->getMessage(), 0);
            return false;
        }
        return true;
    }
3

After more searches, I managed to work it out. Hopefully the below will offer some small mercy to some lost joomla soul like I was. The main challenge was constructing the URL and get a response. So here's my solution

url: "index.php?option=com_ajax&module=CompanyPage&method=updateDetails&format=raw"

  1. Required if using ajax request: index.php?option=com_ajax

  2. Your module being mod_CompanyPage is called without the mod_ as : &module=CompanyPage

  3. Your method in the helper class must have the key word Ajax at the end of the function. function updateDetailsAjax() but is constructed without the word Ajaxas : &method=updateDetails

  4. Finally the &format=raw at the end. (I haven't work out why yet)

To get a response from the helper class just echo it out.

<script>
jQuery(document).ready(function () {
    jQuery("#submit").click(function () {
    $.ajax({
       type: "POST",
       url: "index.php?option=com_ajax&module=CompanyPage&method=updateDetails&format=raw",
       data: dataString,
       success: function(data){
       alert(data);    // alert box pop up either show "We did it" or the error message from data connection
       }
        });

    });
});
</script>

helper.php

class modCompanyPageHelper
{

    function updateDetailsAjax()
    {  

        if( isset( $_POST['Company_Name'] ) )
        {

            $jinput = JFactory::getApplication()->input;

            $_Company_Name = $jinput->get('Company_Name', 'default_value', 'RAW');
            $_Company_Address = $jinput->get('Company_Address', 'default_value', 'RAW');

            $insert_query = "INSERT INTO #__myCompany (Company_Name, Company_Address, Create_Date)
            VALUES('".$_Company_Name."','".$_Company_Address."','".date("Y-m-d H:i:s")."')";

            $db = JFactory::getDbo();
            $query = $db->getQuery(true);

            try
            {
                $db->setQuery($insert_query);
                $db->query();
            }
            catch (RuntimeException $e)
            {

                echo $e->getMessage();
                return false;
            }
            echo "We did it";
            return true;
        }
    }
}

With this knowledge, I was able to call backend function to insert, upload and delete database record. I also managed to upload files on to server using dropzone.js

Life would have been so much easier had I known this info a month ago.

  • I managed to get a response from the helper class. Just echo back. – Phillip Oct 29 '16 at 0:30
1

Please, use Joomla's Ajax interface which is fully explained here. Do not reinvent the wheel and use your own Ajax calls - this is bad both for security and scalability.

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.