Jquery/Ajax to get database using php

Viewed 136

I have an HTML page that is too big to post on here, however I'll just post the ajax/jquery I am using to try and access the PHP file variables.

threadPage.html

<script type="text/javascript">
            
        $.ajax({
        url : '/ThreadCreation.php',
        type : 'POST',
        data: {'titles': titles}
        crossDomain: true,
        dataType : 'jsonp',
        success : function (data) {
           console.log(data) /
        },
        error : function () {
           alert("error");
        }
    })  

</script>

<!-- bunch of html -->

So essentially I am trying to get the variable from the ThreadCreation.php in JSON form. It should be in an array so that I can loop through it in the HTML file.

ThreadCreation.php

<?php

    $username = 'root';
    $password = '';
    $db = 'main_database';

    $conn = mysqli_connect('localhost', $username , $password,$db);
    
    if (!$conn){
        die("unable to connect");
    }

    
   $sql = mysqli_query($conn, "SELECT title FROM thread");

   while($row = mysqli_fetch_array($sql)) {
   $titles[] = $row['title'];

   echo json_encode($titles);
?>

I will repeat though, that this HTML file is only getting information from the database through PHP. So there is no form submission here.

I keep getting that 'titles is not defined'. This makes sense because there is not titles defined in the HTML, however I am unsure how to construct my ajax request to collect the data, as this format is all I have seen people use.

1 Answers

Mention empty array first just to prevent error in case you have no data in database then empty array will proceed.

$sql = mysqli_query($conn, "SELECT title FROM thread");

$titles = array();
while ($row = mysqli_fetch_array($sql)) {
    array_push($titles,$row['title']); // Push data in empty array
}
echo json_encode($titles);
Related