0

I've been trying to retrieve data from a mysql table. My php script is as follows:

$mysqli = mysqli_connect($servername, $username, $password, $dbname);

$query = "SELECT * FROM $tablename";

$result = mysqli_query($mysqli, $query);

$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
$jsonData = json_encode($data);
echo($jsonData);

It is giving me this result when the php url is called from browser:

[{"id":"p1","image_data":"data:image\/jpeg;base64,largestring","image_status":"","image_returnedbit":""},{"id":"p2","image_data":"data:image\/jpeg;base64,largestring","image_status":"","image_returnedbit":""}]

(I have only two rows in the mysql table. The extra two columns in the array aren't processed atm) And I'm having a hard time trying to utilize that data. I have this html file (consistingg some css, html too but not included):

    $(function () {
    $("#button-get").click(function () {
        $.ajax({
            type: "GET",
            url: "https://www.example.com/myphpfile.php",  
            dataType: "",              
            success: function(response){ 
                // alert(response);
                // alert(response["id"]);
                console.log(response[0]);
                // $(".image-gallery").append(`<div class="image-single"><img src=${}></div>`);
            }
        });
    });
});

It seems like an array is being echoed, but logging response(0) gives [ and logging response(1) gives {. Please assist me if someone can :) would really appreciate. Any help is appreciated. Previously, I tried echo($data) on the php script, but it only showed a word Array on the browser and/on console log. I believe echo($jsonData) is sending a string which I'd have to play with to get values (splitting and removing certain characters). How can I achieve retrieving data that I can feasibly use on my html page?

1 Answer 1

1

this is because the ajax is treating the response as string not as json so you have two options either use JSON.parse(response) to convert the json string to json object or you need to set dataType to json

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so very much brother! Setting datatype to json worked perfectly :). Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.