• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 308
  • Last Modified:

AJAX post submit actions

Hello,
I am currently writing a script which is supposed to take a user inputted registration form and if some of the information already exists in a database (MySQL) then copy it to a set of different fields on the form.  I am using AJAX to perform the action so the page doesn't have to reload but I am having some problems with it.  I'd also like to be able to return a generic error if something else goes wrong.  I think the code below will explain it better, I'm putting in comments of where I'm trying to make things happen.  My question is; what is the best way to have multiple actions happen?  I've gone through some tutorials but usually it's only a single operation which takes place when the AJAX request is performed.  Thanks in advance and let me know if you need any other information.
P.S. I am using Kohana as a framework, but I don't think that should matter for the actual AJAX programming.

public function action_register()
    {
        if( $this->request->is_ajax() )
        {
            $this->auto_render = FALSE;
        }
        if( $this->request->method() === Request::POST )
        {
          
            $user = new Model_User;
            $post = $this->request->post();


            if( $user->where( 'email', '=', $post[ 'Email' ] )->count_all() === 0 )
            {
                
                $userparams = array();
                $userparams[ 'first_name' ] = $post[ 'FirstName' ];
                $userparams[ 'last_name' ] = $post[ 'LastName' ];
                $userparams[ 'email' ] = $post[ 'Email' ];
                $userparams[ 'emailconf' ] = $post[ 'Emailconf' ]; 
                $userparams[ 'password' ] = $post[ 'Password' ];
                $userparams[ 'passconf' ] = $post[ 'Passconf' ];
                $usercheck = $user->validate_create( $userparams );

                try
                {
                    $usercheck->check();
                    $user->values( $userparams );             
                    $user->save();
                    $user->add( 'roles', ORM::factory( 'role' )->find(1) );
                    Auth::instance()->login( $this->request->post( 'Email' ), $this->request->post( 'Password' ) );
                    $this->redirect( 'userhome' );
                }
                catch( ORM_Validation_Exception $e ) // Registration validation error
                {   
                    // Return an error asking user to confirm correct values (possibly additional processing)
                }
            }
            else // Email exists
            {
                // Copy 'Email' value to 'LoginEmail' form element on main page.
            }

        }
        else
        {
            // Request was not a correct POST request
        }

Open in new window


Script Code:
$(document).ready( function()
{
    $( '#register_form' ).submit( function( e )
    {
        e.preventDefault();
        var fName = document.getElementById( "FirstName" ).value;
        var lName = document.getElementById( "LastName" ).value;
        var Email = document.getElementById( "Email" ).value;
        var Emailconf = document.getElementById( "EmailConf" ).value;
        var Pass = document.getElementById( "Password" ).value;
        var Passconf = document.getElementById( "PassConf" ).value;
        var dataString = 'FirstName=' + fName + '& LastName=' + lName + '& Email=' + Email + '& Emailconf=' + Emailconf + '& Password=' + Pass + '& Passconf=' + Passconf;
        $.ajax(
                {
                    type: "POST",
                    url: "index.php/register",
                    data: dataString,
                    success: function( data )
                    {
                        alert( data );
                        // Separate Email Copy and recheck form
                            
                        }
                    }
                    
                });
    });
});

Open in new window

0
William-B
Asked:
William-B
3 Solutions
 
Ahmed MerghaniCommented:
As the above code, you can create action functions as much as AJAX calls you need. For example:
ajax call register => function action_register
ajax call login => function action_login
ajax call logout => function action_logout
and so on.
But I have concern with the above code, in the ajax call in the "url", you need to specify your controller(class) that implements these actions functions'. For example if your class name is "Controller_Ajax", your calls should be something like this for "register":
url: "index.php/ajax/register"

Open in new window

For "login":
url: "index.php/ajax/login"

Open in new window

For "logout":
url: "index.php/ajax/logout"

Open in new window

0
 
Julian HansenCommented:
Why don't you use .serialize to serialize your form i.e.
$(document).ready( function()
{
  $( '#register_form' ).submit( function( e ) {
    e.preventDefault();
    var dataString = $(this).serialize();
    $.ajax({
      type: "POST",
      url: "index.php/register",
      data: dataString,
      dataType: "JSON",
      success: function( data ) {
        alert( data );
        // Separate Email Copy and recheck form
      }}
    });
  });
});

Open in new window

Next make your return type JSON (as shown above) and return an object to your AJAX function. You do this as follows
$d = array(); /* or stdClass some complex object */
// set up object / array / combination here
echo json_encode($d);

Open in new window

Now you can return multiple values to your calling function and then decide what you need to do with them in your AJAX success.
0
 
Slick812Commented:
greetings William-B, , effectively using an AJAX server request, requires you to know what is needed in the Three separate computer operations for every Ajax process. you seem to have no problem with collecting the page FORM inputs to send out in the first process as javascript with -
       var dataString =

However, in your second process on the PHP server, you do not have ANY code there to do anything to send back to the browser page for the third process in javascript.

For me to construct an AJAX processes, I usually start at the END with what I need to show the user on the page AFTER I get the server info back. This way I can know what separate chunks of data I need to get from the server (usually database query) and then use in the several places on the page to update or create <div> or <inputs> to inform the user of the server query result, this Includes the ERROR handling page output for queries that have zero rows returns or as you have an error as "invalid post".

since you on a successful "Add User" you redirect  as -
    $this->redirect( 'userhome' );
your AJAX development will be for ERROR control, you must determine the output to a user that is required for all three errors you have as -
// Request was not a correct POST request
// Email exists
// Return an error asking user to confirm correct values


you will need to know how many <input> and <div> updates, on each different server ERROR query , to construct your data returns from the server. There are many ways to "pack" separate error data elements into ONE text string to send back to the page from the server,  and julianH suggestion of -
    dataType: "JSON",
is a common one in jquery ajax. but you will need to know some about how to construct on server and then  separate in the javascript the chunks of different data that each of the different ERRORS can use.

I hope this helps you some, but getting and understanding of ajax is not so easy.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
William-BAuthor Commented:
Sorry about the delay in responding.  I got it working using all your solutions.  Thanks very much for all your input.  I have run into a problem though, when I debug the return message ("email" or such) it is extremely slow.  I'm running this on a local host so a connection shouldn't be a problem.  It's just when I click "submit" it takes about .5 - 1 second to return from the ajax call.  Does anybody know how to speed this up?  I know it's an asynchronous call, but there has to be some tweaks somewhere.  Thanks again.
0
 
Slick812Commented:
you say - "there has to be some tweaks somewhere"
??? ? ?
tweaks to what ?
how to speed up what? ?
you show us nothing we can evaluate, to try and help.
what code processes are you using?  the first browser code, , the second server php code, and the last JS .done code.
0
 
Julian HansenCommented:
If there is a delay in your response it is most likely in your server side process.

You need to look in your register code to see what could be causing the delay.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now