javascript - back-end error_msg is not giving a alert..!

41

I am using jquery to make a .php file execute but my major problem is when ever a error is thrown from back-end i used a alert to display that error_msg..but ever i submit with a error intentionally...its just moving on to page specified in action...no error alert poped up...plz help me out of this.!!pardon me if am wrong

here gose the DB_Function.php

<?php
class DB_Functions {
    private $db;

    // constructor for database connection
    function __construct() {
        try {
            $hostname = "localhost";
            $dbname = "miisky";
            $dbuser = "root";
            $dbpass = "";
            $this->db = new PDO("mysql:host=$hostname;dbname=$dbname", $dbuser, $dbpass);
        }
        catch(PDOException $e)
        {
            die('Error in database requirments:'    . $e->getMessage());
        }
    }

    /**
      * Storing new user
      * returns user details of user
      */
  public function storeUser($fname, $lname, $email, $password, $mobile) {  
    try {
        $hash = md5($password);
        $sql = "INSERT INTO users(fname, lname, email, password, mobile, created_at) VALUES ('$fname', '$lname', '$email', '$hash', '$mobile', NOW())";
        $dbh = $this->db->prepare($sql);

        if($dbh->execute()){
            // get user details
            $sql = "SELECT * FROM users WHERE email = '$email' LIMIT 1";
            $dbh = $this->db->prepare($sql);
            $result = $dbh->execute();
            $rows = $dbh->fetch();
            $n = count($rows);
            if($n){
                return $rows;
            }
        }
    }
    catch (Exception $e) {
        die('Error accessing database: ' . $e->getMessage());
    }
    return false;
}

/*to check if user is
 already registered*/
  public function isUserExisted($email) {
    try{
        $sql = "SELECT email FROM users WHERE email = '$email' LIMIT 1";
        $dbh = $this->db->prepare($sql);
        $result = $dbh->execute();
        if($dbh->fetch()){
            return true;
        }else{
            return false;
        }
    }catch (Exception $e) {
        die('Error accessing database: ' . $e->getMessage());
    }
}
/*to check if user
exist's by mobile number*/
public function isMobileNumberExisted($mobile){
try{
    $sql = "SELECT mobile FROM users WHERE mobile = '$mobile' LIMIT 1";
    $dbh = $this->db->prepare($sql);
    $result = $dbh->execute();
    if($dbh->fetch()){
    return true;
    }else{
    return false;
    }
}catch(Exception $e){
    die('Error accessing database: ' . $e->getMessage());
}
}
//DB_Functions.php under construction 
//more functions to be added
}
?>

here gose the .php file to be clear on what am doing..!!

<?php
    require_once 'DB_Functions.php';
    $db = new DB_Functions();

    // json response array
    $response = array("error" => false);
    if (!empty($_POST['fname']) && !empty($_POST['lname']) && !empty($_POST['email']) && !empty($_POST['password']) && !empty($_POST['mobile'])){
        // receiving the post params
        $fname = trim($_POST['fname']);
        $lname = trim($_POST['lname']);
        $email = trim($_POST['email']);
        $password = $_POST['password'];
        $mobile = trim($_POST['mobile']);

        // validate your email address
        if(filter_var($email, FILTER_VALIDATE_EMAIL)) {
            //validate your password
            if(strlen($password) > 6){
            //validate your mobile
            if(strlen($mobile) == 12){
            //Check for valid email address
            if ($db->isUserExisted($email)) {
                // user already existed
                $response["error"] = true;
                $response["error_msg"] = "User already existed with " . $email;
                echo json_encode($response);
            } else {
                if($db->isMobileNumberExisted($mobile)) {
                    //user already existed
                    $response["error"] = true;
                    $response["error_msg"] = "user already existed with" . $mobile;
                    echo json_encode($response);
            } else {

                // create a new user
                $user = $db->storeUser($fname, $lname, $email, $password, $mobile);
                if ($user) {
                    // user stored successfully
                    $response["error"] = false;
                    $response["uid"] = $user["id"];
                    $response["user"]["fname"] = $user["fname"];
                    $response["user"]["lname"] = $user["lname"];
                    $response["user"]["email"] = $user["email"];
                    $response["user"]["created_at"] = $user["created_at"];
                    $response["user"]["updated_at"] = $user["updated_at"];
                    echo json_encode($response);
                } else {
                    // user failed to store
                    $response["error"] = true;
                    $response["error_msg"] = "Unknown error occurred in registration!";
                    echo json_encode($response);
                }
            }
         }
        } else {
            $response["error"] = true;
            $response["error_msg"] = "Mobile number is invalid!";
            echo json_encode($response);
        }

        } else {
            //min of 6-charecters
            $response["error"] = true;
            $response["error_msg"] = "password must be of atleast 6-characters!";
            echo json_encode($response);
        }

       } else {
            // invalid email address
            $response["error"] = true;
            $response["error_msg"] = "invalid email address";
            echo json_encode($response);
        }
    } else {
        $response["error"] = true;
        $response["error_msg"] = "Please fill all the required parameters!";
        echo json_encode($response);
    }
?>

and here gose the main file .js

$(document).ready(function(){

    //execute's the function on click
    $("#submit").click(function(e){

        /*jquery to call the url requested 
        and parse the data in json*/
        $.ajax({
            url: "register.php",
            type: "POST",
            data: {
                fname: $("#fname").val(),
                lname: $("#lname").val(),
                email: $("#email").val(),
                password: $("#password").val(),
                mobile: $("#mobile").val()
            },
            dataType: "JSON",
            /*Give out the alert box
            to display the results*/ 
            success: function (json){
                if(json.error){
                    alert(json.error_msg);
                    e.preventDefault();
                }else{
                    alert("Registeration successful!",json.user.email);
                }
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert(errorThrown);
                e.preventDefault();
            }
        });
    });

}); 

and here gose the corresponding .html file

<form method = "POST" name = "register" id = "register" role="form" action="login.html">

          <div >
            <input type="text" name = "fname" id = "fname" placeholder="First Name" required="">
          </div>
          <div >
            <input type="text" name = "lname" id = "lname" placeholder="Last Name" required="">
          </div>
          <div >
            <input type="email" name = "email" id = "email" placeholder="Email" required="">
          </div>
          <div >
            <input type="password" name = "password" id = "password" placeholder="Password" required="">
          </div>
          <div >
            <input type="mobile" name = "mobile" id = "mobile" placeholder="Mobile No" required="">
          </div>
          <div  id="recaptcha_widget">
                            <div >
                             <div data-sitekey="6Lc4vP4SAAAAABjh8AG"></div>
                            <!-- End Thumbnail-->
                           </div>
                           <?php include("js/captcha.php");?>
          </div>
          <div >
              <div cle the terms and policy </label></div>
          </div>ass="checkbox i-checks"><label> <input type="checkbox"><i></i> Agre
          <button type="submit" name = "submit" id = "submit" >Register</button>

          <p ><small>Already have an account?</small></p>
          <a href="login.html">Login</a>
        <

/form>
497

Answer

Solution:

From the comments:

So only after displaying Registeration successful! I want to submit the form and redirect it to login.html

Well the solution is quite simple and involved adding and settingasync parameter tofalse in.ajax(). Settingasync tofalse means that the statement you are calling has to complete before the next statement in your function can be called. If you setasync: true then that statement will begin it's execution and the next statement will be called regardless of whether the async statement has completed yet.

Your jQuery should be like this:

$(document).ready(function(){
    //execute's the function on click
    $("#submit").click(function(e){

        /*jquery to call the url requested 
        and parse the data in json*/
        $.ajax({
            url: "register.php",
            type: "POST",
            data: {
                fname: $("#fname").val(),
                lname: $("#lname").val(),
                email: $("#email").val(),
                password: $("#password").val(),
                mobile: $("#mobile").val()
            },
            async: false,
            dataType: "JSON",
            /*Give out the alert box
            to display the results*/ 
            success: function (json){
                if(json.error){
                    alert(json.error_msg);
                    e.preventDefault();
                }else{
                    alert("Registeration successful!",json.user.email);
                    ('#register').submit();
                }
            },
            error: function(jqXHR, textStatus, errorThrown){
                alert(errorThrown);
            }
        });
    });
}); 

So the form will only get submitted if the registration is successful, otherwise not.

Edited:

First of all make sure that<!DOCTYPE html> is there on the top of your page, it stands for html5 and html5 supportsrequired attribute.

Now comes to your front-end validation thing. The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via thesubmit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.

However, you can request (static) form validation against the constraints defined by HTML5 attributes, using thecheckValidity() method.

For the purpose of simplicity I removed your terms and conditions checkbox and Google ReCaptcha. You can incorporate those later in your code.

So here's your HTML code snippet:

<form method = "POST" name = "register" id = "register" role="form" action="login.html">

  <div >
    <input type="text" name = "fname" id = "fname" placeholder="First Name" required />
  </div>
  <div >
    <input type="text" name = "lname" id = "lname" placeholder="Last Name" required />
  </div>
  <div >
    <input type="email" name = "email" id = "email" placeholder="Email" required />
  </div>
  <div >
    <input type="password" name = "password" id = "password" placeholder="Password" required />
  </div>
  <div >
    <input type="mobile" name = "mobile" id = "mobile" placeholder="Mobile No" required />
  </div>

  <!--Your checkbox goes here-->
  <!--Your Google ReCaptcha-->

  <input type="submit" name = "submit" id = "submit" value="Register" />

</form>

<p ><small>Already have an account?</small></p>
<a href="login.html">Login</a>

And your jQuery would be like this:

$(document).ready(function(){

    //execute's the function on click
    $("#submit").click(function(e){

        var status = $('form')[0].checkValidity();
        if(status){
            /*jquery to call the url requested 
            and parse the data in json*/
            $.ajax({
                url: "register.php",
                type: "POST",
                data: {
                    fname: $("#fname").val(),
                    lname: $("#lname").val(),
                    email: $("#email").val(),
                    password: $("#password").val(),
                    mobile: $("#mobile").val()
                },
                async: false,
                dataType: "JSON",
                /*Give out the alert box
                to display the results*/ 
                success: function (json){
                    if(json.error){
                        alert(json.error_msg);
                        e.preventDefault();
                    }else{
                        alert("Registeration successful!",json.user.email);
                        $('#register').submit();
                    }
                },
                error: function(jqXHR, textStatus, errorThrown){
                    alert(errorThrown);
                }
            });
        }

    });

}); 
81

Answer

Solution:

your form submit takes action before ajax action so its reloading the page and use form submit instead of submit button click

//execute's the function on click
    $("#register").on('submit',function(e){
       e.preventDefault(); // prevent page from reloading 

Ok steps to be sure that everthing works fine while you try to use ajax

1st : use form submit and usee.preventDefault(); to prevent page reloading

//execute's the function on click
    $("#register").on('submit',function(e){
       e.preventDefault(); // prevent page from reloading
       alert('Form submited'); 
   });

if the alert popup and form not reloading the page then the next step using ajax

  //execute's the function on click
    $("#register").on('submit',function(e){
       e.preventDefault(); // prevent page from reloading
       $.ajax({
          url: "register.php",
          type: "POST",
          dataType: "JSON",
          data: {success : 'success'},
          success : function(data){
              alert(data);
          }
       });
   });

and in php (register.php)

<?php 
   echo $_POST['success'];
?>

this code should alert with "success" alert box .. if this step is good so now your ajax and php file is connected successfully then pass variables and do another stuff

People are also looking for solutions to the problem: php - Memory leak in recursive function with reference

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.