2

I'm trying to get data from DB with PHP and export it to JSON file, I'm also trying to display it in my HTML file using AJAX but without success.

I tried to use external JS file and calling for it from Success in AJAX and I tried also to write the function into Success part.

What I did wrong ?

<!DOCTYPE html>
<html>

    <head>
        <title>DataBase Project - Tom Yahav</title>
            <link rel="stylesheet" href="include/style.css"/>
        <link rel="stylesheet" href="showTable.js"/>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
    </head>

    <header>
    <h1>Database - Students</h1>
    </header>

<body>
    <div id="wrapper">
        <nav class="navbar navbar-default">
  <div class="container-fluid">
    <div class="navbar-header"> </div>
    <div>
      <ul class="nav navbar-nav">
        <li><a href="index.html">Home</a></li>
        <li class="active"><a href="AddorRemoveStudents.html">Add/Remove Students</a></li>
        <li><a href="AddorRemoveTeachers.html">Add/Remove Teachers</a></li>
        <li><a href="AddorRemoveCourses.html">Add/Remove Courses</a></li>
        <li><a href="Sortby.html">Top 3 Students</a></li>
      </ul>
    </div>
  </div>
</nav>

<div class="container">
    <div class="insertData">
        <form class="form-horizontal">
  <div class="form-group">
    <label for="" class="col-sm-2 control-label">Student ID:</label>
    <div class="col-sm-10">
      <input type="number" class="form-control" id="" placeholder="Student ID">
      </div>
            </div>
    <div class="form-group">
    <label for="" class="col-sm-2 control-label">Student Name:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="" placeholder="Student name">
    </div>
  </div>
  <div class="form-group">
    <label for="" class="col-sm-2 control-label">Student Address:</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="" placeholder="Student Address">
    </div>
  </div>
  <div class="form-group">
    <label for="" class="col-sm-2 control-label">Student Birth Date:</label>
    <div class="col-sm-10">
      <input type="datetime" class="form-control" id="" placeholder="Student Birth Date">
    </div>
  </div>
<div class="rightButtons">
<button type="button" class="btn btn-success">Add</button>     
<button type="button" class="btn btn-danger">Erase</button>
<button type="button" class="btn btn-warning">Update</button>
</div>         
        </form> 
    </div>
    <br>
    <br>

  <script>
  $(function() {
    $("#posts").submit(function() {
      var txt = $("#txt").val();
      var title = $("#title").val();
      var dataString = 'txt=' + txt + '&title=' + title;       

      $("#loader").show();
      $("#loader").fadeIn(300).html('<span class="loading">Loading..</span>');

      $.ajax({
        type: "GET",
        url: "jsonStudent.php",
        data: dataString,
        cache: true,
        success: function(html){
          $("#loader").after(html);
          $("#loader").hide();
        }  
      });

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

    <form method="post" id="posts" action="">
      <input type="submit" value="Display Students" name="submit" class="btnSubmit">
    </form>
<div id="loader"></div>
<table id="table1">
  <thead></thead>
</table>

</div>
    </div>
    </body>
</html>

And the External JS file is:

function createTableByForLoop(data)
{
  var eTable="<table><thead><tr><th colspan='3'>Created by for loop</th></tr><tr><th>Name</th><th>Title</th><th>Salary</th</tr></thead><tbody>"
  for(var i=0; i<data.length;i++)
  {
    eTable += "<tr>";
    eTable += "<td>"+data[i]['name']+"</td>";
    eTable += "<td>"+data[i]['title']+"</td>";
    eTable += "<td>"+data[i]['salary']+"</td>";
    eTable += "</tr>";
  }
  eTable +="</tbody></table>";
  $('#forTable').html(eTable);
}

The PHP file:

    function printStudents() {
      $host="127.0.0.1";
      $port=3306;
      $user="root";
      $password="root";
      $dbname="courcessystem";

     $con = new mysqli($host, $user, $password, $dbname, $port)
        or die ('Could not connect to the database server' . mysqli_connect_error());


        $sql = "SELECT * FROM teacher";
        $result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($con));

        $emparray = array();
        while($row =mysqli_fetch_assoc($result)) {
            $emparray[] = $row;
        }

        echo json_encode($emparray);
        $con->close();   
    }   

    printStudents();

?>

Thank you!

8
  • 1
    what error you are getting in your browser console? Commented Jan 2, 2016 at 17:00
  • 4
    where are you calling the createTableByForLoop method inside the success ? Commented Jan 2, 2016 at 17:03
  • 1
    Please call createTableByForLoop(data) after ajax success Commented Jan 2, 2016 at 17:03
  • Just so that you're aware using the after method in your case would add the table twice. Also your Ajax success parameters are not correct so your not getting the data you're expecting Commented Jan 2, 2016 at 17:08
  • You can try to use console.log(html) to see what is being returned. Without the php I don't know what could go wrong, looks fine to me. Also try to use POST instead of GET. Commented Jan 2, 2016 at 17:14

1 Answer 1

1

Given that jsonStudent.php outputs something like:

[
    {
        "name": "X",
        "title": "X",
        "salary": 0
    }

]

Change the ajax code to something like this:

  $.ajax({
    type: "GET",
    dataType: "json",
    url: "jsonStudent.php",
    data: dataString,
    cache: false, // You don't want to use cache for this
    success: function(data){
      createTableByForLoop( data );
      $("#loader").hide();
    }  
  });

Also, #forTable doesn't exist in the html.

Sign up to request clarification or add additional context in comments.

6 Comments

I tried to change to your suggestion but I don't get the data from JSON file, I get : "Loading..."
Could you put console.log( data ); inside the success function and post what it prints?
On console.log I get this error: Uncaught ReferenceError: createTableByForLoop is not defined $.ajax.success @ AddorRemoveStudents1.html:88 c @ jquery.min.js:3 p.fireWith @ jquery.min.js:3 k @ jquery.min.js:5 r @ jquery.min.js:5 .
Ok good, the js-file containing createTableByForLoop must be loaded before this code. You don't load it at all.
I did it in Head part : <link rel="stylesheet" href="showTable.js"/>
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.