Lo Dennis
Lo Dennis

Reputation: 33

Unable to get data by sending html request

I am a beginner of php and I tried to write a php file to scrape data from internet and display it in the html file through ajax. My problem is: I get no problem when scraping data and storing them in my database in back-end side. Everything is fine.

But when I try to send data to my html file through ajax, after html send a request to the php file, I receive a warning message which I don't know how to fix it.

Uncaught SyntaxError: Unexpected token '<', "<br />
<b>"... is not valid JSON
    at JSON.parse (<anonymous>)
    at Object.success (index.html:262:17)
    at c (jquery-3.6.0.min.js:2:28327)
    at Object.fireWith [as resolveWith] (jquery-3.6.0.min.js:2:29072)
    at l (jquery-3.6.0.min.js:2:79901)
    at XMLHttpRequest.<anonymous> (jquery-3.6.0.min.js:2:82355)

Here is my php file. I scrape data first and then store them in my database. After that, I retrieve data I need and encode them into JSON. (I am very sure that my php file can run smoothly)

<?php
        // The codes above scrape data from internet...
        // The codes above scrape data from internet...
        // The codes above scrape data from internet...
        // The codes above scrape data from internet...


        $link=mysqli_connect("localhost","root","A12345678","bulletins translator");
        $arr = array();

        $sql =  "SELECT * FROM `daily bulletins`";
        $result = mysqli_query($link, $sql);

        while ( $row = mysqli_fetch_row($result) ) 
        {
            array_push($arr, $row[0], $row[1], $row[3]);
        }
        echo json_encode($arr,JSON_UNESCAPED_UNICODE);
        $link->close();
?>

Here is the output(json object) that I want.enter image description here

I want to display them in my html file for further usage. The error pops up in the line

"$.each(JSON.parse(data), function (key, val) ".

And here is my html file.

<script> 
$(document).ready(function() 
{
        $.ajax(
        {
            type: 'POST',
            url:  'DataProcessor2.php',
            
            success: function(data) 
            {
                var bulletin_array = [];
                $.each(JSON.parse(data), function (key, val) 
                {
                    console.log(val);
                    bulletin_array.push(val);
                });

                // And the codes continues here...
                // And the codes continues here...
                // And the codes continues here...
                // And the codes continues here...
            }
        });
}
</script>

I google my problem and find a similar case (text). Yet, I have tried the suggestion from Ninja Work but the error still persists. I did add "echo json_encode($arr);" at the end of the script but it does not help at all.

Which step I was wrong and create the problem? Any suggestion would be appreciated.

Upvotes: 0

Views: 34

Answers (0)

Related Questions