I'm running an AJAX call that passes some variables to a PHP script which is supposed to INSERT into a table. But it doesn't work ?
Code :
<?php
$cn = mysql_connect('localhost','root','');
if ($cn) {
mysql_select_db('test',$cn);
}
if (isset($_POST['saverecord'])) {
$name = mysql_real_escape_string($_POST['name']);
$gender = mysql_real_escape_string($_POST['gender']);
$phone = mysql_real_escape_string($_POST['phone']);
mysql_query('INSERT INTO `ajax_php` (name,gender,phone) VALUES ($name,$gender,$phone)');
echo "IT WORK";
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title><?php echo "Ajax + PHP Tutorial"; ?></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<table id="data">
<tr>
<td>
Name :
<input type="text" name="name" id="name">
</td>
<td>
Gender :
<select id="gender" name="gender">
<option value="0">Male</option>
<option value="1">Female</option>
</select>
</td>
<td>
Name : <input type="text" name="phone" id="phone">
</td>
</tr>
<input type="button" value="save" id="save">
</table>
</body>
</html>
<script type="text/javascript">
$(function(){
// Save Data
$('#save').click(function(){
//get values
var name = $('#name').val();
var gender = $('#gender').val();
var phone = $('#phone').val();
alert(name);
$.ajax({
url: 'index.php',
type: 'POST',
async: false,
data: {
'saverecord' : 1,
'name': name,
'gender': gender,
'phone': phone
},
success: function(re) {
if (re==0) {
alert('success');
$('#name').val('');
$('#gender').val('');
$('#phone').val('');
}
}
});
});
// End
});
</script>
Also it doesn't display IT WORK, but Success is alerted. I think that the problem is located in the given javascript code ...
console.log(..).)