Solved

Ajax to check form value in MySQL database

Posted on 2016-09-09
10
37 Views
Last Modified: 2016-09-10
I've used ajax a lot before, I just can remember details.

Here is what I need to do.

Use enters email & password on an html form.

form tag has "onSubmit = return chk_vals();"

In chk_vals I want to use ajax to run a php program on the server that looks up the entered email / password pair; if it finds a match it returns something I can use to disallow. If it DOES NOT find a match, OK.

I can write all the php / mysql. Just need the client side ajax (javascript).

I'd like a sample along these lines, I can "fill in the blanks". One thing I can't remember is how to the the php to "return" a value to the client.

Thanks
0
Comment
Question by:Richard Korts
  • 4
  • 4
  • 2
10 Comments
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
Can you use jQuery or do you need raw javascript?
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
Here is a working sample
HTML
<form id="login" class="form-horizontal">
<div class="form-group">
  <label for="username" class="col-sm-2 control-label">Username</label>
  <div class="col-sm-10">
	<input type="email" id="username" name="username" class="form-control" />
	<p class="alert alert-danger" style="display: none"></p>
  </div>
</div>
<div class="form-group">
  <label for="password" class="col-sm-2 control-label">Password</label>
  <div class="col-sm-10">
	<input type="password" name="password" class="form-control" />
  </div>
</div>
<div class="form-grouprow">
  <button class="btn btn-default col-sm-2 col-sm-offset-10" type="submit">Login</button>
</div>
</form>

Open in new window

jQuery
<script>
$(function() {
  // BIND TO BLUR OF username FIELD
  $('#username').blur(function() {
    // GET A REFERENCE TO THE STATUS MSG
    var status = $(this).next();
	
	// CLEAR ANY EXISTING ERRORS
    status.removeClass('alert-success alert-danger').hide();
	
    // CHECK IF THE USERNAME EXISTS
    $.ajax({
      url: 't1566.php',
      data: {action: 'chkemail', email: $(this).val()},
      type: 'POST',
      dataType: 'JSON'
    }).done(function(resp) {
	  // REPORT RESULT
      if (resp.success) {
        status.addClass('alert-success');
      }
      else {
        status.addClass('alert-danger');
      }
      status.html(resp.msg).show();
    });
  });
  
  // BIND TO FORM submit
  $('form').submit(function() {
    // GET THE FORM DATA AND SEND IT OFF
    var data = $(this).serialize() + "&action=validate";
    $.ajax({
      url: 't1566.php',
      data: data,
      type: 'POST',
      dataType: 'JSON'
    }).done(function(resp) {
      alert(resp.msg);
    });
    
    return false;
  });
});
</script>

Open in new window

PHP
<?php
// SETUP OUR RESPONSE OBJECT
// WITH SOME DEFAULT fail VALUES
$response = new stdClass;
$response->success = false;
$response->msg = 'invalid parameters';

// GET THE ACTION IF ONE EXISTS
$action = isset($_POST['action']) ? $_POST['action'] : false;

// CREATE A function REFERENCE
// WE PREPEND action_ TO THE ACTION
// TO PREVENT CRAFTY PERSONS OF DUBIOUS 
// INTENT FROM EXECUTING THINGS WE DON'T 
// WANT THEM TO EXECUTE
if ($action) {
  $function = "action_" . $action;
  
  // WE HAVE A FUNCTION FOR THIS ACTION 
  // SO CALL IT WITH OUR RESPONSE
  if (function_exists($function)) {
    $function($response);
  }
}

// RETURN THE RESULTS
die(json_encode($response));

// CHECK USERNAME / EMAIL IS NOT IN USE
function action_chkemail($response)
{
  // FUDGE SOME SUCCESS / FAIL VALUES
  $response->success = rand(1,2) % 2;
  
  // CREATE RETURN MSG BASED ON ABOVE
  $response->msg = $response->success ? 'Email is not being used' : 'Email already in use';

}

// VALIDATE THE FORM SUBMISSION
function action_validate($response)
{
  $response->success = rand(1,2) % 2;
  $response->msg = $response->success ? 'Email and Password are good to go' : 'Oops!' ;
}

Open in new window

Working sample here

EDIT: Added comments to code
0
 

Author Comment

by:Richard Korts
Comment Utility
Julian,

Thanks SO MUCH for all that effort.

My problem is I can't understand most of it at all. Seems WAY too complex. I am NOT an object programmer; I don't really understand JSON (I have used it). I don't understand AT ALL how Jquery is connected to the form.

I just want a simple process:

(1) pass form entered email & password to php

(2) Look up (in php) in database.

(3) If found, return false; else, return true.

I want to display a message with an alert (if found in database) & return false so the form does NOT submit to process.

I can do the rest.
0
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
I just want a simple process:
It doesn't get much simpler than what Julian has provided. This is a complex process. You need to collect data from the form and create a package to send to the server, open an asynchronous connection to a script on the server and send the package, monitor that connection to the script on the server while that script processes the package, receive the response from the script on the server, and handle that response in the web page in the browser.

Julian's solution uses jQuery which you have not included in your tags. And I seem to recall in your previous questions that you need raw javascript solutions. But the jQuery solution is much, much, more simple than the raw javascript in this case.
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
@Richard,
The JSON is not critical - I just used to be able to pass back complex information (i.e. other than just a message) - I can change the code only to output a message.

Essentially the code is doing too things
1. Checking that the email is unique
2. Checking the name and password are valid

The check on the email. When you exit a control (input) on a form the browser fires a blur() event (think: click in text box and <Tab> out or <click> out - blur() fires). The code (line 4) simply says to the browser - when there is blur() on the username field run this code.

The code it runs is an $.ajax call to a PHP script - passing the email (username) as a parameter.

The AJAX bit forms the main body of the event handlers - if you are unfamiliar with jQuery AJAX post back and I can take you through that.

The PHP script (as a demo) generates a random number which if divisible by 2 results in a failure message otherwise a success message.

A simple version of the above would be as follows (NB: I have not tested this - there may be some typos but the logic should be right)
HTML
<form>
  <label for="username">Username :</label> <input type="email" name="username" id="username" /><br/>
  <label for="password">Password :</label> <input type="password" name="password" id="password" />
  <input type="submit" value="Login" />
</form>

Open in new window

JQuery
$('form').submit(function() {
   // Make the AJAX call
   $.ajax({
      url: 'checkemail.php'
      data: {
        email: $('#username').val(),
        password: $('#password').val()
      },
      type: 'POST'
   }).done(function(resp) {
     // Show the messages from the sever
     alert(resp);
   });
   // This tells the form not to follow default behaviour and submit
   return false;
});

Open in new window

PHP (checkemail.php)
<?php
$username = empty($_POST['username']) ? false : $_POST['username'];
$password =  empty($_POST['password']) ? false : $_POST['password'];
if ($username && password) {
   if (!usernameValid($username, $password)) {
       echo "Username already in use";
   }
   else { 
      echo "Username is good to go";
   }
}
else {
   echo "Invalid username and / or password";
}

function usernameValid($username, $password) 
{
   // This is where you check your DB to see if the Username is valid
}

Open in new window

EDIT:
Updated sample JQuery code to include sending Password
0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 

Author Comment

by:Richard Korts
Comment Utility
OK, much better.

I have to do other checks in the form validation. I guess I can do that in the .submit(function)?

referencing as $('#formfieldname').val(),is that correct?

Also, I'm guessing that if  .submit(function) "falls through" it returns true?

Also, I fail to see  how it works if things are OK from the php. In that case, I want NO message.

Is "resp" a magic word for what the server echos?

I don't (can't) spend days learning all the syntax details of Jquery.

Thanks
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
Comment Utility
I have to do other checks in the form validation. I guess I can do that in the .submit(function)?
Yes
Also, I fail to see  how it works if things are OK from the php. In that case, I want NO message.
What you can do is the following. Check for a blank message - which indicates success and if it is not blank show it.
if (resp != '' ) {
   alert(resp)
}
else {
   // update screen or redirect
}

Open in new window

Is "resp" a magic word for what the server echos?
No you can call it anything you like. When the AJAX call completes the done() part fires and calls the function you pass to done with the response from the server - so what ever gets sent back from the server is passed as a parameter to the success function.

Also, I'm guessing that if  .submit(function) "falls through" it returns true?
Usually submit will return true if all is well false if it is not. False prevents the form being submitted true allows it to.
HOWEVER
When you bring AJAX into the mix it changes the rules - you always submit false from the submit function. Why? Because AJAX is asynchronous - it will complete after the submit  finishes and it is only when it completes that you know the status of the AJAX call. Therefore you return false from submit and then in your success handler you decide what you are going to do next based on the response.

With respect to the question asked - the check for the unique username makes sense as an AJAX call - it is doing a pre-check before round tripping to the server. When you introduce the form submit as an AJAX call that opens up a whole new topic in terms of what to do and how to do it.

I don't (can't) spend days learning all the syntax details of Jquery.
At it's heart jQuery is JavaScript. The upside is that to do what you want to do using plain JavaScript requires a lot more code to get one's head around. We can show you how to do it with JavaScript but I am not sure it will be doing you any favours. If you are going to be working with AJAX then jQuery is definitely worth getting to know - even if it is just superficially.

The key thing with jQuery is the selector - jQuery allows you to easily select an element or group of elements and then perform various functions on the element. In this case however the $.ajax() function is just a library function for making AJAX calls. You don't have to use jQuery inside the success function - you can use whatever JavaScript you are happy with.

Here are some links that you can look at if you want to know more about the plain JavaScript approach to AJAX.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
0
 

Author Closing Comment

by:Richard Korts
Comment Utility
I'm still going to try to do it in plain JavaScript. I found some examples I think I can build on.

Soooooooooooo much simpler.

I will post (on this question) the code if it works.

I understand that Jquery is ALL the rage now and that Javacript is passe & "out of favor". Still works & I use it all the time.

Thanks for your efforts, much appreciated.
0
 

Author Comment

by:Richard Korts
Comment Utility
Can I just do as in this code?

if (resp != '' ) {
   alert(resp);
   return false;
}
else {
   return true;
}

Open in new window

0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
Actually the return statements are unnecessary - they don't really do anything and are misleading.
What that should be is

if (resp != '') {
   alert(resp);
}
else {
   // AJAX was successful so do what you need to here
}

Open in new window

I understand that Jquery is ALL the rage now and that Javacript is passe & "out of favor". Still works & I use it all the time.
Important to remember JQuery is JavaScript - just a library that makes using JavaScript a little easier. But JavaScript is by no means out of favour - still the engine behind the client side interactive web.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

The task A number given should be formatted for easy reading by separating digits into triads. Format must be made inline via JavaScript, i.e., frameworks / functions are not welcome. So let’s take a number like this “12345678.91¿ and format i…
Introduction Got endorsements from your clients?  Great!  There is almost nothing better than word-of-mouth advertising.  But how can you do that on the internet?  Sure you can make a page for endorsement quotations and list them all, but who is …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 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

16 Experts available now in Live!

Get 1:1 Help Now