I’m learning AJAX and jQuery and I’m trying to put together a simple test script that will take 2 input fields and insert the data to my database. I can’t figure out what I’m doing wrong, but the code below won’t insert the data. can anyone spot my problem?
I’m not getting any errors and I don’t see anything weird in the console.
HTML
<input id="name" type="text"/>
<input id="LastName" type="text"/>
<button id="testButton">Button</button>
<div id="callback"></div>
JS
$('#testButton').click(function () {
var firstName = $("#name").val();
var lastName = $("#LastName").val();
$.ajax({
type: "POST",
url: "insert.php",
data: { name: firstName, LastName: lastName }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
PHP
//Adding to the local database
$name = array($_POST['name'], $_POST['LastName']);
$qry = $dbh->prepare(
'INSERT INTO info (FirstName, LastName) VALUES (?,?)');
if ($qry->execute($name)) {
echo "Success";
}
Your JS code is working just fine but with jsfiddle echo service.
here is the link : http://jsfiddle.net/TPu8X/
another version : http://jsfiddle.net/TPu8X/1/
Your code will only work with
jquery 1.5.2or later (May be you are using an older version)It seems you are not having your
insert.phpat correct path.So try placing php at correct path.