dongman2721 2017-02-09 21: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-09 22: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.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部