lpares12
lpares12

Reputation: 4013

Receive ajax response in a website mvc

So I have 3 files now (a View, which consists of a list.js and list.php, and a Controller which consists of a get_data.php file).

get_data.php:

<?php
   $str_json = file_get_contents('php://input');
   $data = json_decode($str_json, true);
   $token = $data['token'];
   $request = $data['request'];
   echo "<p>" . $request . "</p>";
?>

list.js:

function getItems(list) {
  var http = new XMLHttpRequest();
  var url = "../model/get_data.php";
  var dataPost = {"token" : true, "request": list};
  var str_json = JSON.stringify(dataPost);

  http.open("POST", url, true);

  http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  http.setRequestHeader("Content-length", dataPost.length);
  http.setRequestHeader("Connection", "close");

  http.onreadystatechange = function() {
      if (http.readyState == 4 && http.status == 200) {
          document.getElementById("show").innerHTML = http.responseText;
      }
  };
  http.send(str_json);
}

window.onload = getItems("start");

list.php:

<some html code>
<body>
   <span id="show" ></span>
</body>
<some more code>

I'm trying to implement the Model-View-Controller pattern, but I don't know how I'd transfer the 'echo' which is inside the 'get_data.php' file to the view.

Note that the <span> tag in the list.php file is the one showing the changing text

Upvotes: 0

Views: 49

Answers (1)

Tekay37
Tekay37

Reputation: 559

I guess what you need is just "include" your view into your controller via require_once() like this:

get_data.php:

<?php
    $str_json = file_get_contents('php://input');
    $data = json_decode($str_json, true);
    $token = $data['token'];
    $request = $data['request'];
    //echo "<p>" . $request . "</p>"; -- don't echo anything in the controller
    require_once('item.php');
?>

item.php:

<p>
  <?php echo $request ?>
</p>

require_once() will include the file just there so your scope doesn't change.

Upvotes: 1

Related Questions