1

Have been working on a form with Ajax and used to work on a version with no extras (css and so on) before. It worked all fine, data has been inserted successfully into the database and I have been able to show and hide two divs. Now I used to apply it to the form I've been working on. It acts different from the previous version, so it's exactly the same (sure, changed some names, added some inputs), like no "success message" from the PHP-file, suddenly all data visible in the URL, the current form doesn't hide and shows the next one.

I can't understand the sudden change in behavior, took a look for mistakes, compared the codes, but have no idea. It seems to be such a small mistake that I don't spot it or something is wrong with the whole construction.

The current file is:

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<?
require 'config.php';
session_start();

// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
  $_SESSION['message'] = "You must log in before viewing your profile page!";
  header("location: error.php");    
}
else {
    // Makes it easier to read

    $id = $_SESSION['id'];
    $name = $_SESSION['name'];
    $email = $_SESSION['email'];
    $active = $_SESSION['active'];
    $hash = $_SESSION['hash'];
}


?>


<script type="text/javascript">
function getState(val) {
  $.ajax({
  type: "POST",
  url: "demo_ajax.php",
  data:'country_id='+val,
  success: function(data){
    $("#region").html(data);
  }
  });
}

$(document).ready(function(){
  $("#submit").click(function(){

    var size=$("#size").val();
    var industry=$("#industry").val();
    var country=$("#country").val();
    var region=$("#region").val();
    var url=$("#website").val();    
    var fb=$("#fb").val();
    var lkdn=$("#lkdn").val(); 

    $.ajax({
      type:"post",
      url:"process2.php",
      data:"size="+size+"&industry="+industry+"&country="+country+"&region="+region+"&url="+url+"&fb="+fb+"&lkdn="+lkdn,
      success:function(data){
       $("#theform").hide();  
       $("#info").html(data);   
       //$("#partone").css();     
       $("#partone").show();

       alert("Hello");
     }
   });
  });
});




</script>  
  <?php include 'js/js.html'; ?>
  <?php include 'css/css.html'; ?>

</head>

<body class="w3-blue r_login_corp_body">
<div id="info" style="color:white"></div>
<div class="r_login_corp_body"></div>

<div class="w3-content w3-white r_siu r_centered_div">
        <header class="w3-camo-black w3-container">
            <div class="w3-container ">
                <span class="w3-xlarge r_caption">eRecruiter</span>         <span class="large">Corporate Login</span>
            </div>

            <div class="w3-black">
                <a href="javascript:void(0)" onclick="selectForm('register');">
                  <div class="w3-half tablink w3-hover-text-yellow w3-padding w3-center w3-padding-16">Register</div>
                </a>
            </div>              
        </header>   

  <!--  Register -->
  <div id="register" role="form" class="r_form_elements">
        <form  name="formone"  class="form"  autocomplete="off">
          <div id="profed" class="w3-container w3-padding-16">
              <div class="alert alert-error"></div>

              <label>Company Industry</label>
                <input class="w3-input" name="industry" id="industry" type="text" placeholder="Your Industry" >

              <label>Company Size</label>
                <input class="w3-input" name="size" id="size" type="integer" placeholder="Your Company Size" >

              <label >Country:</label>
                <select name="country" id="country" class="demoInputBox" onChange="getState(this.value);" >
                  <option value="">Select Country</option>
                    <?php       
                      $sql1="SELECT * FROM pentagonal_country";
                          $results=$mysqli->query($sql1); 
                      while($rs=$results->fetch_assoc()) { 
                      ?>
                      <option value="<?php echo $rs["country_code"]; ?>"><?php echo $rs["country_name"]; ?></option>
                      <?php
                      }
                    ?>
                </select>

              <label>State:</label>
                <select id="region" name="region" onKeyup="checkform()">
                <option value="">Select State</option>
                </select>

              <label>Website</label>
                <input class="w3-input" name="website" id="website" type="url" placeholder="Your Website-Address" >

              <label>Facebook</label>
                <input class="w3-input" name="fb" id="fb" type="url" placeholder="https://facebook.com/" >

              <label>Linkedin</label>
                <input class="w3-input" name="lkdn" id="lkdn" type="url" placeholder="https://linkedin.com/in/">                                      
          </div>
      <div class="w3-row">
        <button type="submit" id="submit" class="w3-button w3-black w3-half w3-hover-yellow" >Add</button>
        <button class="w3-button w3-black w3-half w3-hover-pale-yellow">Forgot Password</button>

      </div>
    </form>
  </div>
  <!--  Register -->
  <div id="partone" style="display:none">
        <form>
               name : <input type="text" name="name" id="name">
               </br>
               message : <input type="text" name="message" id="message">
               </br>

               </br>
               name : <input type="text" name="url" id="url">
               </br>
               message : <input type="text" name="fb" id="fb">
               </br>
               name : <input type="text" name="lkdn" id="lkdn">
               </br>

               </br>                                             </br>
               Send;

        </form>      
</div>
</div> 


</body>
</html>

and the PHP-file to insert data is:

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

session_start();

// Check if user is logged in using the session variable
if ( $_SESSION['logged_in'] != 1 ) {
  $_SESSION['message'] = "You must log in before viewing your profile page!";
  header("location: error.php");    
}
else {
    // Makes it easier to read

    $id = $_SESSION['id'];
    $name = $_SESSION['name'];
    $email = $_SESSION['email'];
    $active = $_SESSION['active'];
    $hash = $_SESSION['hash'];
}

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

  $industry=$_POST["industry"];
  $size=$_POST["size"];
  $country=$_POST["country"];
  $region=$_POST["region"];      
  $website=$_POST["url"];
  $fb=$_POST["fb"];
  $lkdn=$_POST["lkdn"];
  $usrid=$id; 

$sql = "INSERT INTO corp_user_profile (id, industry, size, nation, region, url, facebook, linkedin)  
VALUES ('$usrid', '$industry','$size', '$country', '$region', '$website', '$fb', '$lkdn')";


if (mysqli_query($conn, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

mysqli_close($conn);
?>

I used to work with the previous file I've worked with just to be sure that everything's right after a week of bug fixing.

Can somebody tell me where the problem is, probably why it is a mistake to avoid future problems like this?

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
nucky
  • 348
  • 5
  • 15
  • [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Jul 14 '17 at 12:48
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Jul 14 '17 at 12:50
  • Where are you setting your session variables? – Jay Blanchard Jul 14 '17 at 12:50

2 Answers2

1

You may want to prevent the default behavior by passing the event to your click function and calling event.preventDefault().

vi5ion
  • 1,028
  • 7
  • 11
  • "Submitting the form could have changed the url of the page which causes your ajax url to be different as well since you're using a relative url" . This is irrelevant because a) the form doesn't specify and action and so will postback to itself, keeping the URL the same, and b) the ajax will never run anyway because posting back the page destroys the page and any javascript which was running on it. And on the next refresh, even if the same script is restored, it will still never get chance to execute. – ADyson Jul 14 '17 at 13:03
  • I removed that line because you're right about the URL. I've just made a testcase and the ajax request definitely still gets triggered though. – vi5ion Jul 14 '17 at 13:21
  • That's true it may do if the page doesn't post back _immediately_, so agreed my previous statement may be a little too absolute, but you'll likely never get a response before the full postback. Doesn't stop it screwing things up on the server though by submitting the same data twice! Either way we both came up with the same solution which I'm sure will solve it. – ADyson Jul 14 '17 at 13:23
  • Also to you a big thanks, vi5ion, you gave me the right answer, too. – nucky Jul 14 '17 at 15:15
1

The most obvious bug (aside from the SQL injection stuff mentioned above) is that <button type="submit" will cause the form to submit normally via postback, unless you prevent it using script. Add event.preventDefault() to the first line of your "click" handler.

$("#submit").click(function(event){
    event.preventDefault(); //prevent default postback behaviour
    var size=$("#size").val();
//...etc

You're seeing the data in the URL because the form is posting normally (before the ajax has chance to run) and doing a GET because there's no other method specified in the form's markup, and GET is the default..

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • 1
    It works! Thanks ADyson for solution and explanation. Now it works. And I've learned something. – nucky Jul 14 '17 at 15:14