I'm trying to get this to work, but I am having issues. What am I missing here?
I'开发者_开发技巧m trying to insert some data via jQuery to a local MySQL table. If I run save.php on its own, it inserts a blank row in the DB, so that works. Any ideas?
**index.php**
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('form#submit').submit(function () {
var nume = $('#nume').val();
$.ajax({
type: "POST",
url: "save.php",
data: "nume="+ nume,
success: function() {
$('#nume').val('');
}
});
return false;
});
});
</script>
</head>
<body>
<form id="submit" method="post">
<p>Nume: <input id="nume" name="nume" type="text"></p>
<p><input id="submitButton" type="button" value="Submit"></p>
</form>
</body>
</html>
**save.php**
<?php
mysql_connect('localhost', 'root', 'root') or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$nume = htmlspecialchars(trim($_POST['nume']));
$add = "INSERT INTO ajax_test (nume) VALUES ('$nume')";
mysql_query($add) or die(mysql_error());
?>
Are you sure the form is submitting? Your button is not an input type="submit" - it's just a button. It won't submit the form on its own.
If the solution of Scott Saunders does not work try this:
instead of
url: "save.php",
try:
url: "save.php?nume=testvalue",
If that also does not work, check if your PHP script reads the input value out of $_GET['nume']
or $_POST
instead of $_REQUEST['nume']
couple of things you could do to help with troubleshooting.
Stick an alert alert("submit");
in after the $('form#submit').submit(function () {
to see if the form is submitting. Also stick one in the success alert("success");
to see if you're getting a callback. This will show you at what stage it's failing and help you liit your search.
You can also use the firebug plugin for firefox to see what's being sent via ajax, if it's working, to see if you've got any values wrong. Think you need to tick Show XMLHttpRequests in Console
精彩评论