0

ok now below is my code that when some body puts the username and password and click submit button then the Javascript and ajax is triggered

    <html>
    <head>
        <title>Untitled Document</title>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script>
            $(function () {
            $('form').on('submit', function (e) {
            $.ajax({
            type: 'post',
            url: 'redirect.php',
            data: $('form').serialize(),
            success: function () {
            alert('form was submitted');     
            }
            });
            e.preventDefault();
            });
            });

        </script>
    </head>
    <body>
        <form>
            <div class="add_list">
                <p><span>Select User Name : </span>
                    <input type="text" name="username" size="20" />
                </p>
                <p><span>Select Your Password : </span>
                    <input type="password" name="password" size="20" />
                </p>
            </div>
            <div class="add_user">
                <input type="submit" value="add user" />
            </div>
        </form>
    </body>
</html>

after it is triggered it loads this page which is redirect.php page

 <?php
include 'includes\config.php';
//connects to the database


if (!empty($_POST['username']) && !empty($_POST['password'])) {
    // Now checking user name and password is entered or not.

    $username = mysql_real_escape_string($_POST['username']);

    $password = mysql_real_escape_string($_POST['password']);

    $check    = "SELECT * from user where username= '" . $username . "'";
    $qry      = mysql_query($check);
    $num_rows = mysql_num_rows($qry);

    if ($num_rows > 0) {
        // Here we are checking if username is already exist or not.

        echo "The username you have entered already exist. Please try again with another  username.";
        echo ('<script type="text/javascript"> alert ("The username you have entered already    exist.            Please try again with another username.");</script>');
        exit;
    }

    // Now inserting record in database.
    $query = "INSERT INTO user VALUES ('','" . $username . "','" . $password . "')";
    //id,username and password
    mysql_query($query);
    echo "User Added Successfully";
    echo ('<script type="text/javascript"> alert ("The username is added successfully.");</script>');
    exit;
}
?>

now the problem is when i submit the form it alerts that form is submitted but the actual javascript which is in redirect.php is not loading that is not alerting and also the echo of php is also not working though it is getting submitted in database and another problem is that if that username already exists when a person is entering the form is submitted is alerting and then nothing and when i check it is not getting submitted as username already exist but not echo or alert of javascript is working.

Nagendra Rao
  • 7,016
  • 5
  • 54
  • 92

4 Answers4

2

I recommend something like:

On the redirect.php page:

if($num_rows > 0){
     echo ("fail");
}
else {
     //your insert code
     echo ("success")
}

and your ajax success should be

success: function(data) {
    switch(data) {
         case 'fail':
              //fail code here
              alert ('That user already exists');
              //or simply alert (data);
              break;
         case 'success':
              //Success code here
              alert (data);
              break;
         default:
              //Error - invalid response from redirect
    }
}
rrtx2000
  • 626
  • 4
  • 13
  • Nice use of CASE; was too tired to think that deep :) – TheCarver Dec 11 '13 at 23:02
  • Thanks Papa. I actually copy and pasted some of my already existent code and just did a little modification. I like the case method because I actually return a 0, 1, 2... etc and it's easy to add additional contingencies this way. – rrtx2000 Dec 12 '13 at 03:50
1

It looks like you're thinking about it wrong. The redirect.php page isn't the one that displays to the user that the username exists or doesn't exist. The redirect.php page sends a message (or result) back to the ajax function. The ajax function acts on that message. That message can be accessed by putting a variable inside the success function like: success: function(var) Then you test and act on the contents of the variable.

To demonstrate how it works and to avoid confusion, I recommend you make a test_ajax.php page. The entire contents of the test_ajax.php page is:

 <?php
 echo('These are the ajax results');
 ?>

and change the url and success function to

<script>
    $(function () {
        $('form').on('submit', function (e) {
        $.ajax({
        type: 'post',
        url: 'test_ajax.php',
        data: $('form').serialize(),
        success: function(var) {
        alert (var);
        }
        });
        e.preventDefault();
        });
    });
</script>

Now when you submit, it will alert "These are the ajax results". Once you see how that works, you can go back to your redirect.php page and have ajax act on the response as mentioned in the other answers.

Keith Cox
  • 138
  • 4
0

You actually have a few issues, but won't go into them all.

Firstly - this is just an advisory, not a coding error - you should be using mysqlli or PDO for database queries. The mysql_ functions you are using are not supported anymore.

Also, (again, just advisory) where you have this line:

"SELECT * from user where username= '" . $username . "'"

It is pointless returning all columns just for a count. Simply use SELECT username FROM user... or SELECT COUNT(username) FROM user.... This is good practice if you ever have many columns and millions of users. If you need to check one column, then select one column, don't return them all.

On your PHP page, you can simply echo the following responses on success:

echo "Added";
// and //
echo "Exists";

You don't need to echo a SCRIPT with an alert. You can do this client-side.

And your AJAX request can have a listener for this response:

$.ajax({
    type: 'post',
    url: 'redirect.php',
    data: $('form').serialize(),
    dateType: "html",
    success: function(data) {
        if (data == "Added") {
            alert("User added.");
        } elseif (data == "Exists") {
            alert("Username already exists!");
        } else {
            alert("User submission failed.");
        }  
    }, error: function() {
       alert("An error occurred.");
    }
});

For example, swap this chunk of code:

if ($num_rows > 0) {
    echo "The username you have entered already exist. Please try again with another  username.";
    echo ('<script type="text/javascript"> alert ("The username you have entered already    exist. Please try again with another username.");</script>');
    exit;
}

With this:

if ($num_rows > 0) {
    echo "Exists";
    exit;
}

And use the above AJAX method I described.

TheCarver
  • 19,391
  • 25
  • 99
  • 149
0

You are getting the result back but you are using the ajax in a wrong way.

the success already gives you the result, if you want to use html in the result you need to apply to DOM.

The HTML/JS to show your the response from the response.php should be like this:

<html>
  <head>
        <title>Untitled Document</title>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
        <script>
          $(function () {
            $('form').on('submit', function (e) {
              $.ajax({
                type: 'post',
                url: 'redirect.php',
                data: $('form').serialize(),
                success: function (data) {
                  $('.result').html(data);
                }
              });
              $('.result').html('form was submitted');
              e.preventDefault();
            });
          });
        </script>
  </head>
  <body>
    <form>
      <div class="add_list">
        <p>
          <span>Select User Name : </span>
          <input type="text" name="username" size="20" />
        </p>
        <p>
          <span>Select Your Password : </span>
          <input type="password" name="password" size="20" />
        </p>
      </div>
      <div class="add_user">
      <input type="submit" value="add user" />
      </div>
      <div class="result">
      </div>
    </form>
  </body>
</html>
Fetz
  • 1,196
  • 8
  • 11