Solved

AJAX post submit actions

Posted on 2014-10-14
6
249 Views
Last Modified: 2014-11-03
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
Comment
Question by:William-B
6 Comments
 
LVL 8

Assisted Solution

by:Ahmed Merghani
Ahmed Merghani earned 167 total points
ID: 40381572
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
 
LVL 51

Assisted Solution

by:Julian Hansen
Julian Hansen earned 166 total points
ID: 40382090
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
 
LVL 33

Accepted Solution

by:
Slick812 earned 167 total points
ID: 40382428
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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:William-B
ID: 40390953
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
 
LVL 33

Expert Comment

by:Slick812
ID: 40391278
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 40391374
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now