Jump to content

Ajax - Handling process scripts


bigdspbandj

Recommended Posts

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.

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.