Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6821143
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T21:30:35+00:00 2026-05-26T21:30:35+00:00

What is wrong with my JavaScript? It is breaking somewhere to add a record

  • 0

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.php for my main
  • add.php for adding a record
  • delete.php for 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?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T21:30:36+00:00Added an answer on May 26, 2026 at 9:30 pm

    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:

     $("#add").load("add.php") {
    

    That’s not the proper syntax of the .load() method. Basically, you have this:

    $("#add").load("add.php") {
      // ... stuff to happen after add.php loads
    }
    

    What you should have is this:

    $("#add").load("add.php", function() {
      // .. stuff to happen after add.php loads
    });
    

    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.php and then fire some JavaScript commands after you’ve loaded it. But looking at the source of your add.php file, you don’t want to do this. Your add.php file 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:

    var dataString = 'ID=' + id 'name='+ name + '&username=' + type + '&password=' + rating + '&gender=' + release;
    

    Then you’re sending that in your data package via AJAX:

    $.ajax({
        type: "POST",
        url: "add.php",
        data: dataString,
        success: function(){
            $('.success').fadeIn(200).show();
            $('.error').fadeOut(200).hide();
        }
    });
    

    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. Your dataString variable would end up looking like:

    ID=1name=Bob&username=my_user&password=password&gender=male
    

    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:

    $.ajax({
        type: "POST",
        url: "add.php",
        data: {
    
        },
        success: function(){
            $('.success').fadeIn(200).show();
            $('.error').fadeOut(200).hide();
        }
    });
    

    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:

    • ID
    • name
    • username
    • password
    • gender

    But your add.php is checking for:

    • Submit
    • name
    • type
    • score
    • Yreleased

    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=5 to 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:

    $("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? !")){
            $.ajax({
                type: "get",
                url: "delete.php?" + info,
                context: document.body,
                success: function(){
                    $('.p'+del_id).html('deleted');
                }
            });
        }
        return false;
    });
    

    See url: "delete.php" becomes url: "delete.php?" + info? This will append your ID to the url and make $_GET['id'] available in PHP.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We have received some JavaScript from an agency that looks wrong, but works. For
Coming from a c# background, I'm probably looking at JavaScript from a completely wrong
Is the following method wrong way of declaring namespace in Javascript? It is from
if screen reader fill any content wrong then how to give info (if javascript
What is wrong with this code. The code is finding the javascript and debug1
Whats wrong with my query? ALTER TABLE test_posts ADD sticky boolean NOT NULL default
I was reading Douglas Crockford's web page, JavaScript: The World's Most Misunderstood Programming Language
i'm writing some inline javascript. it's not working and i'm not sure why. at
not the best with Javascript so thought i'd ask where i'm going wrong. as
What am I doing wrong? According to specs lowering domain with JavaScript should be

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.