简体   繁体   中英

Ajax post to php > get php variable with xmlhttprequest

I want to update my table with javascript every couple seconds.

So far I made an ajax post request to my update.php and trigger if is set. Then do a mysql query and put the resultset in a json variable .

After this i get it with a XMLHttpRequest .

The problem is that every XMLHttpRequest example uses echo json. But when I put my echo json in my isset post check it wont return anything anymore.

I think the problem is that it can't echo ?

This is my code:

PHP :

 if (isset($_POST["updateTable"])) { $result = mysqli_query($con,"SELECT * FROM users"); $row = mysqli_fetch_row($result); $rsArray[] = array(); while ($row) { $rsArray[] = $row; $row = mysqli_fetch_row($result); } echo json_encode($rsArray); } 

AJAX :

 var updateTable = "true"; setTimeout(function(){ $.ajax({ type: 'POST', url: '../EXT_PHP/update.php', data: { updateTable: updateTable } }); console.log(updateTable); }, 3000); 

xmlhttpRequest :

 setTimeout(function(){ var oReq = new XMLHttpRequest(); oReq.onload = function() { alert(this.responseText); }; oReq.open("get", "../EXT_PHP/update.php", true); oReq.send(); }, 3000); 

Have you Tried to set the header of you PHP Script to JSON?

header('Content-Type: application/json');

Note that the header must be set before the first output of your Programm (iE the first echo)

<?php
header('Content-Type: application/json');
if (isset($_POST["updateTable"])) {
        $result = mysqli_query($con,"SELECT * FROM users");
        $row = mysqli_fetch_row($result);

        $rsArray[] = array();
        while ($row) {
            $rsArray[] = $row;
            $row = mysqli_fetch_row($result);
        }
        echo json_encode($rsArray);
    }

if that doenst work still you should check if there has been any errors within the json_encode function, there are some problems with encoding by time. Use

echo json_last_error_msg();

for this.

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