Jump to content

Recommended Posts

Okay, so I'm trying to use a tutorial I found to validate my information using Ajax and javascript and the jquery library. I'm completely new to javascript and haven't a clue how any of it works (I usually only use PHP).

 

Here is the tutorial: http://jqueryfordesigners.com/using-ajax-to-validate-forms/

 

Here is the code I'm using

 

<?php
    $message = '';
    $error = array();
    
    // we'll fake the database check, the following names won't be available.
    $taken_usernames = array(
        'remy',
        'julie',
        'andrew',
        'andy',
        'simon',
        'chris',
        'nick'
    );

    // main submit logic
    if (@$_REQUEST['action'] == 'register') {
        $resp = check_username($_REQUEST['username']);
        
        if ($resp['ok']) {
            $message = 'All details fine';
        } else {
            $message = 'There was a problem with your registration details';
            $error = $resp;
        }
    } else if (@$_REQUEST['action'] == 'check_username' && isset($_SERVER['HTTP_X_REQUESTED_WITH'])) {
        // means it was requested via Ajax
        echo json_encode(check_username($_REQUEST['username']));
        exit; // only print out the json version of the response
    }
    
    function check_username($username) {
        global $taken_usernames;
        $resp = array();
        $username = trim($username);
        if (!$username) {
            $resp = array('ok' => false, 'msg' => "Please specify a username");
        } else if (!preg_match('/^[a-z0-9\.\-_]+$/', $username)) {
            $resp = array('ok' => false, "msg" => "Your username can only contain alphanumerics and period, dash and underscore (.-_)");
        } else if (in_array($username, $taken_usernames)) {
            $resp = array("ok" => false, "msg" => "The selected username is not available");
        } else {
            $resp = array("ok" => true, "msg" => "This username is free");
        }

        return $resp;        
    }
?>

   <script src="<?php echo HTML_PATH; ?>public/js/jquery.js" type="text/javascript"></script>
   
   <?php if (!isset($_REQUEST['nojs'])) : ?>
    <script type="text/javascript">
    <!--
  $(document).ready(function () {
  var validateUsername = $('#validateUsername');
  $('#username').keyup(function () {
    var t = this; 
    if (this.value != this.lastValue) {
      if (this.timer) clearTimeout(this.timer);
      validateUsername.removeClass('error').html('<img src="<?php echo HTML_PATH; ?>images/ajax/ajax-loader.gif" height="16" width="16" /> checking availability...');
      
      this.timer = setTimeout(function () {
        $.ajax({
          url: 'Iindex.php?action=register',
          data: '&action=check_username&username=' + t.value,
          dataType: 'json',
          type: 'post',
          success: function (j) {
            validateUsername.html(j.msg);
          }
        });
      }, 200);
      
      this.lastValue = this.value;
    }
  });
});

    //-->
    </script>
<?php endif ?>

<?php



if (isset($_POST['submitted'])) {
        // Database stuff goes here
} 


else {
?>
<div class="register">
<?php if ($message) : ?>
        <p id="message"><?=$message?></p>
<?php endif ?>
<fieldset title="Register">
<legend><heading>Register<heading></legend>
<form action="<?php $_SERVER['PHP_SELF']; ?>?action=register" method="POST">
<table width="300" height="200">
  <tr>
    <td><div align="right">First Name:</div></td>
    <td><input name="firstname" type="text" size="20" maxlength="30"></td>

  </tr>
  <tr>
    <td><div align="right">Last Name:</div></td>
    <td><input name="lastname" type="text" size="20" maxlength="30"></td>
  </tr>
  <tr>
    <td width="120"><div align="right">Username:</div></td>
    <td width="180"><input type="text" name="username" value="<?=@$_REQUEST['username']?>" id="username" /></td>
    <td><span id="validateUsername"><?php if ($error) { echo $error['msg']; } ?></span></td>
  </tr>
  <tr>
    <td><div align="right">Password:</div></td>
    <td><input name="password" type="password" size="20" maxlength="30"></td>
  </tr>
   <tr>
    <td><div align="right">Confirm Password:</div></td>
    <td><input name="confirmpassword" type="password" size="20" maxlength="30"></td>
  </tr>
   <tr>
    <td><div align="right">Email:</div></td>
    <td><input name="email" type="text" size="20" maxlength="30"></td>
  </tr>
  
  <tr>
    <td><input name="submitted" type="hidden" value="1"></td>
    <td><input name="submit" type="submit" value="Register"></td>
  </tr>
</table>
</form>
</fieldset>
</div>
<?php
     ;
 	} 

     ?>

 

This is already inside the index.php page (index.php?action=register). I haven't a clue why it isn't working. I've only put the extra stuff on the username at the moment and it comes up with "checking availability" when you click it and never changes.

 

Sorry if I haven't explained this well. Can anyone help me fix this or point me to another tutorial/way of doing this that is easier?

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/107257-ajax-validation/
Share on other sites

jquery is a javascript framework that makes the ajax call a lot easier then the regular ajax. look at the following line in your js code

url: 'Iindex.php?action=register',

this will call your file Iindex.php and will return a value in text format

 

Link to comment
https://forums.phpfreaks.com/topic/107257-ajax-validation/#findComment-550051
Share on other sites

Okay new problem too. For some reason, this code at the top of the page stops the message from updating dynamically (found out through trial and error):

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

 

anyone know why?

Link to comment
https://forums.phpfreaks.com/topic/107257-ajax-validation/#findComment-550063
Share on other sites

the page you are requesting should only give the info you want on your main page so all the html stuff you remove your ajax page should be just text

 

for example

<?php
foreach($namearray as $name ){
    echo($name);
}
?>

actually you probably want to get an array which is more complicated but first make this work from there on you can progress

Link to comment
https://forums.phpfreaks.com/topic/107257-ajax-validation/#findComment-550081
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.