Wednesday, August 3, 2011

Update web pages using the Asynchronous HTTP Request with jQuery in CodeIgniter

1. Create a web page that has in input box for the guest to enter their email address.

2. The page should load the javascript file, ready.js (which initializes jQuery.
When the onchange event is fired, it will send the contents of the input box to the ajaxCheck function.

3. This function will use the ajax $.post function provided through jQuery to send the str value to the server using asynchronious http calls. (note: you can write this yourself or use jQuery). Notice how the controller registration is called and routed to the checkID function. The checkID function queries the database and then returns a value that indicates what was found. These values are:
Current (the email is registered), Invalid (the email is not valid email account), True (user is not registered but in our contact list), False (user is not registered).

4. Finally it puts these values into a json array structure and sends it back to the javascript function that called it.

echo json_encode(array("returnValue"=>$value,"idValue"=>$id));

5. The callback function will have access to these two variables: data.returnValue and data.idValue;

With this information it can update the web page as appropriate. Use jQuery functions to rewrite elements and the page will not need to do a complete refresh.

The view file:

<html>
<head>
<script src="<?=base_url()?>/_lib/js/ready.js" type="text/javascript"></script>
</head>

<script >
function ajaxCheck(str) {
    //called by email input box
   
    $.post(
        "registration/checkID",
        { sendValue: str },

        function(data) {
            //this is the callback function that will receive the results from the php function on the server
            //alert(data.returnValue);
            $success = data.returnValue;
            $newid = data.idValue;
            switch ($success ) {
                case 'current':
                    //user is registered for the year
                    $('#displayMsg').text('You are already registered for 2011. Sign in to edit');
                    var href = jQuery(location).attr('href');
                    $('#signinbox').show();
                   
                    $('input[name="email"]').val(str);
                    //var tmpString = '<p><a href="'+href +'/unregister/'+$newid +'"> Unregister </a> for the workshop.</p>';
                    //$('#unregisterbox').html(tmpString);
                    //$('#unregisterbox').show();
                    break;
                case 'true':
                    //user is not registered yet, but they are in the rolls
                    $('#displayMsg').text('');
                    $('#oldUser').show();
                    $('#regForm2').show();
                    $('#regForm3').show();
                    break;
                case 'false':
                    //user is not registered and is new
                    $('#displayMsg').text(' Registration requires your name, zip code and organization');
                    $('#regForm2').show();
                    $('#regForm3').show();
                    break;
                case 'invalid':
                    $('#displayMsg').text(' oops...not a valid form of email');
                    break;
                default:
                    $('#displayMsg').text(' please register');
                    $('#regForm2').show();
                    $('#regForm3').show();
            }
        },
        "json"
    );
}

</script>
<body>

   
                    <label for="in_email" style="display:inline">Email </label>
                    <input type="text" id="in_email" name="in_email" onchange="ajaxCheck(this.value)" size=40 value="" />
               
                   
                   

</body>
</html>





And finally, some php for the controller and the server:

function checkID() {
        //this is called by the browser using ajax techniques via jQuery
        //IF USER IS REGISTERED FOR 2011, DROP OUT.
        //FIND USER IN DATABASE
        // returns true if it finds the email
        //returns false if it doesn't find the email
        //returns invalid if the email is bad
        //returns current if the email is registered for 2011
        $id = '';
        $email = strtolower($_POST['sendValue']);
        $this->load->helper('email');
        $this->load->database();

        if ($email != '' && valid_email($email) ) {       
            //CHECK if email is in use
            $this->db->where('active', '1');
            $this->db->where('email', $email);
            $attendees = $this->db->get('attendees');
            $attendee = $attendees->result();
            $count = count($attendee);

            if ( $count >= 1 ) {
                $value = 'true';
                //it is in use, see if //check if registered
                $id = $attendee[0]->id;
                $this->db->where('attendeeId', $id);
                $regged = $this->db->get('registrations');
                $reg = $regged->result();
                if ( count($reg ) >=1 ) {
                    //it is registered, see what year

                    $year = $reg[0]->workshopYear;
                    if ( $year == '2011') {
                        //crash and burn.  don't let them reregister. without signing in first
                        $value = 'current';
                    }
                }
            }  else  { $value = 'false'; }
        } else { $value = 'invalid'; }
        echo json_encode(array("returnValue"=>$value,"idValue"=>$id));
    }