0

i am creating login page with ajax.when user name and pass is wrong it should display error and when pass is right it should redirect to another page.but here in both case success function is called..

<script>
    $(document).ready(function()
    {


    $("#simple-post").click(function()
    {
        $("#ajaxform").submit(function(e)
        {
            $("#simple-msg").html("<img src='loading.gif'/>");
            var postData = $(this).serializeArray();
            var formURL = $(this).attr("action");

            $.ajax(
            {
                url : formURL,
                type: "POST",
                data : postData,
                success:function(data, textStatus, jqXHR) 
                {
                alert(data.status);
                $("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code></pre>');


                },
                error: function(jqXHR, textStatus, errorThrown) 
                {
                    $("#simple-msg").html('<pre><code class="prettyprint">AJAX Request Failed<br/> textStatus='+textStatus+', errorThrown='+errorThrown+'</code></pre>');
                }
            });
            e.preventDefault(); //STOP default action
        });

        $("#ajaxform").submit(); //SUBMIT FORM
    });

    });
    </script>

this is php

<?php
ob_start();

include 'CUserDB.php';

session_start(); 
include 'config.php';
$myusername=$_POST['txtusername']; 
$mypassword=$_POST['txtpassword']; 
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword=mysql_real_escape_string($mypassword);      

$qry = "SELECT UserName,Type_user FROM login WHERE UserName = '".$myusername."' AND password = '".$mypassword."' ";

$result = mysql_query($qry) or die ("Query failed");

$UserData = mysql_fetch_array($result);

    if($UserData['UserName'] != '')

        {
            session_start(); 

             $_SESSION['UserId'] = $myusername;

        $typ = $UserData['Type_user'];



    if   ( $typ == "Dealer")
    { 
 header('location:Dealer/EditLoginDetails.php');  


    }
    else if     ($typ == "Individual")
    {
         header('location:/Dealer/EditLoginDetails.php');  

    }
    else 
    {
        header('location:/Builder/managep.php'); 
    }




        }
   else 

    { 
    echo " wrong username or password";


    }

?>

i want to display wrong username pass if not success..how to do this please i am new in ajax

3
  • how to consider this as error } else { echo " wrong username or password"; } Commented Nov 21, 2013 at 6:25
  • Use if condition in success and pass some token from php code. if (valid) else display error Commented Nov 21, 2013 at 6:26
  • On a sidenote… please don't store passwords in plaintext. Hash and salt them. Also, don't use the mysql_ functions. Please use prepared statements and mysqli_ or PDO instead. Commented Nov 21, 2013 at 6:28

3 Answers 3

2

Please have a clear understanding of success callback of jquery.Ajax. The documentation says: A function to be called if the request succeeds.

In your case, request is successful if the username and password entered are wrong.

To Make it work properly, change your php code of this part to:

$redirect = '';
if($UserData['UserName'] != '')
{
    session_start();
    $error = 0;
    $message = 'Valid';
    $_SESSION['UserId'] = $myusername;

    $typ = $UserData['Type_user'];

    if($typ == "Dealer")
    {
        $redirect = 'Dealer/EditLoginDetails.php';
    }
    else if($typ == "Individual")
    {
        $redirect = '/Dealer/EditLoginDetails.php';
    }
    else
    {
        $redirect = '/Builder/managep.php';
    }
}
else
{
    $error = 1;
    $message = 'Invalid username or password';
}

echo json_encode(array('error' => $error, 'message' => $message, 'redirect' => $redirect));

And jquery code to,

$.ajax({
    url : formURL,
    type: "POST",
    data : postData,
    dataType:'json',
    success:function(data, textStatus, jqXHR) {
        if(data.error == 1) {
            $("#simple-msg").html('<pre><code class="prettyprint">'+data.message+'</code>< /pre>');
        } else {
            window.location = data.redirect;
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

What HTTP status codes count as success in jQuery.ajax? says that following codes are successful for AJAX-responses:

status >= 200 && status < 300 || status === 304

So you can set error header:

header('HTTP/1.0 403 Forbidden');
echo " wrong username or password";

1 Comment

@Ramesh approach is better for this situation.
0
 success:function(data, textStatus, jqXHR)  {
     if(data== "error message"){
            //display error here
      } else{
       $("#simple-msg").html('<pre><code class="prettyprint">'+data+'</code>< /pre>');
      }
  },

Error message can be like error / sucess etc.

success: function(data) {
  if(data.status == 'success')
      alert("Thank you for subscribing!");
  else if(data.status == 'error')
      alert("Error on query!");
}

2 Comments

how to set data.status in php
There is two way transfer, either json or xml. for json. you should encode json.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.