doupiao9318 2018-05-29 22:29
浏览 53

当使用javascript调用php函数时,Php $ _POST返回空

I am still studying php and java script. I am creating a simple contact form and set the form action to the same page using $_Server[php_self]

What I want to do is when someone submit to my form, it will show a message including the name that was submitted on the same page. replace the contact form with the message.

I also tried pointing action to a different php page. and it still did not work. Does Javascript work like that? or I have to use different code or language to do that.

Here is my code

<!DOCTYPE html>
<html>
<head>
    <?php 
    include 'action.php';
?>
    <title> My profle</title>
    <meta name="robots" content="noindex">
    <link rel="stylesheet" type="text/css" href="style.css">

</head>
<body>
<div class="contact">
   <form class="form" class="contact" id="contact-form" action="action.php" method="POST">
            Name: <br>
           <input type="text" class="field" name="name"><br>
           Number:<br>
           <input type="text" class="field" name="number"><br>
           Email:<br>
           <input type="email" class="field" name="email:>"<br>
           <br>
           <input type="submit" class="submit" name="submit" value="submit"
           onclick ="document.getElementById('contact-form').innerHTML='<?php thankyou();?>'">
       </form>
</div>
</body>
</html>

Then here is the action.php

<?php
    function thankyou(){
        $name = $_POST['name'];
        echo "Thank you"." $name ! Your message has been submitted.";
    }
?>

</div>
  • 写回答

2条回答 默认 最新

  • duanmeng3126 2018-05-29 22:34
    关注

    You have a couple of different problems here.

    The first is a lack of understanding about the timing of when PHP and JS run.

    The second is that DOM changes are lost when a new page is loaded.

    This is what is happening:

    1. The browser requests the page
    2. The PHP runs ($_POST does not have a name key)
    3. The browser gets the page
    4. You click the submit button
    5. The JavaScript runs, and set the innerHTML (remember that the PHP ran back at step 2)
    6. The form submits causing the browser to navigate to a new page
    7. The PHP runs again
    8. The browser gets the new page … and the DOM changes make to the previous page are lost

    Further reading: What is the difference between client-side and server-side programming?.

    评论

报告相同问题?

悬赏问题

  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面