1

So, I need to use ajax in order to submit a form (click any of 6 buttons and increment by 1 a field in the db). I think I got my function correct(well, if I did, it'd be working), but it's still refreshing the page after every submit. What am I doing wrong here?

Both my PHP and HTML are inside the same page (index.php) Here's my code:

 <?php
 include '/Login/db_login.php';
 $page = 'index.php';

 if(isset($_POST['ContBt1'])){
 $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 1";
mysqli_query($conn, $sql);
 mysqli_close($conn);
 }
 
 if(isset($_POST['ContBt2'])){
 $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 2";
mysqli_query($conn, $sql);
 mysqli_close($conn);
 }
 
 if(isset($_POST['ContBt3'])){
 $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 3";
 mysqli_query($conn, $sql);
 mysqli_close($conn);
 }
 
 if(isset($_POST['ContBt4'])){
 $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 4";
 mysqli_query($conn, $sql);
 mysqli_close($conn);
 }
 
 if(isset($_POST['ContBt5'])){
 $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 5";
mysqli_query($conn, $sql);
 mysqli_close($conn);
 }
 
 if(isset($_POST['ContBt6'])){
 $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 6";
mysqli_query($conn, $sql);
 mysqli_close($conn);
 }
 ?>
 
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Index</title>
<link href="index.css" rel="stylesheet" type="text/css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

</head>

<body class="Background">
 <div class="BtLogin">
   <a href="Login/paginalogin.php">
    <input type="image" id="admin" src="http://i.imgur.com/I3D3nqm.png">
   </a>
 </div>
 <form action=""  id="myform" method="POST" onsubmit="return false">
  <table class="Table">
   <tr>
    <td><input class="Button ButtonTxt" type="button" name="ContBt1"  value="A"></td>
    <td><input class="Button ButtonTxt" type="button" name="ContBt2"  value="B"></td>
   </tr>
   <tr>
    <td><input class="Button ButtonTxt" type="button" name="ContBt3"  value="C"></td>
    <td><input class="Button ButtonTxt" type="button" name="ContBt4"  value="D"></td>
   </tr>
   <tr>
    <td><input class="Button ButtonTxt" type="button" name="ContBt5"  value="E"></td>
    <td><input class="Button ButtonTxt" type="button" name="ContBt6"  value="F"></td>
   </tr>
  </table>
 </form>
         <script>
$(function(){
    $('.Button').on('click', function (e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: 'index.php',
            data: $('#myform').serialize(),
            success: function () {
                alert('The form was submitted successfully');
            }
        });
    });
});
  </script>
</body>
</html>

Here's my db_login.php:

<?php
 $servername = "localhost";
 $username = "root";
 $password = null;
 $dbname = "pap1";

 $conn = mysqli_connect($servername, $username, $password, $dbname);
 if (!$conn) {
  ?>
     <html >
<head>
  <meta charset="UTF-8">
  <title>Error Page</title>
</head>

<body>

      <h1>ERROR</h1>
   <center><h2> Error ($dbname) does not exist</h2></center>
  </form>

</body>
</html>
<?php
 }
?>
Azazel
  • 65
  • 8
  • 1
    Your form selector is incorrect. Try `$('#myform')` to select by id. – e_i_pi May 08 '17 at 23:00
  • Did that, still not working, sadly... – Azazel May 08 '17 at 23:04
  • FYI, anything you put after `exit` will **not** execute – Phil May 08 '17 at 23:06
  • Hold on, you've got header redirects whenever a form submission `$_POST` array contains any of the submit button values. This code will be causing the "reload" (read: redirect): `header('Location: '.$page, true, 303);` – e_i_pi May 08 '17 at 23:07
  • Can you nest an AJAX call to itself? That would do bad things won't it? – Forbs May 08 '17 at 23:08
  • Removed all the headers reddirects. I'm not really sure why I added them to begin with... I'm still a rookie, trying to learn jquery and ajax by myself but it's pretty hard to do so. Anyways, sadly it's still not working, no idea why – Azazel May 08 '17 at 23:15
  • So, I moved my script to the bottom, right before

    , I now get the alert saying the form was submited, but the database values remain unchanged

    – Azazel May 08 '17 at 23:18
  • @Azazel I've re-opened your question. Thanks for updating the code – Phil May 09 '17 at 00:15
  • Problem is, `serialize()` won't pick up the button that you clicked to submit the form. I'm pretty sure there's another duplicate for this, will find it in a minute – Phil May 09 '17 at 00:17
  • Possible duplicate of [jQuery: how to get which button was clicked upon form submission?](http://stackoverflow.com/questions/5721724/jquery-how-to-get-which-button-was-clicked-upon-form-submission) – Phil May 09 '17 at 00:19
  • Change input type="submit" to type="button" then check...if nothig happening then the error in ajax call or in ajax call url page – Ashu May 09 '17 at 10:47

1 Answers1

0
  1. Add attribute to your form tag: onsubmit="return false"
  2. Change buttons type from 'submit' to 'button'
  3. Your code should be like this:

    $(function(){ $('.Button').on('click', function (e) { e.preventDefault(); $.ajax({ type: 'POST', url: 'index.php', data: $('#myform').serialize(), success: function () { alert('The form was submitted successfully'); } }); }); });

P.S. Let me know if something going wrong let me know. ------- Updated ---------- Try this code:

<?php
 include '/Login/db_login.php';
 $page = 'index.php';

 if(isset($_POST['ContBt1'])){
     $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 1";
    mysqli_query($conn, $sql);
     mysqli_close($conn);
 }

 if(isset($_POST['ContBt2'])){
     $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 2";
    mysqli_query($conn, $sql);
     mysqli_close($conn);
 }

 if(isset($_POST['ContBt3'])){
     $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 3";
     mysqli_query($conn, $sql);
     mysqli_close($conn);
 }

 if(isset($_POST['ContBt4'])){
     $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 4";
     mysqli_query($conn, $sql);
     mysqli_close($conn);
 }

 if(isset($_POST['ContBt5'])){
     $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 5";
    mysqli_query($conn, $sql);
     mysqli_close($conn);
 }

 if(isset($_POST['ContBt6'])){
     $sql = "UPDATE senhas2 SET Contador=Contador+1 WHERE ID = 6";
    mysqli_query($conn, $sql);
     mysqli_close($conn);
 }
 if (isset($_POST['ContBt1']) || isset($_POST['ContBt2']) || isset($_POST['ContBt3']) || isset($_POST['ContBt4']) || isset($_POST['ContBt5']) || isset($_POST['ContBt6']))
    die();
 ?>
<!doctype>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Index</title>
    <link href="index.css" rel="stylesheet" type="text/css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body class="Background">
    <div class="BtLogin">
        <a href="Login/paginalogin.php">
            <input type="image" id="admin" src="http://i.imgur.com/I3D3nqm.png">
        </a>
    </div>
    <form action=""  id="myform" method="POST">
        <table class="Table">
            <tr>
                <td><input class="Button ButtonTxt" type="button" name="ContBt1"  value="A"></td>
                <td><input class="Button ButtonTxt" type="button" name="ContBt2"  value="B"></td>
            </tr>
            <tr>
                <td><input class="Button ButtonTxt" type="button" name="ContBt3"  value="C"></td>
                <td><input class="Button ButtonTxt" type="button" name="ContBt4"  value="D"></td>
            </tr>
            <tr>
                <td><input class="Button ButtonTxt" type="button" name="ContBt5"  value="E"></td>
                <td><input class="Button ButtonTxt" type="button" name="ContBt6"  value="F"></td>
            </tr>
        </table>
    </form>
    <script>
        $(function(){
            $('.Button').on('click', function (e) {
                e.preventDefault();
                var data = {};
                $("#myform input").each(function(){
                    data[$(this).attr("name")] = $(this).val();
                })
                $.ajax({
                    type: 'POST',
                    url: 'index.php',
                    data: data,
                    success: function () {
                        alert('The form was submitted successfully');
                    }
                });
            });
        });
    </script>
</body>
</html>
  • Still not working, opening Chrome's console, under the network tab, everytime I press a button a new entry "index.php" pops-up with the status code "200 OK". I guess my problem is on the url? The url is the one where you have the db connection strings and the queries right? Linking it to index.php should work I guess, as it includes the db_login and all the queries needed.. – Azazel May 09 '17 at 11:54
  • Updated and also added the db_login.php – Azazel May 09 '17 at 19:16