0

Currently I'm creating a simple calendar with javascript and php using mysqli so I'm trying to pass all my records from database to a variable in javascript so that I can use it to display in my calendar to show a date as event when I click the date which is the 25th it will display the data.

this is my database I want to display

My php code

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "calendar";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
$sql = "SELECT * FROM bootstrap" ;
$result = mysqli_query($conn,$sql);
$myArray = array();
    
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $myArray[] = $row['title'];                   
    }
} 
else {
    print_r ($myArray); 
}
?>

Here is the part of my javascript I want to pass the result from my query

Javascript code

  //here I want to pass the array result from my query in php     
  var codropsEvents = {
 '08-25-2021' : '<span>New Year\'s day</span>',
 '11-23-2021' : '<span>Second Event</span>,
 '12-2-2021'  : '<span>Last Event</span>   
  };
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • I think if you did a little research on AJAX that would suit this situation quite nicely – RiggsFolly Aug 29 '21 at 14:17
  • Create the PHP array in the format you want (with the date in the correct format as key) and use `json_encode()` to turn it into a JS object. Then you can can do as @RiggsFolly suggested, call your PHP using Ajax from JS to get the result. – M. Eriksson Aug 29 '21 at 14:17
  • @MagnusEriksson ok thank you I will try to do what you said Im just a little bit confused on using the json_code() but I will try to look some for some example – Newbie Self Study Developer Aug 29 '21 at 14:30
  • [json_encode()](https://www.php.net/manual/en/function.json-encode.php) is what you need to use to turn the PHP array into a proper JS object. – M. Eriksson Aug 29 '21 at 17:16
  • @MagnusEriksson Yes I made the result from my query as a json_encode() now my new problem is how will I put it inside my variable as array? like this var codropsEvents = { '08-25-2021' : 'New Year\'s day', '08-26-2021' : 'New Event 1', '08-27-2021' : 'New Event 2'}; – Newbie Self Study Developer Aug 29 '21 at 17:32
  • @MagnusEriksson Ive been trying this var text = ' '; var myArr = JSON.parse(text); for(var i = 0; i < myArr .length; i++) { var obj = myArr[i]; console.log(obj); var codropsEvents = new Object(); codropsEvents.obj = ''+ obj +''; } but it doesnt work – Newbie Self Study Developer Aug 29 '21 at 17:36

0 Answers0