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
.
- Any idea where I when wrong with my insert?
- 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;
}