deuseux12 deuseux12 - 1 year ago 71
Javascript Question

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).


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


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);"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;

window.onload = getItems("start");


<some html code>
<span id="show" ></span>
<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
tag in the
file is the one showing the changing text

Answer Source

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


    $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


  <?php echo $request ?>

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download