Solved

AJAX post submit actions

Posted on 2014-10-14
6
267 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 57

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 34

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
Independent Software Vendors: 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!

 

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 34

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 57

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

Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
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…

688 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