简体   繁体   中英

AJAX call the PHP script not outputting any results

I am trying to update my list of tweets via AJAX. I have ran the script on the page and know that script works, and I have a console.log line in my ajax call so I know that is getting hit as well.

    setInterval(function () {sendRequest()}, 5000);

    function sendRequest(){
        var xmlhttp;

        if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp=new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange=function(){
            if (xmlhttp.readyState==4 && xmlhttp.status==200){
                console.log("yay");
            }
        }

        xmlhttp.open("GET","getTweets.php",true);
        xmlhttp.send();

    }

My AJAX should run every 5 seconds, and the hit the PHP script to return new results that have been stored in the database. My PHP looks like:

$conn = mysqli_connect("localhost", "*", "*", "*");

if (!$conn) {
    echo("Connection failed: " . mysqli_connect_error());
}

$query = "SELECT * FROM tweets;";

$results = mysqli_query($conn, $query);

while($list = mysqli_fetch_assoc($results)){

echo '<div class="tweet-containter">';

echo '<img class="user-img" alt="user-img" src="images/gb.png">';
echo '<h3 class="tweet-username">@'.$list['username'].'</h3>';
echo '<p class="tweet-body">'.$list['tweetBody'].'</p>';   
echo '<p class="tweet-body">Tweeted: '.$list['datePosted'].'Retweet: <i class="fa fa-retweet" id="retweet4" onclick="retweetAJAX()"></i> Like: <i class="fa fa-thumbs-up" id="likes4" onclick="likeAJAX()"></i> Dislike: <i class="fa fa-thumbs-down" id="dislikes4" onclick="dislikeAJAX()"></i></p>';

echo '</div>';

}

This goes for those that do not understand ReadyState codes. You should know the following codes for ReadyState:

0: request not initialized 
1: server connection established
2: request received 
3: processing request 
4: request finished and response is ready

And Status Code

200: "OK"
404: Page not found

with that said, try doing this:

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
       if(xmlhttp.status == 200){
           console.log(xmlhttp.responseText);
       } else if(xmlhttp.status == 400) {
          alert('There was an error 400')
       } else {
           alert('something else other than 200')
       }
    }
}

ryandonohue,

PHP is a Hyper-Text Processor. PHP runs on your server & the results are generated before the page is loaded. You should not be using PHP to output results like HTML elements, it is much more appreciated if you use JavaScript to manipulate the Document Object Model (DOM).

Though, for your intermediate purposes you might not notice an immediate difference.

For PHP5 you should look into the usage of PHP-PDO http://php.net/manual/en/class.pdo.php to prevent SQL injection.

Modification:

function getall($table, $values, $conditions = null, $limit = null, $ascdesc = null){
        $values_str = "";
        foreach($values as $key => $value){
            $values_str .= $value . ", ";
        }
        $cond_str = "";
        $hascond = false;
        if($conditions != null){
            $hascond = true;
            foreach($conditions as $key => $value){
                $cond_str .= $key . "='" . $value . "' AND ";
            }
            $cond_str = rtrim($cond_str, " AND ");
        }
        $values_str = rtrim($values_str, ", ");
        $cond_str = " WHERE (" . $cond_str . ")";


        $orderby = "";
        $hasorder = false;
        if($ascdesc != null){
            $hasorder = true;
            foreach($ascdesc as $key => $value){
                $orderby = " ORDER BY " . $value . " " . $key;
                break;
            }
        }


        $sql = "SELECT " . $values_str . " FROM " . $table . " " . (($hascond)? $cond_str: "") . (($hasorder)? $orderby: "") . (($limit)? " LIMIT " . $limit: "");
        //echo $sql;
        $sql_prep = (new PDO('mysql:host=localhost;dbname=' . 'database', 'username', 'Password'))->prepare($sql);
        $sql_prep->execute();
        return $result = $sql_prep->fetchAll(PDO::FETCH_ASSOC);

    }

initialization: ( returns an array so you need to json encode)

getall('table',
    Array(
          '*'
     ),
     null, 5, null);

AJAX:

function ajax(file,type, params, func){
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                //xmlhttp.responseText
                func(xmlhttp.responseText);
            }
        }
        if(type.toLowerCase() != "post"){
            xmlhttp.open(
                type, file + "?" + params_to_get(params),
                true
            );
            xmlhttp.send();
        }else{
            xmlhttp.open(
                type, file,
                true
            );
            xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            xmlhttp.send(params_to_get(params));

Since you have an error code of readystate of 4 with a status of 500 i would say the issue is more with the compatibility of MYSQLi or the way your table is set up with your database.

check out this POST for more information about headers: Ajax call to PHP is returning nothing

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