I'm having a problem with jQuery(or maybe php). I want forms to be submitted without refreshing the page so i ended up with the following code but the problem is it doesn't wo开发者_运维问答rk. Here's the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#submit").click(function() {
var name = $("#name").val();
var dataString = 'name='+ name;
$.ajax({
type: "POST",
url: "p.php",
data: dataString,
success: function(){
alert("It works");
}
});
return false;
});
</script>
</head>
<body>
<form id="myForm" name="myForm" action="">
<p>
<label for="name"></label>
<input type="text" name="name" id="name" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Submit" />
</p>
</form>
<br />
</body>
</html>
Processing Page:
<?php include("../includes/includes.php"); ?>
<?php $name = $_POST['name']; ?>
<?php $sql = "INSERT INTO xyz
(id, value) VALUES
(1, '{$name}')";
$result = $database->query($sql);
?>
i dont know why its not working but you can try like this
<form id="myForm" name="myForm" action="">
<p>
<label for="name"></label>
<input type="text" name="name" id="name" />
</p>
<p>
<input type="button" name="submit" id="submit" value="Submit" />//change type to button
</p>
</form>
also make an error callback
$(function(){
$("#submit").click(function(e) {
e.preventDefault();
var name = $("#name").val();
$.ajax({
type: "POST",
url: "p.php",
data: {name:name},
success: function(){
alert("It works");
},
error:function(e){alert("it failed");}
});
});
});
You need to modify your form tag like this:
<form id="myForm" name="myForm" action="" onsubmit="return false;">
精彩评论