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 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀