简体   繁体   中英

Can't load data from the server using ajax call

I am pretty new to all of these technologies (php, knockout, and ajax).

I am trying to load data from phpMyAdmin DB but it seems like my ajax call is not executed. The loadData function in my js is called in HTML and it controls the visibility of the table in my UI. Meaning, the table will be visible only when there I get data from the server.

my html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="main.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
  <script type='text/javascript' src='knockout-2.2.0.js'></script>

</head>
<body>
<div class="container" data-bind="load: loadData()">

  <table data-bind="visible: people().length > 0" class="students">
      <thead>
          <tr>
              <th>Name</th>
              <th>Age</th>
              <th>Remove</th>
              <th>Update</th>
          </tr>
      </thead>
      <tbody data-bind="foreach: people">
          <tr>
              <td>
                  <span data-bind="text: name"></span>
              </td>
              <td>
                  <span data-bind="text: age"></span>
              </td>
          </tr>
      </tbody>
  </table>  
</div>
</body>
<script type='text/javascript' src='studentapp.js'></script>
</html>

js

var personModel = function(id, name, age){
  var self = this; //caching so that it can be accessed later in a different context
  self.id = ko.observable(id); //unique id for the student (auto increment primary key from the database)
  self.name = ko.observable(name); //name of the student
  self.age = ko.observable(age);
};

var model = function () {
var self = this;
self.people = ko.observableArray([]);
    self.loadData = function () {
    //console.log("AHAHAHAH");
     // alert("super");
     //fetch existing student data from database$(document).ready(function() {
     $.getJSON("refresher_save.php", function(data) {
        for(var x in data){
          //student details
          var id = data[x]['id'];
          var name = data[x]['name'];
          var age = data[x]['age'];

          //push each of the student record to the observable array for 
          //storing student data
          self.people.push(new personModel(id, name, age)); 
        }
     });
};

};

ko.applyBindings(new model());

php

<?php
$db = new mysqli('localhost', 'root', '', 'student');

$action = (!empty($_POST['action'])) ? $_POST['action'] : ''; //action to be used(insert, delete, update, fetch)
$student = (!empty($_POST['student'])) ? $_POST['student'] : ''; //an array of the student details

//check if the student is not an empty string
//and assigns a value to $name and $age if its not empty
if(!empty($student)){
  $name = $student['name'];
  $age = $student['age'];    
}

switch($action){
    default:
              //only select student records which aren't deleted
              $students = $db->query("SELECT * FROM students WHERE status = 1");
              $students_r = array();

              while($row = $students->fetch_array()){

                  //default student data
                  $id = $row['id'];
                  $name = $row['name'];
                  $age = $row['age'];

                  //update status
                  //its false by default since
                  //this is only true if the user clicks
                  //on the span
                  $name_update = false;
                  $age_update = false;

                  //build the array that will store all the student records
                  $students_r[] = array(
                      'id' => $id, 'name' => $name, 'age' => $age
                      );
              }

              echo json_encode($students_r); //convert the array to JSON string
            break;
}
?>

Can anyone help ?

I think this line:

<div class="container" data-bind="load: loadData()">

should say this instead:

<div class="container" data-bind="load: $root.loadData()">

To prove this out, in the browser console run the following:

ko.contextFor(document.body).$root

You should see your view model return as an object you can browse in the console.

You also may want to move your import for studentapp.js to the top of the code beneath your KO and JQuery imports.

As @A.Wolff suggested, I would put your code inside the success callback.

And, this code will not work, you need to reference the element you are iterating in the loop.

    <tbody data-bind="foreach: people">
      <tr>
          <td>
              <span data-bind="text: name"></span>
          </td>
          <td>
              <span data-bind="text: age"></span>
          </td>
      </tr>
  </tbody>

It should be:

    <tbody data-bind="foreach: people">
      <tr>
          <td>
              <span data-bind="text: $data.name"></span>
          </td>
          <td>
              <span data-bind="text: $data.age"></span>
          </td>
      </tr>
  </tbody>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM