bigdspbandj Posted February 22, 2008 Share Posted February 22, 2008 I understand how ajax sends a request to a server side script and how it gets a response. A lot of my scripts are usually "process" scripts and follow this flow: user_interface.php (form leads to process script) process_data.php (script that processes form into database...) user_interface.php (back to user_interface via header() in proccess_data.php) I do this to keep file sizes down. Anyway how would I go about getting ajax to handle that kind of a script? Do I need to rewrite my scripts to be included as apposed to separate files that redirect? I am also trying to keep graceful degradation in mind. Quote Link to comment Share on other sites More sharing options...
roopurt18 Posted February 22, 2008 Share Posted February 22, 2008 Well, AJAX requests are initiated by JavaScript code that you write. They're not generally seen by the user and search engines don't care about them being friendly. So you could add a query string value named ajax. Then in your scripts: <?php $ajax = isset($_GET['ajax']) && $_GET['ajax'] == 1; if($ajax){ user_interface.php } process_data.php if($ajax){ $user_interface.php } ?> This is cumbersome in two ways though. The first is that you might have to change a lot of scripts. Your life is always much easier when using mod_rewrite to send everything through a single index.php file. That way global site stuff like this only has to be added in a single place. Secondly, the best way to respond back to AJAX requests is with JSON. If you are not familiar with JSON you should read up on it. If you are familiar with JSON, then you will have to come up with a way for your AJAX requests to output pure JSON in place of the normal user_interface.php stuff. For example, I typically respond with JSON that looks like: { ok : false, error : true, error_msg : 'E-mail required.' } Then my JavaScript can do something like: function ajax_handler(xhr){ var obj = eval( xhr.responseText ); if(obj.ok){ alert('success!'); }else if(obj.error){ if(obj.error_msg){ alert(obj.error_msg); }else{ alert('Unknown server error.'); } } } Hope that helps. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.