简体   繁体   中英

Pulling value from rows, using Ajax and PHP

I created this small script, from what I have learned about Ajax + Javascript so far. I am running this in Chrome btw, so XMLHttpRequest(); should be working

PHP,

    $conn = new PDO('mysql:host=localhost; dbname=test', 'root', '')

    $stmt = $conn->query("SELECT text FROM ajax");
    foreach($stmt as $each){

?>

Ajax,

<script type='text/javascript'>

    var request = new XMLHttpRequest();
    request.open('GET', <?php echo $each['text']; ?>, false);
    request.send();
    console.log(request);

</script>
<?php } ?>

Now, in database test where tbl name is ajax I have rows id & text , in which text has three filled-in rows, but the ajax code is not showing me anything. It is not echoing anything at all, let alone update instantly, when I am adding texts in my rows. What am I doing wrong?

out.php

<?php
     $conn = new PDO('mysql:host=localhost; dbname=test', 'root', '')

     $stmt = $conn->query("SELECT text FROM ajax");
     echo json_encode($stmt);
?>

test.html

<script>
    var request = new XMLHttpRequest();
    request.open('GET', "http://mysite.com/out.php", false);
    request.onreadystatechange=function()
    {
        if (request.readyState==4 && request.status==200)
        {
             var data = JSON.stringify(request.responseText); //The data from the server will be in responseText
             //data now contains an array of JSON objects of your data
             for(i=0;i<data.length;i++) {
                 console.log(data[i].text);   //.text is a variable based on your MYSQL field
             }
        }
    }
    request.send();
    console.log(request);
</script>

First you need to make a php script that outputs the data straight out nothing else (as in the out.php section above) and then have the javascript script in a whole other page (as in the test.html section) and give the request.open call the url to out.php in the example above http://mysite.com/out.php , but replace that with your actual url to the out.php file, and since you are on localhost something like http://localhost/Portal/Test/out.php

First I would remove the foreach loop. Change it to the following:

echo json_encode($stmt);

That will give your AJAX request variable a JSON encoded object to work with. Currently your result variable from your AJAX request is only displaying the results within the console.

Maybe try changing console.log(request) to the follwing:

alert(JSON.stringify(request));

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