March 20, 2012

Processing JSON output from mysql through php

Question by rudawg

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>

Answer by Starx

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
}   

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!