0

I am trying use for fetching data and displaying it through jQuery. This is my script

<script>
    $("#kys_SignUp_form").submit(function(event){
    event.preventDefault();

    var $form = $(this);
    var $url = $form.attr('action');
    var $email = $("#email").val();
    var $username = $("#username").val();
    var $password = $("#password").val();

    $.ajax({
          type: 'POST',
          url: $url,
          data: { email: $email, password: $password, username: $username },

          success: function(data) {
                alert("Transaction Completed!");
           }

            });
    });

 </script>

And this is my form:

 <form role="form" action="kys_SignUp.php" method="post" id="kys_SignUp_form">
   <div class="form-group">
       <label for="email" >Email address:</label>
       <input type="email" style="width: 300px" class="form-control"  name="email" id="email" required>
    </div>

  <div class="form-group">
    <label for="Username" >Username:</label>
    <input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
   </div>

  <div class="form-group">
     <label for="password" >Password:</label>
     <input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
  </div>

   <button type="submit"  class="btn btn-default">Submit</button>

</form>

I am new to jQuery. The problem that I am facing is the page is being redirected to the php file even after using ajax, I think ajax function is not at all called.

This is my php file:

 <?php 

 include "kys_DbConnect.php";

 $email = $username = $password = "";

if($_SERVER["REQUEST_METHOD"] == "POST"){

    $email = cleanData($_POST["email"]);
    $username = cleanData($_POST["username"]);
    $password = cleanData($_POST["password"]);        
}

$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();

    if(isset($kys_username)){
         echo "Username or Email already exists";         
    }  
   else{

        $insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)"); 
        $insert->bind_param("sss",$username,$email,$password);
        $insert->execute();
         header("Location: http://localhost/KeyStroke/index.html");
        exit();

   }
function cleanData($data){

    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;        
}
?>

I am not able find out what's wrong with my code.

24
  • 1
    any error in browser console? Commented Apr 4, 2016 at 5:43
  • $(document).ready(function(){ //code here }); ? Commented Apr 4, 2016 at 5:43
  • @Chetan No error in Browser. Commented Apr 4, 2016 at 5:45
  • Add a alert/logging statement in the submit handler to see whether it is getting called Commented Apr 4, 2016 at 5:46
  • @aldrin that doesnt make any difference because submit() will be called with the button is clicked Commented Apr 4, 2016 at 5:46

7 Answers 7

2

Updated try this :

<form role="form" action="kys_SignUp.php" method="post" id="kys_SignUp_form">
    <div class="form-group">
        <label for="email" >Email address:</label>
        <input type="email" style="width: 300px" class="form-control"  name="email" id="email" required>
    </div>

    <div class="form-group">
        <label for="Username" >Username:</label>
        <input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
    </div>

    <div class="form-group">
        <label for="password" >Password:</label>
        <input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
    </div>

    <button id="submit_btn"  class="btn btn-default">Submit</button>

</form>

UPDATED 2 :

<script>

      $(function() {
             // Handler for .ready() called.
             $("#submit_btn").on('click',function(event){
         //alert is not being called at all . That means .submit() is never beign called
               alert("hello there");
              event.preventDefault();

              var form = $('#kys_SignUp_form'); //changed from $(this)
              var url = form.attr('action');
              var email = $("#email").val();
              var username = $("#username").val();
              var password = $("#password").val();


                 $.ajax({
                      type: 'POST',
                      url: url,
                      dataType:"json", //<-- add this
                      data: { email: email, password: password, username: username },

                     success: function(data) {
                               if(data.success){
                            window.location.href=data.result;
                          }else {
                            alert("ERROR. "+data.result);
                             }

                             }

                 });

          });



    });
</script>

and in your PHP code

 <?php 

 include "kys_DbConnect.php";

 $email = $username = $password = "";

if($_SERVER["REQUEST_METHOD"] == "POST"){

    $email = cleanData($_POST["email"]);
    $username = cleanData($_POST["username"]);
    $password = cleanData($_POST["password"]);        
}

$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();

    if(isset($kys_username)){
         echo json_encode(array("success"=>false,"result"=>"Username or Email already exists"));         
    }  
   else{

        $insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)"); 
        $insert->bind_param("sss",$username,$email,$password);
        $insert->execute();
        echo json_encode(array("success"=>true,"result"=>"http://localhost/KeyStroke/index.html"));

   }
function cleanData($data){

    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;        
}
?>
Sign up to request clarification or add additional context in comments.

12 Comments

ThankYou for your answer. I have edited my code please check it out now
Thanks a lot it's working, Can you please tell me why .submit() dint work??
and Rafique now i am facing one more problem. in my php if the username already exists i will display the error using ajax else i want to redirect to a different page . i am using header function in php! after ajax is working i am not able to redirect
Do you keep your firebug open while testing this?
he is referring to FIREBUG of mozilla.. or other tools like that. @Jois
|
1
<script>

$("#clickbutton").click(function(){


var $url = 'kys_SignUp.php';
var $email = $("#email").val();
var $username = $("#Username").val();
var $password = $("#password").val();


$.ajax({
type: 'POST',
url: $url,
data: 'email='+$email+'&password='+$password+'&username='+$username,

success: function(data) {
alert("Transaction Completed!");

}

});

});
</script>

and also remove action in your form and change your submit button

<button type="button" id="clickbutton"  class="btn btn-default">Submit</button>

Comments

1

Try this function:

<script>

      $(function() {

             $('#kys_SignUp_form button[type="submit"]').on('click',function(event){

               alert("hello there");
              event.preventDefault();

              var form =  $("#kys_SignUp_form");//note here we select the form element to get the url
              var url = form.attr('action');
              var email = form.find("#email").val();
              var username = form.find("#username").val();
              var password = form.find("#password").val();


                 $.ajax({
                      type: 'POST',
                      url: url,
                      dataType:"json", 
                      data: { email: email, password: password, username: username },

                     success: function(data) {
                       if(data.message == "Success") {
                            window.location ='http://localhost/KeyStroke/index.html';
                       } else {alert(data.message)}

                 });

          });



    });
</script>

php:

 include "kys_DbConnect.php";
function cleanData($data){

    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;        
}
function isUser($username,$email)
$stmt = $con->prepare("SELECT * FROM kys_users WHERE username=? OR email=?");
$stmt->bind_param("ss",$username,$email);
$stmt->execute();
$stmt->bind_result($kys_id,$kys_email,$kys_username,$kys_password);
$stmt->fetch();

    if(isset($kys_username)){
       return true;      
    }
}  
function inserNewUser($username,$email,$password)
        $insert = $con->prepare("INSERT INTO kys_users (username, email, password) VALUES (?, ?, ?)"); 
        $insert->bind_param($username,$email,$password);
        $insert->execute();

   }


if($_SERVER["REQUEST_METHOD"] == "POST"){
    $email = cleanData($_POST["email"]);
    $username = cleanData($_POST["username"]);
    $password = cleanData($_POST["password"]);  
    if (isUser($username,$email)) {
      echo json_encode(['message'=>'Username or Email already exists'])
    } else {
      inserNewUser($username,$email,$password);
      echo json_encode(['message'=>'Success']);
    }

} else {
echo json_encode(['message'=>'Error get method not allowed'])
}

4 Comments

ThankYou it's working!! can you tell me what was wrong
I don't know why your submit event wasn't triggering i just addapted Rafique answer and changed the form variable to the form id to get the url
from what i can see your submit wasn't triggering because it wasn't in a document ready statement
I already changed it on my answer long ago. you should have edited it in my answer itself rather than posting it separately. Bcz this soultion is incomplete without actual php code.
0

Look at my way, may be it will help you.

$('#frmReportWithparams').submit(function () {        
    $.ajax({
        url: "@Url.Content("~/LeftMenu/SendReportWithParameter")",
        type: "POST",
        data: $('#frmReportWithparams').serialize(),
        success: function (result) {
            if (result.IsSuccess == true) {
                alert("Thank You.")
                $('#modalHomeIndex').dialog('close')
            }
            else {
                alert("'Error Occurs.Try Later.")
                $('#modalHomeIndex').dialog('close')
            }
        }
    })
    return false;
})

actually the code is for C#, but i just set where to post a form in ajax.
look at @Url.content where i passed the values where my form will be posted. and the parameters are serialized in data field.
if you have any other query then ask further...

3 Comments

My problem is that .submit() is never called. Can you please look into that once
<input type="submit" value="OK" class="btn btn-default" style="cursor:pointer;" />
yes, debugger will help you to debugg your jquery/javascript code in browser, it's important functionality. also you can add alert when submit is called, so you can check whether your form is posting via jquery or not.
0

Why Use $ in js variable this is wrong.

Use This One.

var form = $(this);  
var url = $form.attr('action');  
var email = $("#email").val();  
var username = $("#username").val();  
var password = $("#password").val();

1 Comment

i did but it dint make any difference
0

try this may be this will work

<script> 
$(document ).ready(function() { 
    $('#kys_SignUp_form').on('submit', function(e) {
      e.preventDefault();
    });
});

 // ================ SUBMIT  =====================
$('#kys_SignUp_form .form_submit').on('click', function(e){
    e.preventDefault();
    var $form = $(this);      
    var $email = $("#email").val();
    var $username = $("#username").val();
    var $password = $("#password").val();

    $.ajax({
        type: 'POST',
        url: 'kys_SignUp.php',
        dataType: 'json',
        data: { email: $email, password: $password, username: $username },
        success: function(data) {
            alert("Transaction Completed!");
        },
       error : function( errorThrown) {

         alert('errorThrown ' + errorThrown);
      }
    });
});
</script>

HTML

<form role="form"  method="post" id="kys_SignUp_form">
<div class="form-group">
    <label for="email" >Email address:</label>
    <input type="email" style="width: 300px" class="form-control"  name="email" id="email" required>
</div>

<div class="form-group">
    <label for="Username" >Username:</label>
    <input type="text" style="width: 300px" class="form-control" name="username" id="Username" required>
</div>

<div class="form-group">
    <label for="password" >Password:</label>
    <input type="password" style="width: 300px" class="form-control" id="password" name="password" required>
</div>

<button type="submit"  class="btn btn-default form_submit">Submit</button>

Comments

0

You need to do two things.

1- Change var var url = $form.attr('action'); to

var url = $("#kys_SignUp_form").attr('action');

2- Add a return statement just before you submit function ends

complete script will look like below-

<script>
  $( document ).ready(function() {
         // Handler for .ready() called.
         $("#kys_SignUp_form").submit(function(event){

          alert("hello there");
          event.preventDefault();
          var form = $(this);
          var url = $("#kys_SignUp_form").attr('action');
          var email = $("#email").val();
          var username = $("#username").val();
          var password = $("#password").val();

          $.ajax({
                  type: 'POST',
                  url: url,
                  data: { email: email, password: password, username: username },

                 success: function(data) {
                           alert("Transaction Completed!");

                         }
             });
        return false;
      });
});
</script>

Comments

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.