Solution 1 :

By putting the “event.preventDefault()” inside your function, you are actually telling that function to not execute the form submission. You didn’t put your whole code here so I can only guess that you put the “script” tag on your header or above the elements that needs to be hidden. I would suggest that you put the “script” tag just above the “/body” tag, you know at the very end of your program, so it can render all the elements first before executing the javascript function.

Problem :

What I’m trying to do is that a button click calls a php function which does something and also calls a javascript function which checks if the button was clicked and makes div’s invisible and visible.

This is the ‘form’

    <form id="form1" action="<?=$_SERVER['PHP_SELF'];?>" method="post">
      <button type="submit" id="jahrgang1" name="j1" class="btn jahrgang1">Jahrgang 1</button><br>
      <button type="submit" id="jahrgang2" name="j2" class="btn jahrgang2">Jahrgang 2</button><br>
      <button type="submit" id="jahrgang3" name="j3" class="btn jahrgang3">Jahrgang 3</button><br>
      <button type="submit" id="jahrgang4" name="j4" class="btn jahrgang4">Jahrgang 4</button><br>
    </form>

Here’s where I want to execute the php function by clicking on the submit buttons. This calls a simple php function.

if(array_key_exists('j1', $_POST)) { 
 j1();
}
if(array_key_exists('j2', $_POST)) { 
 j2();
}
if(array_key_exists('j3', $_POST)) { 
 j3();
}
if(array_key_exists('j4', $_POST)) { 
 j4();
}

And here is whats in my javaScript file.

const form1 = document.getElementById("form1");
form1.addEventListener("submit", einfachBtn)

function einfachBtn() {
 startseiteContainerElement.classList.add("hide")
 schwierigkeitContainerElement.classList.add("hide")
 anleitungContainerElement.classList.add("hide")
 aufgabeEinfachContainerElement.classList.remove("hide")
 hptmContainerElement.classList.remove("hide")
}

If I do it like this, the php function gets called and you can see that the JavaScript code does get executed and hides the divs and shows other for a split second but then goes back to how it was before and it was like the JavaScript function wasnt called.

However if i do it like that, only the JavaScript code gets executed and the php function doesn’t:

function einfachBtn(event) {
  event.preventDefault();
  startseiteContainerElement.classList.add("hide")
  schwierigkeitContainerElement.classList.add("hide")
  anleitungContainerElement.classList.add("hide")
  aufgabeEinfachContainerElement.classList.remove("hide")
  hptmContainerElement.classList.remove("hide")
}

Is there any solution on how I can execute with one button both of these functions?

Thanks in advance!

Comments

Comment posted by Triby

You need to use AJAX to call the PHP without page reloading.

By