How to handle multiple requests through an Ajax API?
ajax, javascript, jquery
Solution
It can be everything from something quite simple, to something more complicated, how you write it is up to you, assuming you're the only one who's going to use the API, and as far as I know there are no standards set in stone for this kind of thing, but a good way to solve things like this is to create a convenience function, both clientside and serverside, say something like
function fetch(what, data) {
data.what = what;
return $.ajax({
url : '/my/ajaxapi.php',
data : data,
dataType : 'json'
});
}
And when you need something you do
fetch('users', {name : 'Bill'}).done(function(result) {
$('#user').text(result.text);
});
$('.zoidberg').on('click', function() {
var self = this;
fetch('zoidberg', {}).done(function(result) {
$(self).text(result.text);
});
});
on the serverside you have one file, and how you set it up depends on the language used, but say PHP, and you could of course get fancy with classes etc. or just do a simple if/else or switch/case
<?php
$key = $_GET['what']; // wrap in something that makes it safe
$res = Array();
switch($key) {
case 'users' :
// lookup in DB or something
$res['text'] = $username;
break;
case 'zoidberg' :
$res['text'] = " Why Must I Be a Crustacean in Love";
}
echo json_encode($res);
?>
It's just a quick example, but set it up so it fits what you're doing, and it can save you a lot of work, and you have everything in one place so it's easy to find and modify later, easy to add new things that can be gotten with ajax etc. and possibly only need to get resources, DB connection etc. once, and not in every file.
Problem
I have a large project that requires multiple functions to be processed through Ajax calls, so far I am using different files to handle each function call. I know there's got to be a better way to handle the requests through an API And what would be a standard practice for designing such an API in terms of structure? Thanks!