Skip to content

Instantly share code, notes, and snippets.

@MontealegreLuis
Created February 7, 2013 16:38
Show Gist options
  • Save MontealegreLuis/4732220 to your computer and use it in GitHub Desktop.
Save MontealegreLuis/4732220 to your computer and use it in GitHub Desktop.
Ajax example
<!DOCTYPE HTML>
<html>
<body>
<form>
<select name="courses" id="courses">
<option value="">Select a course</option>
<option value="1">JavaScript</option>
<option value="2">PHP</option>
<option value="3">HTML &amp; CSS</option>
</select>
</form>
<div id="courseDetails"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#courses').on('change', function(event) {
var selectedCourseId = $('#courses').val();
if ($.trim(selectedCourseId) !== '') {
$.ajax({
url: "process-courses.php",
dataType: 'json',
data: {courseId: selectedCourseId},
success: function(response, textStatus, jqXHR) {
var html = '<h2>' + response.name + '</h2>'
+ '<p>' + response.description + '<p>';
$('#courseDetails').html(html);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
});
</script>
</body>
</html>
<?php
$courseId = filter_var($_GET['courseId'], FILTER_VALIDATE_INT);
//This values are from your database
// SELECT * FROM data....;
$courseInfo = array(
1 => array('name' => 'JavaScript', 'description' => 'Introduction to Javascript'),
2 => array('name' => 'PHP', 'description' => 'Introduction to PHP'),
3 => array('name' => 'HTML & CSS', 'description' => 'Introduction to HTML & CSS'),
);
//You should also check if the ID exists...
$response = json_encode($courseInfo[$courseId]);
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo $response;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment