Home > OS >  Why my simple form is not sending post data in php?
Why my simple form is not sending post data in php?

Time:04-16

I'm trying to send data over post request, but the post array seems to be empty. I've tried all the methods i.e., get, post, and request but I'm getting the same result all the time, please help me sort this out.

Here is my code snippet:

Html File:

 <form action="question-paper.php" method="post">
    <input type="hidden"  name="quespaper" value="formValue"/>
    <button type="button" onclick="openExam();"  style="margin- 
      top:15px;"> Start </button>
</form>

PHP File:

print("Post array<br>");
var_dump($_POST);

JavaScript code:

function openExam(){
   window.open('question-paper.php', '_blank');
}

CodePudding user response:

Apparently the code below would call a JavaScript function. That function would then maybe be responsible to submit the form, so maybe add that code as we cannot see it on your post.

<button type="button" onclick="openExam();"

Alternatively you can remove the onclick="openExam();" part and just add the parameter type="submit" to the button, then it will submit the form immediately when pressed

CodePudding user response:

 <form action="question-paper.php" method="post">
     <input type="hidden"  name="quespaper" value="formValue"/>
     <button type="submit"  style="margin-top:15px;"> Start </button>
</form>

I changed the type from button to submit. It will automatically go to the file mentioned in the action of the form tag.

I am sure it works.

CodePudding user response:

If your openexam works, then no need to have a form at all OR not need to have JavaScript

So EITHER this (which will send the hidden field) - add the method="post" if needed. If post IS needed, then you cannot use the window.location

<form action="question-paper.php" target="_blank">
  <input type="hidden"  name="quespaper" value="formValue"/>
   <button type="submit"  
  style="margin-top:15px;"> Start </button>
</form>

OR

  <button type="button" onclick="openExam()" style="btn btn-outline-success" 
  style="margin-top:15px;"> Start </button>
  • Related