开发者

How to make the JS function get the data from the database everytime I call it?

开发者 https://www.devze.com 2023-04-09 09:28 出处:网络
I am using a code look like this: <script> function getdata() { varemployee = <?php //connect to database and get employee na开发者_如何学JAVAme

I am using a code look like this:

<script>
  function getdata() 
  {
  var  employee = 
    <?php 
//connect to database and get employee na开发者_如何学JAVAme
    echo "'" . $row['empnm'] "'";
    ?>;
  }
</script>
<a href="#" onclick="getdata();">print them</a>

It works, but the function is running the PHP code only on the page loading and not every time I call the function. So, if the target employee name is changed the JS function will show the old name untill the page is reloaded. How to make the JS function get the data from the database everytime I call it?


look into a library like jQuery

Then using the following code

function getdata(){
  $.post("path/to/file.php", function(data) {
        var employee = data;
        // do whatever with the data.
  });
}

and you can still use your same html

<a href="#" onclick="getdata();">print them</a>

and file.php

<?php

// connect to your db, get your results, echo them back
echo $row['empnm'];
 ?>


When you first request the page, PHP renders out a whole string of html, then your browser executes that generated HTML, not the original PHP. i.e. your server is going to send something like

<script>
  function getdata() 
  {
  var  employee = 
    "hello world";
  }
</script>
<a href="#" onclick="getdata();">print them</a>

So, as far as the web browser knows, "hello world" is just hardcoded there.

You'll need to look into AJAX for how to make it work. Check out this beginners' tutorial on using jQuery for ajax: http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/


Define a global variable

<script>
    var employee = <?php echo "'" . $row['empnm'] "'";?>;
    function getdata(){
        return employee;
    }
</script>

Now keep on changing variable employee whenever it is changed

<a href="#" onclick="getdata();">print them</a>


If you're in a PHP loop -- it does looks like you are, since -- you can use PHP to define the parameter to be passed into getdata() in your loop; e.g.

<script type="text/javascript">
function getdata(employee) {
    // connect to database and get employee name
}
</script>

<?php
foreach ($loopData as $row) {
    print '<a href="#" onclick="getdata(' . $row['empnm'] . ');">print them</a>';
}
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消