Ajax代码在jquery表单验证中不起作用

Ajax代码在jquery表单验证中不起作用

问题描述:

I want to write (register section) code that can check if email have been used in past or the login is empty.

The code is working fine, but my ajax code dont run at all.

I checked everything, path to php file is good, variables are good etc. Don't how to solve it.

Code:

$('.login').submit(function(e) {

    e.preventDefault();
    var error = 0;
    var self = $(this);

    var $name = self.find('[type=name]');
    var $email = self.find('[type=email]');
    var $pass = self.find('[type=password]');

    var emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;

    if (!emailRegex.test($email.val())) {
        createErrTult("Błąd! Email ma zły format!", $email)
        error++;
    }

    //MY AJAX CODE
    var email = $email.val();

    $.ajax({
        url: '../inc/rejestracja.php?action=emailcheck',
        data: {
            'email': email
        },
        type: 'POST',
        success: function(odp) {
            if (odp == 1) {
                createErrTult("Błąd! taki email już istnieje w bazie!", $email)
                error++;
            }
        }
    });

    if ($name.val().length > 1 && $name.val() != $name.attr('placeholder')) {
        $name.removeClass('invalid_field');
    } else {
        createErrTult('Error! Wrong name!', $name)
        error++;
    }

    if ($pass.val().length > 1 && $pass.val() != $pass.attr('placeholder')) {
        $pass.removeClass('invalid_field');
    } else {
        createErrTult('Error! Wrong password!', $pass)
        error++;
    }

    if (error != 0) return;
    self.find('[type=submit]').attr('disabled', 'disabled');

    self.children().fadeOut(300, function() {
        $(this).remove()
    })
    $('<p class="login__title">sign in <br><span class="login-edition">welcome to A.Movie</span></p><p class="success">You have successfully<br> signed in!</p>').appendTo(self)
        .hide().delay(300).fadeIn();

    // var formInput = self.serialize();
    // $.post(self.attr('action'),formInput, function(data){}); // end post
});

php:

<?php

include ("config.php");

  if($action == "emailcheck"){

      //sprawdzamy czy był już dodany plus
      $test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
            if ($test > 0) {
                $dodano = 1;
                echo json_encode($dodano); 


      }
?>

First, you should try adding error callback:

$.ajax({
    url: '../inc/rejestracja.php?action=emailcheck',
    data: {
        'email': email
    },
    type: 'POST',
    success: function(odp) {
        if (odp == 1) {
            createErrTult("Błąd! taki email już istnieje w bazie!", $email)
            error++;
        }
    },
    error: function(xhr, textStatus, error) // THOSE ROWS
    {
       alert(error);
    }
});

This may alert you about some occured error.

Second, you can try to use json instead of plain text:

Client-side:

$.ajax({
    url: '../inc/rejestracja.php?action=emailcheck',
    data: {
        'email': email
    },
    dataType: 'json', // THIS ROW
    type: 'POST',
    success: function(odp) {
        if (odp['result'] == 1) {
            createErrTult("Błąd! taki email już istnieje w bazie!", $email)
            error++;
        }
    },
    error: function(xhr, textStatus, error)
    {
       alert(error);
    }
});

Server-side:

<?php

include ("config.php");
if (isset($_GET['action'])){
    $action = $_GET['action'];
    if($action == "emailcheck") {
      if(isset($_GET['email'])) {
        $email = $_GET['email'];
        //sprawdzamy czy był już dodany plus
        $test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
        if ($test > 0) {
            $dodano = 1;
            echo (json_encode(array("result" => $dodano))); // THIS ROW
        }
      }
    }
}
?>

before everything check you config.php file path .. In your case config.php should be in the same path with rejestracja.php and try this.. lets start with ajax

$.ajax({
        url: '../inc/rejestracja.php?action=emailcheck',
        data: {
            email: email
        },
        type: 'GET',
        success: function(odp) {
            if (odp == 1) {
                alert('Email exists');
            }else{
                alert('Email dosen\'t exists');
            }
        }
    });

then in php

<?php

include ("config.php");
if (isset($_GET['action'])){
   $action = $_GET['action'];
  if($action == "emailcheck"){
      if(isset($_GET['email'])){
         $email = $_GET['email'];
         //sprawdzamy czy był już dodany plus
         $test = mysql_num_rows(mysql_query("select * from uzytkownicy where email='$email'"));
            if ($test > 0) {
                $dodano = 1;
                echo ($dodano); 

        }
    }
}
?>

you should get alert with ('Email exists')