0

I am trying to display a table from my PHP file on a web page which is the index.html file using ajax. I am new to PHP and ajax so I currently do not know what is wrong with the codes. However what I do know is that there data is not getting through this line in the javascript file.

 document.getElementById("divTable").innerHTML=xmlhttp.responseText;

It works without ajax but of course I do need to go to database.php to display the table. I want it to display on index.html. Also, will my delete button in my PHP file still work?

P.S. I'm using vi editor as I'm currently coding this on a server. However it's just to test out. I am new to server stuff, ajax and PHP so do pardon my mistakes if any. And ignore the table formatting in my HTML file.

P.P.S I do not know any form of jQuery and what I have written is my current knowledge of AJAX.

<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css"/>
    <script src="function.js" type="text/javascript"></script>
</head>

<body>
    <form name="infoForm" method="post" onsubmit="return checkFields()"  action="">
            <table>
            <tr>
                    <td>Name:</td>
                    <td><input type="text" name="name" id="name" maxlength="40"></td>
            </tr>
            <tr>
                    <td>Address:</td>
                    <td><textarea maxlength="45" name="address"id="address" ></textarea></td>
            </tr>
            <tr>
                    <td>Phone:</td>
                    <td><input type="text" name="phone" id="phone"  maxlength="20"><br></td>
            </tr>
            <tr>
                    <td>Gender:</td>
                    <td><input checked type="radio" name="gender" id="male" value="Male">Male
                    <input type="radio" name="gender" id="female" value="Female">Female</td>
            </tr>
            <tr>
                    <td>
                            Nationality:
                    </td>
                    <td>
                            <select name="nation">
                              <option value="Singapore">Singapore</option>
                              <option value="Malaysia">Malaysia</option>
                              <option value="Thailand">Thailand</option>
                              <option value="Indoensia">Indonesia</option>
                              <option value="Philippines">Philippines</option>
                            </select>
                    </td>
            </tr>
            <tr>
                    <td></td>
                    <td>
                            <br><input type="reset" value="Cancel">
                            <input type="submit" name="result" value="Submit" onclick="checkFields()"/>
                    </td>
            </tr>
            </table>
    </form>

    <div id="divTable"></div>
 </body>
</html>

This is my javascript file, function.js:

function checkFields(){

var name = document.getElementById("name");
var address = document.getElementById("address");
var phone = document.getElementById("Phone");

 if(confirm('Do you want to submit')){
  if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
   alert("Please fill in all your details.");
   return false;
  }
  else{
   var page = "database.php";
  var xmlhttp = new XMLHttpRequest();

  if(xmlhttp==null){
   alert("Your browser does not support AJAX!");
   return false;
  }
   xmlhttp.onreadystatechange=function(){
   document.getElementById("divTable").innerHTML=xmlhttp.responseText;
   }
  xmlhttp.open("GET", page, true);
  xmlhttp.send(null);
  }
 }
 else{
  return false;
 }
}

This is my PHP file, database.php:

<?php
    // Define database parameters //
    DEFINE ('DB_USER' ,'iqwer222');
    DEFINE ('DB_PASSWORD', 'wfwqr');
    DEFINE ('DB_HOST', 'localhost');
    DEFINE ('DB_NAME', 'aqwfvaqf');

    $table_info = "info";

    // Connect to database
    $conn = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die ('Could not connect to Database:'. mysql_error());
    @mysql_select_db (DB_NAME) OR die ('Could not select the Database: '.mysql_error());

    // Delete Row
    if(isset($_POST['delete'])){
     $id = $_POST['deleteRow'];
     $query_string = "delete from $table_info where user_id='$id'";
     $result = @mysql_query($query_string);
     }

    //Check if phone no. is duplicate and if not, insert data
    if(isset($_POST['result'])){
    $phone = $_POST['phone'];
    $query_string = "select phone from $table_info where phone='$phone'";
    $result = @mysql_query($query_string);
    $num_row = mysql_num_rows($result);
    if($num_row){
     echo "A same phone number has been found. Please enter a different phone number.";
    }else{
    $query_string = "insert into $table_info(name, address, phone, gender, nation) values('".$_POST['name']."','".$_POST['address']."','".$_POST['phone']."','".$_POST['gender']."','".$_POST['nation']."')";
    $result = @mysql_query($query_string);
     }
    }

    // Display table
    $query_string = "select * from $table_info";
    $result = @mysql_query($query_string);
    $num_row = mysql_num_rows($result);

    if($num_row){
     echo "<table border=1>";
     echo "<tr><th>Name</th><th>Address</th><th>Phone no.</th><th>Gender</th><th>Nationality</th><th>Created</th><th>Modified</th><th>Action</th></tr>";

             while($row = mysql_fetch_array($result)){
             echo "<tr><td>", $row['name'], "</td>";
             echo "<td>", $row['address'], "</td>";
             echo "<td>", $row['phone'], "</td>";
             echo "<td>", $row['gender'], "</td>";
             echo "<td>", $row['nation'], "</td>";
             echo "<td>", $row['createdTime'], "</td>";
             echo "<td>", $row['modifiedTime'], "</td>";
             ?>

            <!--Delete button-->
            <td><form id="delete" method="post" action="">
            <input type="hidden" name="deleteRow" value="<?php echo $row['user_id'] ?>"/>
            <input type="submit" name="delete" value="Delete" onclick="return confirm('Are you sure you want to delete this contact?')"/></td></form></tr>

            <?php
             }
            echo "</table>";
            }
     else{
      echo "0 results";
    }
?>

    <form method="post" action="index.html">
    <input type="submit" name="goBack" value="Back"/>
    </form>
Viral Savaj
  • 3,379
  • 1
  • 26
  • 39
kross
  • 475
  • 1
  • 11
  • 31
  • Please insert following line in php file - echo "
    "; print_r( $_POST); die; then let me know array output
    – Prakash May 07 '15 at 06:41

1 Answers1

2

Considering that you database.php file is giving out correct data back.

a) Error :-

You are not using return false on form submit handler , just add return false and things will work for you

b) Suggestion

1) You are attaching the checkFields() function 2 times, once on submit button click and other on form submit, remove one of them(use sumbit)

2) User below callback in onreadystatechange , the one you have done will work but it is not correct as this callback get called mulitple times

       xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
          document.getElementById("divTable").innerHTML=xmlhttp.responseText;
        }
       }

Example Code below :

    <html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css"/>
        <script >
        function checkFields(){

    var name = document.getElementById("name");
    var address = document.getElementById("address");
    var phone = document.getElementById("Phone");

     if(confirm('Do you want to submit')){
      if(name == null, name == ""||address == null, address == ""||phone == null, phone == ""){
       alert("Please fill in all your details.");
       return false;
      }
      else{
       var page = "database.php";
      var xmlhttp = new XMLHttpRequest();

      if(xmlhttp==null){
       alert("Your browser does not support AJAX!");
       return false;
      }
       xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
          document.getElementById("divTable").innerHTML=xmlhttp.responseText;
        }
       }
      xmlhttp.open("GET", page, true);
      xmlhttp.send(null);
      }
     }


     return false;
    }
        </script>
    </head>

    <body>
        <form name="infoForm" method="post" onsubmit="return checkFields()"  action="">
                <table>
                <tr>
                        <td>Name:</td>
                        <td><input type="text" name="name" id="name" maxlength="40"></td>
                </tr>
                <tr>
                        <td>Address:</td>
                        <td><textarea maxlength="45" name="address"id="address" ></textarea></td>
                </tr>
                <tr>
                        <td>Phone:</td>
                        <td><input type="text" name="phone" id="phone"  maxlength="20"><br></td>
                </tr>
                <tr>
                        <td>Gender:</td>
                        <td><input checked type="radio" name="gender" id="male" value="Male">Male
                        <input type="radio" name="gender" id="female" value="Female">Female</td>
                </tr>
                <tr>
                        <td>
                                Nationality:
                        </td>
                        <td>
                                <select name="nation">
                                  <option value="Singapore">Singapore</option>
                                  <option value="Malaysia">Malaysia</option>
                                  <option value="Thailand">Thailand</option>
                                  <option value="Indoensia">Indonesia</option>
                                  <option value="Philippines">Philippines</option>
                                </select>
                        </td>
                </tr>
                <tr>
                        <td></td>
                        <td>
                                <br><input type="reset" value="Cancel">
                                <input type="submit" name="result" value="Submit" />
                        </td>
                </tr>
                </table>
        </form>

        <div id="divTable"></div>
     </body>
    </html>
sanjeev
  • 4,405
  • 2
  • 19
  • 27
  • Thank you, however that brings me to my unanswered question which whether my delete button in database.php would work or not. I tested it out and it seems if I try to delete a row, the page would somehow be refreshed. And strangely even though I commented out the "Back" button in still appears. Data doesn't seem to be entered into the table too. – kross May 07 '15 at 07:34
  • your button will work , in case you have mentioned you have attached function like `onclick ="testFunction()" ` , for better understanding view the thread `http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements` – sanjeev May 07 '15 at 07:38
  • The "Back" button was just my cache btw. Noted, will visit the thread, thanks for all the help! – kross May 07 '15 at 07:43