Created
November 9, 2015 23:26
-
-
Save pablotron/26398c6c9e09d24f92a0 to your computer and use it in GitHub Desktop.
kirth ajax example (test at http://pmdn.org/kirth/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
try { | |
# check for choice_id | |
if (!isset($_POST['choice_id'])) | |
throw new Exception('missing choice_id'); | |
# extract choice from request | |
$choice_id = $_POST['choice_id']; | |
# do shit with choice_id here | |
# build json-encoded result | |
$r = array( | |
'type' => 'application/json', | |
'body' => json_encode(array( | |
'foo' => rand(1, 100), | |
'choice_id' => $choice_id, | |
)), | |
); | |
} catch (Exception $e) { | |
# build error result | |
$r = array( | |
'type' => 'text/html', | |
'body' => htmlspecialchars($e->getMessage()), | |
); | |
} | |
# send header and body | |
header("content-type: {$r['type']}"); | |
echo $r['body']; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang='en-US'> | |
<head> | |
<meta charset='utf-8'/> | |
<title>Kirth AJAX Example</title> | |
</head> | |
<body> | |
<p> | |
<select id='choices'> | |
<option disabled selected>Choose...</option> | |
<option value='hi'>Hi!</option> | |
<option value='foo'>Foo</option> | |
<option value='bar'>Bar</option> | |
<option value='baz'>Baz</option> | |
<option value='blum'>Blum</option> | |
</select> | |
</p> | |
<p> | |
<b>Results:</b> | |
<ul id='results'> | |
<li>Foo: <span class='foo'></span></li> | |
<li>Choice: <span class='choice_id'></span></li> | |
</ul> | |
</p> | |
</body> | |
<script type='text/javascript' src='js/jquery-2.1.4.min.js'></script> | |
<script type='text/javascript' src='js/kirth.js'></script> | |
</html> | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
jQuery(function($) { | |
"use strict"; | |
// bind to change event | |
$('#choices').change(function() { | |
var choice_id = $(this).val(); | |
// log value | |
console.log('choice_id: ' + choice_id); | |
// make ajax request | |
$.post('choose.php', { | |
// request parameters | |
choice_id: choice_id, | |
}).fail(function(r) { | |
// display error | |
alert('Error: ' + r.responseText); | |
}).done(function(r) { | |
// process result | |
$('#results .foo').text(r.foo); | |
$('#results .choice_id').text(r.choice_id); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment