I'm creating a contest sign-up page for our annual math competition at my school. It requires some AJAX like behavior when you click and select an item in a dropdown list.
I've gotten an event to fire when I select something in the dropdown (I'm currently showing an alert box):
<script type="text/javascript">
$(function() {
$("#student").change(onStudentChange);
});
function onStudentChange()
{
alert("Dropdown changed");
}
</script>
What this needs to do, is do an asynchronous call to the server to get a list of contests that student is currently registered for.
I know I need to do a jquery ajax call. So I think my onStudentChange() function would look like this:
$.ajax({
type : 'POST',
url : 'get_registered_events.php',
dataType : 'json',
data: {
studentid : $('#student').val()
},
success : function(data){
// Do something once we get the data
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
// Display error
}
});
return false;
});
So I went ahead and created the get_registered_events.php
, which I want to return the events the student is registered for.
My problem is, I'm not experienced with PHP and I'm having difficulty figuring out how I would return the data the database gave me to this ajax call in the JSON format. Another snag I have is our school is using a very old version of PHP so I have to use this PEAR JSON library.
Here is that PHP file I'm having trouble with:
<?php
if (!empty($_POST['studentid')) {
include_once('JSON.php');
$json = new Services_JSON();
$dbconn = pg_connect("host=somehost dbname=somedb user=someuser password=somepassword") or die('Could not connect: ' . pg_last_error());
$query = 'SELECT contest.id, contest.title, FROM contest, student_contest WHERE student_id = '.$_POST['studentid'].' AND contest.id = contest_id';
$contests = pg_query($query) or die('Query failed: ' . pg_last_error());
// Here I need to convert the rows of $contests (contest.id, contest.title), into JSON and return it to that ajax call.
}
?>
So my question is, how do I convert $contests (its rows), into JSON (contest.id, contest.title), and return that back to the ajax call that will make it above.
If anyone could point me in the right direction I would really appreciate it.