Retrive data from DB , make an array and send it to a .js file.

Hi guys.
I’m using this calendar
http://www.ldida.altervista.org/calendario/index2.html for a project of mine.

This calendar has this really simple file data.js

[code]var codropsEvents = {

'12-31-2016' : '<span>New Year\'s Eve</span>'

};[/code]

to send the date and events to the calendar.

I’ve made a form , a db and i’ve let a guest to insert events into the database.
Now i want to retrive the data from the database and the name of the event and to put those into the data.js so the calandar can show the event from the database.

To retrive the data from the database i use data.php
[php]<?php include ‘config.php’;
$sql = “SELECT str_data , occasione FROM Evento”;
$result = mysql_query($sql) or die (mysql_error());
if(mysql_num_rows($result) > 0)
{
while($fetch = mysql_fetch_array($result))
{
$data = date(“m-d-Y”, $fetch[‘str_data’]);
$occasione =($fetch[‘occasione’]);
echo "$data $occasione
";
} }
?>[/php]

The code works because the echo gives me the date form the DB in the form i want. Now, how i can pass those data to the data.js file?

You want to create an API that sends json data back.

There is not a simpler way? that’s the last thing i need to complete that webapp but i don’t manage how to put those data there from my database.

JavaScript operates on the client side, ie users machine. PHP operates on the Server before the user machine gets anything. You can print variables to the DOM (the html document), but in the long run this is tedious, fragile, and requires a lot of work when something changes.

Don’t be put off by the term API either, it’s not necessarily some big fancy extra application. A PHP file on your server that you can call that supply json data is also a (very basic) API.

So instead of fetching data.js you should fetch data.php

[php]// data.php

/*

  • Fetch the events from the DB (using PDO or Mysqli)
  • Then make sure your array looks like below
    */
    $events = [
    [
    ‘12-31-2016’ => ‘New Year’s Eve
    ],
    [
    ‘01-01-2017’ => ‘The morning after
    ]
    ];

// Output it as JSON
echo json_encode($events);[/php]

[hr]

Then we need to load it into the calendar.

If you visit http://www.ldida.altervista.org/calendario/index2.html and view source, you can find:

[php][/php]
This is the actual calendar script, you need to include this on your page. Note: you normally never want to modify 3rd party scripts. If you’re ever in a position where you feel you have to, reconsider - or ask someone. I suggest you open up your 3rd party code though and look at it, if you wonder how it works / how to use it. Many have sensible public methods you can call (like we do with setData further down), or good comments/instructions.

[php][/php]
This is the data.js file, you do not want to include this in your page.

Below these are the actual instantiation of the calendar.

[php][/php]

Here we can see one of the options is:

[php]caldata: codropsEvents,[/php]

“codropsEvents” simply refers to the variable created in the data.js file. So instead we do a GET request to data.php, and get our json data directly from there.

[php]caldata: function() {
$.get(“data.php”)
.done(function(data) {
$calendar.setData(data);
})
.fail(function() {
// fetching events failed. show an error to the user, if needed
});
return [];
},[/php]

Wow Jim , really thank you. It’s been 5 hours of work this afternoon, my eyes burn. Tomorow i’ll try your way. Sory if it seems those are “basics” but i’m studyng medicina and for me progamming is just an hobby ^^ I’ll tell you tomorrow if i managed to implement it.

Dear Jim, i’ve tryed following what you said.
I’ve included

wich is made of
[php]<?php
include ‘config.php’;

$query = mysql_query(“SELECT str_data ,occasione FROM Evento”);

$arraydata = array();
$arraynome = array();

while($row = mysql_fetch_assoc($query)){

$arraydata[] = date(“m-d-Y”, $row[‘str_data’]);
$arraynome[] = $row[‘occasione’];

}

$datanome = array_combine($arraydata, $arraynome);

print_r($arraydata);
print_r($arraynome);
print_r($datanome);

// Output it as JSON
echo json_encode($datanome);

?>[/php]

I get this

Array ( [0] => 04-20-2016 [1] => 05-14-2016 ) Array ( [0] => Compleanno [1] => Compleanno ) Array ( [04-20-2016] => Compleanno [05-14-2016] => Compleanno ) {"04-20-2016":"Compleanno","05-14-2016":"Compleanno"}

but then how do i format the array as

$events = [ [ '12-31-2016' => '<span>New Year\'s Eve</span>' ], [ '01-01-2017' => '<span>The morning after</span>' ] ];

Thank you for your patient

Null refers to the output you get from json_encode. You’re trying to encode $events, but it is not defined.

Regarding getting the output correct. You are currently just adding the $row data to the output array. You need to “shape” it into the format you want it to have.

[php]<?php
include ‘config.php’;

$query = mysql_query(“SELECT str_data ,occasione FROM Evento”);

$events = array();

while($row = mysql_fetch_assoc($query)) {
$date = new DateTime();
$date->setTimestamp($row[‘str_data’]);

$event = [
  $date->format('m-d-Y') => $row['occasione']
];

$events[] = $event;

}

// Output it as JSON
echo json_encode($events);[/php]

Here we create a DateTime object from the timestamp in str_data. Then create an event array with the date with a m-d-Y format as key, with the value of occasione. Then we add the event to the events array, and finally output all the events as json.

Jim sorry, i’ve edited my post because i managed to fix some thing before you answered , really sorry. Your coding is for sure better but the way i solved the problem is wrong?

[php]<?php
include ‘config.php’;

$query = mysql_query(“SELECT str_data ,occasione FROM Evento”);

$arraydata = array();
$arraynome = array();

while($row = mysql_fetch_assoc($query)){

$arraydata[] = date(“m-d-Y”, $row[‘str_data’]);
$arraynome[] = $row[‘occasione’];

}

$datanome = array_combine($arraydata, $arraynome);

print_r($arraydata);
print_r($arraynome);
print_r($datanome);

// Output it as JSON
echo json_encode($datanome);

?>[/php]

still the calendar doesn’t seems to get the events.
Here you have the data.php file http://www.ldida.altervista.org/calendario/js/data.php
and there the calendar http://www.ldida.altervista.org/calendario/index2.html

I’ve Also tryed your code and it says
“Parse error: syntax error, unexpected ‘[’ in /membri/ldida/calendario/js/data.php on line 12”

If you go to the dev console in your browser (F12), click the network tab and reload the page you can see all the requests for files. If you open data.php you can see the response you get on this file. JS needs a plain JSON response (nothing else)

You’re using a PHP version before they introduced short array syntax, just change $foo = []; to $foo = array();

Your code should work though, it just need to output what it’s supposed to :slight_smile:

Yes my code does work and the output is

Array ( [0] => 04-20-2016 [1] => 05-14-2016 [2] => 05-03-2016 ) Array ( [0] => Compleanno [1] => Compleanno [2] => Battesimo ) Array ( [04-20-2016] => Compleanno [05-14-2016] => Compleanno [05-03-2016] => Battesimo ) {"04-20-2016":"Compleanno","05-14-2016":"Compleanno","05-03-2016":"Battesimo"}

Should i keep that code or use your?
Also , when you said

I need to make another php with only the

 echo json_encode($datanome);

or the js will not read it?

I’ve also tryed deleting the
[php]print_r($arraydata);
print_r($arraynome);
print_r($datanome);[/php]

now the data.php return only

{"04-20-2016":"Compleanno","05-14-2016":"Compleanno","05-03-2016":"Battesimo"}

wich is the json string but the calendar wont show the events ç_ç

maybe the “intelligent guess” of content type in jquery isn’t as intelligent as one would hope.

Try to add this to your data.php file (after the opening <?php tag)

[php]header(‘Content-Type: application/json’);[/php]

The current setup you’re trying fails. Try to add a console.log(‘failed’) or some alert(‘fail’) into the fail block so you know the request fails. (the path to data.php is wrong)

Damn , my head hurts xD

In the index2.html page
I’ve tryed to change this

<script type="text/javascript" src="js/data.php"></script>

into this

<?php include 'data.php' ?>

I’ve also tryed to change the
index2.html into index2.php

i’ve added [php] header(‘Content-Type: application/json’);[/php]
into the data.php files but still doesn’t work ç_ç

edit: i’ve also added

.fail(function() { alert('fail') or console.log('failed') //tryed both });

but doesn’t show something.

You don’t want either of those.

This part of the javascript calls data.php

$.get("data.php") .done(function(data) { $calendar.setData(data); }) .fail(function() { alert('fail') });

But that’s the wrong path for data.php - you were correct on the path in the code you pasted above, it should be js/data.php

You probably want to have this in there, can’t hurt

I’ve tryed both to add
data.php on the same path as index2.html
or to change

$.get("js/data.php")

still the data are not loaded into the calendario why?

Also , when i run F12 on the browser it says
“data.php:1 Uncaught SyntaxError: Unexpected token :”

You’ll have to check for errors, I don’t have the site/environment to try code so the code supplied here is just as is / not tested. If you have the line that sets content type near the top of the PHP file then that side should be good. Then it’s just to figure out where it goes wrong in your javascript. Currently on the page you still include js/data.php as a script file, which breaks javascript execution

I’ve deleted all the others way of include the data.php file and i’ve left only the js/data.php in the script.
Yes: my data.php file start with the header.

this is an example of woking calendar
http://www.ldida.altervista.org/calendario2/index2.html

where i’ve just edited the data.js file into this

var codropsEvents = { '05-10-2016' : '<span>Christmas Day</span>', '05-15-2016' : '<span>New Year\'s Eve</span>' };

why that works and mine doesn’t?

If you look at the networks tab in your dev console you can see that you no longer request data.php, if it’s not attempting to load the data you won’t get far. Not sure what’s different there because some earlier versions of what you were doing did in fact request data.php

I just tried to manually run this in the console, and it seems to work (F12 -> console, copy paste, enter)

[php]$.get(“js/data.php”)
.done(function(data) {
$("#calendar").calendario().setData(data)
})
.fail(function() {
console.log(‘failed’)
});[/php]

You just need to figure out why it’s no longer trying to fetch data.php

Sponsor our Newsletter | Privacy Policy | Terms of Service