dongman2721 2017-02-10 05:50
浏览 45
已采纳

在javascript函数中对数据库执行php插入

I'm having a page home.php which has a button 'UPDATE'.
1. onclick function of 'UPDATE' should call a javascript function 'write()'.
2. 'write()' function get's the username and a value - both from the session (php comes in use here) and write it to a database.

Here is the code : home.php

<html>
<head>
  <title> Sample Page </title>
</head>

<body>

<script>

function write(){
  <?php

   include("dbConnect.php"); // connection works perfectly with other php files
   // gets 'latestValue' from session variable
   // gets 'username' from session variable
   // updates 'patients' table with the latestValue, against the username
   $query = "UPDATE patients SET lastLDNId = '$_SESSION[latestValue]' WHERE username='$_SESSION[username]'";
   $result = mysqli_query($con,  $query);

  ?>
}

</script>

<input type="button" onclick="write()" value="UPDATE">

</body>
</html>

When i run the code and checking by Inspecting element, I'm getting the following error in the function write(), as the browser interprets it

function writeLDN(lDNId){
  <br />
<b>Notice</b>:  Undefined index: latestValue in     <b>C:\xampp\htdocs\MedPhil\home.php</b> on line <b>98</b><br />
}

When i remove the php part inside the javascript function, the above error is not generated, which means it's not possible to use php in the way I've used.

Can anyone give me a solution other than echoing the whole script content using php?

Thanks in advance

  • 写回答

1条回答 默认 最新

  • dtgsl60240 2017-02-10 06:01
    关注

    I am sorry, but you have a serious misunderstanding regarding server side code vs client side code. In your technology stack PHP is executed only on the server, and only once when the page is requested, JavaScript is executed only on the client side and only there.

    So your attempt to "call" php from javascript cannot work. This is the sequence this gets processed:

    1. The server sees your <?php marker tag and executes the php code in there replacing it with the result of the php code, which in this instance is an error message.
    2. The page gets delivered to the browser (client)
    3. The browser tries to execute the JavaScript code, which is just a php error message, in other words garbage.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示