简体   繁体   中英

How do I transfer the PHP variables to another javascript file?

So my goal is to use PHP to get data from a PostGreSQL database. I want to use this data in a separate javascript file so I can display it on the screen a certain way that I have my website configured. All the tutorials that I have seen online just puts a script tag inside the PHP file but I cannot do that because my website display javascript code is in the separate file. I just need the numbers to be in the javascript file that I got from the PHP file that got its data from the PostGreSQL database. How can I do this?

I just need help with the means to get to the ends because I have researched on my own but it is always not exactly what I want.

PHP:

<?php
$myPDO = new PDO('pgsql:host=myHost; dbname=myDBName', 'myUsername', 'myPassword');
?>

$result = $myPDO->query("SELECT * FROM table WHERE id = 'someID'");

Now I want to use this row's values in another javascript file. How can I do this?

You could use Ajax for this. You could so something like this in your JS file:

$.ajax({
    type: "GET",
    url: 'FILENAME.php',
    success: function(data){
        alert(data);
    }
});

and then in your FILENAME.PHP just return the values.

Your JS should then pull through whatever has been returned, in this case, your database query.

Your JS file needs to request the data from your PHP controller, via an AJAX request. You can then manipulate the returned data object whichever way you like.

  1. use the javascript ajax to call a php api

  2. pass your data at php in your view file , use something like:

var phpData = JSON.parse("<?php echo json_encode($data)); ?>");

We have mainly two methods to pass php value to javascript variable

  1. Simple variable method at the time of first page load
<script>
  var js_variable = <?php echo $data_php_variable; ?> ;
  //this is working only at the first time of the page load
  //you can also parse the data to any format
</script>
  1. Use AJAX call to trigger a PHP request and manipulate return PHP value in JS
$.ajax({
    type: "GET", //get or post method
    url: 'FILENAME.php',   //php request url
    data :{}, //optional ,you can send data with request

    success: function(res){ 
        // this 'res' variable is the php return data in the form of js data 
        console.log(res);
    }
});

ajax method is more dynamic ,it can use any time request handling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM