What is wrong with my JavaScript? It is breaking somewhere to add a record without refreshing the page.
i finished deleting completely now with the aid of some experienced users. but now adding a record to the database is not working yet
i want to add a record dynamically now without refreshing.. deleting is functioning well and it is being reflected on the database.
I will include 4 files and my database:
- the files are
index.phpfor my main add.phpfor adding a recorddelete.phpfor deleting a record- dbconfig for the database connection and configuration
index.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>
add.php:
<?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. ";
}
?>
delete.php:
<?php
require('dbconfig.php'); //we cannot continue without this file, thats why using require instead of include
if(isset($_GET['id']))
{
$id=(int)$_GET['id'];
$sql = 'DELETE FROM `games` WHERE `ID`="'.$id.'" LIMIT 1';
mysql_query( $sql);
echo 'deleted';
}
?>
dbconfig:
<?php
$user_name = "root";
$password = "";
$database = "gamebook";
$server = "localhost";
$bd = mysql_connect($server, $user_name, $password) or die ('I cannot connect to the database because:' . mysql_error());
mysql_select_db($database);
?>
If needed, here’s the schema for my database as well:
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `gamebook`
--
CREATE DATABASE `gamebook` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;
USE `gamebook`;
-- --------------------------------------------------------
--
-- Table structure for table `games`
--
CREATE TABLE IF NOT EXISTS `games` (
`ID` int(4) NOT NULL AUTO_INCREMENT,
`Name` varchar(70) COLLATE utf8_unicode_ci NOT NULL,
`Type` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
`Rating` float NOT NULL,
`Release Year` int(4) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=7 ;
--
-- Dumping data for table `games`
--
INSERT INTO `games` (`ID`, `Name`, `Type`, `Rating`, `Release Year`) VALUES
(1, 'Battlefield 3', 'First Person Shooter', 8.5, 2011),
(2, 'Fifa 12', 'Sports', 9.2, 2004),
(3, 'Red Alert 3', 'Strategy ', 8.8, 2007),
(4, 'Fight Night Round 4', 'Fighting', 9, 2010),
(5, '', '', 0, 0),
(6, '', '', 0, 0);
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
What is wrong in my javascript and what is the best way to figure out??
Is there a good text editor you guys recommend for beginners like myself?
I notice a few things right off the bat.
jQuery Syntax
First of all, your JavaScript syntax is off. In your first file (
index.php) you have the following line:That’s not the proper syntax of the
.load()method. Basically, you have this:What you should have is this:
Remember, you need to add this extra functionality in the form of a callback otherwise it’s not going to work.
Inconsistent calls
In the first code block I addressed, it looks like you’re trying to load
add.phpand then fire some JavaScript commands after you’ve loaded it. But looking at the source of youradd.phpfile, you don’t want to do this. Youradd.phpfile contains the server-side code to process adding a record to the database … you don’t load it directly, you just submit POST requests to it.Invalid data
You’re not sending your data to the server properly. With the add routine, you’re first creating a data string:
Then you’re sending that in your data package via AJAX:
The problem here is two-fold. Firstly, you’re not encoding the data right.
'ID=' + id 'name='is missing a+character and will break. But even with that fixed, you’d be concatenating data improperly. YourdataStringvariable would end up looking like:You see how you’re missing a
&symbol? This is an easy mistake to make, so instead send a data object. You’re less likely to miss characters:Data mismatch
Next, you’re passing data to the server but checking for different values. Your JavaScript to add data looks like it wants to send:
But your
add.phpis checking for:Missing Data
With your delete routine, you’re checking for the value of “ID” in a GET. That means this value needs to be passed as a query argument appended to the URL. For example:
delete.php?ID=5to delete a game with the ID of 5.You’re checking for this just fine in the PHP, but you’re not actually sending the data in your AJAX request. Your code should look more like this:
See
url: "delete.php"becomesurl: "delete.php?" + info? This will append your ID to the url and make$_GET['id']available in PHP.