-1

I created a modal form (that pops up upon a link click, i.e trigger()). This is the HTML code:

<div class="modalbg">
      <div class="modalPopup">
        <form action="samepage.php" class="formContainer" method="post">
          <h2>Change Desk Number</h2>
          <label for="studentid">
            <strong></strong>
          </label>
          <input type="password" placeholder="Your KEY" name="studentid" required/>
          <label id="status" style="color:red;"></label>
          <button type="submit" class="btn" onclick="return verify()">Upgrade</button>
          <button type="button" class="btn cancel" onclick="closeForm()">Close</button>
        </form>
      </div>
</div>

The JavaScript that controls this modal is:

function trigger(){

    document.getElementById("modalPopup").style.display = "block";
            
        
          }
          function closeForm() {
            document.getElementById("modalPopup").style.display = "none";
          }
          function verify() {
                var studentid = document.getElementById("studentid").value;
            if (studentid != dbstudentid || !studentid){
                document.getElementById("status").innerHTML="Invalid Student ID!";
                function trigger(event) { event.preventDefault(); } 
                return false;
                }
            else{
                document.getElementById("modalPopup").submit();
            }
          }

Everything works at this point (i.e it pops up whenever I click the link and whenever I knowingly try to enter a wrong studentid, it returns the "Invalid student ID" on the "status" label. (Note: I had already saved the session's student ID in the variable dbstudentid using:

var dbstudentid = <?php echo json_encode($dbstudenid);?>;

My problem however comes from when I try to execute the PHP on the same page.

Whenever I insert the PHP code into the modalbg div or modalPopup div inside it, the entire modal refuses to pop, let alone submit.

This is the PHP code I used (it should be noted that at the beginning of the page, I had already used include(configure-db.php) and session_start() ) :

<?php


if(isset($_POST['studentid'])){
  $studentid = $_POST['studentid'];
  $desk = 1;
  $deskstatus ="";
        
  $select = "UPDATE users SET deskNo = '$desk' WHERE name='$SESSION';
}

if (mysqli_query($MyConn, $select)) {
  $deskstatus = "Desk changed successfully!";
} else {
  $deskstatus = "Error";
} return $deskstatus;
?>

I have tried everything, the modal just refuses to come every time, let alone successfully make the Desk Update on my Database. to make things worse, whenever I refresh the page, the modal which I set to display:none; by default on CSS suddenly starts showing. But whenever I remove the PHP code, it returns to normal.

Do I need to make the action execute in a separate page? If yes, please how? Else, how please?

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • Missing `"` at the end of the $select =... line, you should have a syntax error. And learn to use prepared statements and parameters, because code is full of security and other holes – ADyson Jun 28 '22 at 17:37
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/32391315) – Dharman Jul 01 '22 at 13:30

1 Answers1

-1

I world highly suggest you think about using AJAX to handle this probolem. let's clear up things.

  1. you can write var dbstudentid = '<?= $dbstudenid ?>'; instead of var dbstudentid = <?php echo json_encode($dbstudenid);?>; this will give you freedom of JS native datatype.

  2. you need to send this form request through ajax and recive output there.

  3. Change the php code else part to like this

    else { $deskstatus = "Error: " . mysqli_error($MyConn); }

Now when there is a actual problem on code you will know what was the problem. and it will not break you interface. 4. Create seperate file that handle this form request. 5. Here is code snippet of plaing JS AJAX implementation

let post = JSON.stringify(postObj)

const url = "https://jsonplaceholder.typicode.com/posts"
let xhr = new XMLHttpRequest()

xhr.open('POST', url, true)
xhr.setRequestHeader('Content-type', 'application/json; charset=UTF-8')
xhr.send(post);

xhr.onload = function () {
    if(xhr.status === 201) {
        console.log("Post successfully created!");
        let AlertDiv = document.querySelector('#alert');
        AlertDiv.innerHTML =  xhr.response; 
    }
}
Hafijul Islam
  • 24
  • 1
  • 5
  • Thanks for the response. I have never used Ajax before, sadly, so I don't understand how to implement the above code you posted. Also. I don't know where to include the action page and return a value from a variable after it has been executed. – Chibuike Ezeiru Jun 28 '22 at 20:38
  • 1
    Okey. The postObj is a JS Object variable containing all form fields data. The url is the value of your form action attribute. Try adding console.log on (xhr.response). Last just echo the variable after executing of php it will be received as response by browser. – Hafijul Islam Jun 29 '22 at 21:20