rudawg
rudawg

Reputation: 73

Processing JSON output from mysql through php

Ok so i managed to figure out the php code and it is working and is outputting in the right json format when i view it in browser. Here's the code thanks to help from Starx:

<?php
include ("Includes/dbConnect.php");

$_GET['date'];

$query2 = "SELECT * FROM events";
$checkevent = mysqli_query($cxn,$query2) or die("Couldn't execute query!");
$dates = array();
    while ($row2 = mysqli_fetch_array($checkevent))
        {
        $eventDate = $row2['eventDate'];
        $eventName = $row2['eventName'];
        $eventHost = $row2['host'];

        $dates[$eventDate] = array('title' => $eventName, 'desc' => $eventHost);

        }
    echo json_encode(array("dates" => $dates));
?>

this outputs: {"dates":{"2012-03-16":{"title":"Table Quiz","desc":"MSU"},"2012-03-20":{"title":"Welcome","desc":"Me"}}}

So there has to be a problem with my jquery code. i altered it as to Starx's specifications but still nothing, anyone have any ideas??

    <script type="text/javascript">
    $(document).ready(function() 
 {
$("#ical").ical({ 


beforeMonth:function(date)
    {
        $.ajax({
            type: "GET",
            url: "getCalendarEvents.php",
            dataType: "json",
            data: "date="+date,
            async: false, //stop rendering the calender until eventdates is changed.
            success: json.each(function(k,v){
                $.fn.ical.changeEventDates(v); //this function changes the eventdates
            }   
        })
    }   
});
});

</script>

Upvotes: 1

Views: 582

Answers (2)

Starx
Starx

Reputation: 78971

Make sure there is no futher operation after you echo the encoded json. So use an exit() at the end to confirm this

echo json_encode($dates);
exit;

Updates

On that case, notice that you are using two dimensional array for $date. When using $date[] = array(..) So you have to access it like

json.each(function(k,v) { 
    //Now v will hold the json format 
    $.fn.ical.changeEventDates(v);
});

Update 2

{"dates":{"eventDate":{"title": "eventName", "desc": "eventHost"}, "eventDate": {"title": "eventName", "desc": "eventHost"}}}

This format is not quite possible, since every item has same key eventDate. You can do it another way. Change up the following in the php

echo json_encode(array("dates" => $dates));
exit;

Now , json in your success function will hold similar format

function(json){
   // This will hold the json is this format
   // {"dates":{ 0 :{"title": "eventName", "desc": "eventHost"}, 1 : {"title": "eventName", "desc": "eventHost"}}}
   // Note the numeric indexing
}   

Upvotes: 1

Christopher Pelayo
Christopher Pelayo

Reputation: 802

your code seems to be fine but the only thing is don't include any other output except for the json string, even the html headers, script and etc. it should only include the json string alone and no other else

Upvotes: 0

Related Questions