David
David

Reputation: 57

How to pass arguments from JS function to PHP code

I want to pass js function arguments "checklistNoteId" and "checklistNoteStatus" to PHP variable, so I can change things in database. What code should I write to pass those arguments? I have tried to do it but it doesn't work. An example of my problem is bellow:

EDIT: I've tried this, but it didn't help me.

JS CODE:

checklistFinishedBtn.onclick = function(e){
     let noteId = Number(e.target.parentNode.getAttribute('checklist-id'));
     if (checklistArray.checklistItems[noteId].isDone){
         changeChecklistNoteStatus(checklistArray.checklistItems[noteId].id, 0);
     } else {
         changeChecklistNoteStatus(checklistArray.checklistItems[noteId].id, 1);
     }
     }

PHP CODE:

<head>
<script>
    function changeChecklistNoteStatus(checklistNoteId, checklistNoteStatus){
        console.log(checklistNoteId);       //this returns 26 (which is correct)
        console.log(checklistNoteStatus);   //this returns 1 (which is correct)
        <?php
        //if I set these values manually, it works
        $status = "<script>document.write(checklistNoteStatus)</script>"; 
        $id = "<script>document.write(checklistNoteId)</script>";
        $sql = 'UPDATE checklist_notes SET isDone = :isDone WHERE id = :id';
        $statement = $pdo->prepare($sql);
        $statement->execute(['isDone' => $status,'id' => $id]);
        ?>
    }
</script>
</head>

After this, the database remains untouched. (I am trying to set the note with id 26 to change isDone variable on button click.) The screen from database is here: enter image description here

Upvotes: 0

Views: 58

Answers (1)

Eric Brown
Eric Brown

Reputation: 1462

It's important to know the difference between client side code and server side code. PHP is server side, which means it will run on the server before it's sent to the client. Javascript is client side, which means it will run when the client receives the code. Because of this, javascript can never write anything directly to PHP because the PHP script has already been run before the client even receives the webpage.

In order to send something client side back to the server, you will need to send a Request. The most common way to do this is with a form element with a method=POST and an action pointed to a php file you want to receive. Here is a simple example: https://www.w3schools.com/tags/att_form_method.asp

If you want it to run in the background, I would recommend looking up AJAX requests and how to perform those instead. It's the same concept, but there is a little more to them.

Upvotes: 1

Related Questions