dongman2721
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
    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.
    点赞 评论

相关推荐