Updated- Added the insert code to save.php, but clicking on Save, no action is happening. Fields values are not getting inserted to db and also I am not getting the alert. Please advice.
I am trying to insert few user inputs to my mysql database using Ajax. Here is my html page:
<form id="form1" action="#" method="post">
<table style="padding-top: 25px;">
<tr style="height: 40px;">
<td style="text-align:right;">field1:</td>
<td><input type="text" id="field1" required/></td>
</tr>
<tr style="height: 40px;">
<td style="text-align:right;">field2:</td>
<td style="width: 286px;"><input type="text" id="field2"/> </td>
</tr>
<tr style="height: 40px;">
<td style="text-align:right;">Field3</td>
<td><input type="text" id="field3"/></td>
</tr>
<tr>
<td></td>
<td style="padding-top: 20px;">
<input type="submit" value="Save" id="Save"/>
</td>
</tr>
</table>
</form>
Here is my Ajax:
<script>
$(document).ready(function() {
$('#Save').click(function() {
var field1 = $('#field1').val();
var field2 = $('#field2').val();
var field3 = $('#field3').val();
$.ajax({
type: 'POST',
async: false,
url: 'save.php',
data: {
'saverecord': 1,
'field1':field1,
'field2':field2,
'field3':field3,
success: function(data)
{
if(data==0){
$('#field1').val('');
$('#field2').val('');
$('#field3').val('');
}
}
});
});
});
</script>
In my save.php file, I am trying to connect to my mysql database like this:
<?php
$cn = mysql_connect("localhost","root","");
if($cn)
{
mysql_select_db('databasename', $cn);
}
if(isset($_POST['saverecord']))
{
mysql_query("INSERT INTO table (field1, field2, field3) VALUES
('{$_POST['field1']}','{$_POST['field2']}','{$_POST['field3']}')");
alert("Inserted successfully");
exit();
}
?>
Please let me know how I can insert the above mentioned 3 field values into my table using Ajax and html? Thank you so much.