jquery.ajax() processData - set to false, still appending form data to url - and other problems

StackOverflow https://stackoverflow.com/questions/10875135

  •  12-06-2021
  •  | 
  •  

Question

So i am attempting to learn some jquery to use in a form to access a mysql database, here is the form:

<form class="loginform" id="loginform" name="loginform">
    <input type="email" id="login" name="login" placeholder="Login..." autofocus required /><br/>
    <input type="password" id="password" name="password" placeholder="Password..." required /><br/>
    <input type="submit" id="loginsubmit" name="loginsubmit" value="LOGIN"/><br/>
    <input type="submit" id="register" name="register" value="REGISTER"/><br/>
</form><!-- end loginform -->

I have a JS function and am using the $.submit() function and through the function defined as the parameter for $.submit() i have a call to $.ajax() like so:

function validateLogin(){
  $('#loginform').submit(function() {      
    $.ajax({
      url: "./validateLogin.php", 
      processData: false,
      data: {
        login: $("#login").val(), 
        password: $("#password").val()
      }, 
      success: function (result){
        alert($('#login').val());
        alert(result);
      }
    });
  });
}

notice the line that reads processData: false, and finally here is the php script that is called by the $.ajax() method in the url setting:

<?php
$verified = FALSE;
$login = $_POST["login"];
$password = $_POST["password"];

$con = mysql_connect(host, user, pass) or die(mysql_error());
mysql_select_db(db, $con) or die(mysql_error());

$result = mysql_query("SELECT * FROM logins") or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
  if ($row[login] == $login) {
    $verified = TRUE;
  }
}
?>

<html>
    <body>
        <?php echo($verified); ?>
    </body>
</html>

There are a few things not working, I can't get anything to happen with the exception of the form data being appended to the url( the url will look something like this after submitting: http://localhost/index.htmlqlogin=aloginname&password=apassword&login=LOGIN, it is also adding the name: value pair for my submit button to the query string for some reason), and it is my understanding from reading HERE (see the data setting) that with processData: false this shouldn't even be happening.

Also I can't get the success: function() to fire the alerts (i have also tried throwing an alert in beforeSend: function() and that won't fire either.

I kinda understand jQuery but not entirely a i'm relatively new to it, but what i understand about the code i've written is that in the JS function i'm attaching an event handler to the form(? - not an element of the form), and in the function that that event handler will execute i am making a call to the $.ajax() method, that sends the data to a url and on successful completion of that processes the function defined in the success: setting of the $.ajax() method. then in my php script i am connecting to mysql, querying it, checking to see if the login from the form matches an entry in the db, if it does a boolean is changed to true and finally the value of the boolean is echoed inside a <html> tag, however i'm not sure about how to display that html data.

so thats my problem in a nutshell. any guidance would be greatly appreciated! feel free to correct me if i am misunderstanding anything about the process as described above. thanks again.

Was it helpful?

Solution

Several things to remark.

1- Make sure the path ./validateLogin.php is right.

2- I don't know if you do already, but if you dont use Firebug, the coolest addon for debugging when developing a website. It will save you hours of work literally and help you with errors involving javascript.

3- The most common use of ajax is to either post or bring data. Either simple string like "done" or "error", or serialized data like JSON.(see JSON). If you need to output an array or an object use json_encode function in PHP.

Here is some code for you to try, it worked for me.

On PHP side

   $result = mysql_query("SELECT * FROM logins") or die(mysql_error());
   while ($row = mysql_fetch_array($result)) {
       if ($row[login] == $login) { 
         $verified = TRUE;
       }
   }
   if ($verified){
        echo 'TRUE';  // This could be anything you want, an array, an object, numbers or a string
   }else{
        echo 'FALSE';
   }

On Javascript Side

$(document).ready(function(){ // Everything is encapsuled in the ready function in order to wait for the page to load completely.
    $.ajax({
        url: './validateLogin.php', 
        type: 'POST',
        success: function(result){

            if(result == 'TRUE'){
                alert('Verified!');                         
            }else{
                alert('Not verified!');                             
            }

        }
    });
});

I know you were trying to output the and tags too, but remember that javascript and ajax is meant to smoothly change the existen layout. So you don't really want to bring huge amounts of HTML code in your requests. You should prepare your layout with HTML and PHP first and then use javascript and ajax only to bring important data or things you need to change on the fly.

OTHER TIPS

//hey try to use this server side php script

$logins = $_POST['login'];
$password = $_POST['password'];

$sqlquery = mysql_query("SELECT * FROM logins WHERE logins=$logins AND password=$password");
$numrow = mysql_num_rows($sqlquery);//check if exists or not

if($numrow > 0){
$verified =  "TRUE";
}
else{
$verified = "FALSE";
}
echo json_encode(array('verified'=>$verified));// echo out with json encode
//JS

$(document).ready(function(){
$("#loginbtn").click(function(){
$.ajax({
      type:'post',
      url:'validatelogin.php',
      data: {login: $("#login").val(), password: $("#password").val()},
      dataType:'json',
      success:function(data){

             alert(data.verified);
      }
});     
});

});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top