Reputation: 17
I want to add a record dynamically. When I insert action = "add.php" for my form, the addition is accomplished by displaying a message after refreshing. I want to add this addition without refreshing dynamically.
Also, for the ID of my games, I want that when I delete a record, for the ID to be decremented or removed. So that, when I add a game again, it uses the next ID available, not keeps on incrementing, like it is happeneing with me now.
If I take off add.php from action, nothing happens and the game isn't added. My question is, where is this script broken? Or if add.php is not functioning right?
Here is my index.php and add.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>title</title>
</head>
<body>
<?php
include("dbconfig.php");
$sql = "SELECT * FROM games";
$result = mysql_query($sql);
while ($record = mysql_fetch_array($result)){
echo "<p class=\"p" .$record['ID']. "\"></br> Game ID: " .$record['ID']. "</br> Game Name: " .$record['Name'].
"<br /> Game Type: ".$record['Type']. "<br /> Rating: ".$record['Rating']."<br /> Year Released: ".$record['Release Year']."<br /> <br />" ?>
<a href="#" id="<?php echo $record["ID"]; ?>" class="deletebutton"><img src="trash.png" alt="delete"/> </a></p>
<?php
}
?>
<form name="add" id ="add" action="" method="post">
<input class ="gameID" type="hidden" id="ID" name="ID" value = " ' .$record['ID'] . ' " />
<b>Game Name: </b> <input type="text" id="name" name="name" size=70>
<b>Game Type:</b> <input type="text" id="type" name="type" size=40>
<b>Rating: </b> <input type="number" id="score" name="score" min="1.0" max="10.0" step ="0.1"/>
<b>Year Released: </b> <input type="number" min="1900" max="2011" id="Yreleased" name="Yreleased" value="1985" size=4>
<p><input type="submit" name="Submit" id = "Submit" value="Add Game" class = "add games"></p>
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("#add").submit(function(){
var name = this['name'].value;
var type = this['type'].value;
var rating = this['score'].value;
var release = this['Yreleased'].value;
var dataString = 'name='+ name + '&type=' + type + '&rating=' + rating + '&release=' + release;
if (name == '' || type == '' || rating == '' || release == ''){
alert("please enter some valid data for your game entry");
}else
$.ajax({
type: "POST",
url: "add.php",
data: dataString,
success: function(){
window.location.reload(true);
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
}
)});
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript">
$(document).ready(function(){
$("a.deletebutton").click(function(){
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var parent = $(this).parent();
if(confirm("Sure you want to delete this game? !..There is no Undo")){
$.ajax({
type: "get",
url: "delete.php?" + info,
context: document.body,
success: function(){
$('.p'+del_id).html('deleted');
$('.success').fadeIn(200).show();
}
});
}
return false;
});
});
</script>
</body>
</html>
<?php
require('dbconfig.php'); //we cannot continue without this file, thats why using require instead of include
if(isset($_POST['name']))
{
$name=addslashes($_POST['name']);
$type=addslashes(($_POST['type']));
$rating=addslashes($_POST['rating']);
$release=addslashes($_POST['release']);
$sql = 'INSERT INTO `games` (`Name`,`Type`,`Rating`,`Release Year`) VALUES ("'.$name.'", "'.$type.'", "'.$rating.'", "'.$release.'")';
mysql_query( $sql);
if(!mysql_errno())
echo " your game has been added to the list of games. ";
}
?>
Upvotes: 1
Views: 2944
Reputation: 150080
What your code is currently trying to do is the right principle: you are trying to trap the submit event on the form, make your Ajax request instead, and then cancel the default submit.
The reason it doesn't work is this line:
$("add games").Submit(function(){
".submit()" should have a lowercase "s", and the selector you are using, "add games", is not going to return any elements because it looks for elements with the tag name "games" that are descendents of elements with tag name "add".
What you want to do is fix the case of the "s", and select your element by id, which you do with "#yourid". Your form name has the id "add", so do this:
$("#add").submit(function(){
Also both your document.ready and your submit handler functions have an extra pair of {}
curly braces around their bodies so you should delete those:
$("#add").submit(function(){
{ // <- delete this {
/*function body code*/
} // <- delete this }
});
Also you are including the jquery.js script twice - once is enough. And you don't need two document.ready handlers, you can combine them into a single one (though you can have more than one and that shouldn't cause a problem).
(There may be some other issues, but try this first and get back to us.)
UPDATE: After the other fixes, I suspect the problem is now in your PHP, in the line:
if(isset($_POST['Submit']))
I don't know PHP, but I assume this is checking for a request parameter called 'Submit' that you are not setting in your JS (it was the name of your submit button and would've been set for a "standard", non-Ajax submit, but it won't be included in your Ajax request). Try changing that line to use a request parameter that you are setting, like:
if(isset($_POST['name']))
Then, even if you don't seem to get a response in the browser, check your database to see if records are being added.
Upvotes: 1
Reputation: 27560
Aside from the problems everyone else helped with, your form is still submitting because of this line:
if (id =='' || name == '' || type == '' || rating == '' || release == ''){
You did not define id
in the code above it. This is causing the function to throw an exception before return false
is called. You need to either remove id =='' ||
from your if-statement or define it in your function.
As a side note, I see that you are pulling data from the form using the following:
var name = $("#name").val();
var type = $("#type").val();
Inside the submit handler, this
is the form object, meaning you can access form fields by name. I would recommend using the following properties:
var name = this['name'].value,
type = this['type'].value;
This way, you don't need IDs on your form fields and you could if necessary insert the same form multiple times in the document.
Also, you should be validating your form input. A user could enter "); DROP TABLE games;//
or <script src='http://evil.com/bad.js'></script>
in any of your fields and really ruin your life.
Upvotes: 0
Reputation: 1805
Make a few changes:
$("add games").submit(function(){ }); -> $(".add games").Submit(function(){});
or
$("#add").submit(function(){}); or $("#add").click(function(){ //run your ajax script here});
as for the id issue, MySQl will keep incrementing the id and if you delete one, it won't decrement it. May I know why you want the ids in order?
Editing again: (Use json.js)
here is another workaround:
var postdata = new Object();
postdata.name = value;
postdata.type = value;
postdata.rating = value;
//and so on
$.ajax({
url: 'your url',
type: "POST",
contentType: "application/json; charset=utf-8", //add this
data: JSON.stringify(postdata), //another change
dataType: "json",
success: function(data, st) {
if (st == "success") {
alert('Data Added');
}
},
error: function() {
alert("Failed!");
}
});
Upvotes: 0