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

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.

We have mainly two methods to pass php value to javascript variable
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>
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

use the javascript ajax to call a php api
pass your data at php in your view file , use something like:
var phpData = JSON.parse("<?php echo json_encode($data)); ?>");

Related

Is there a way to get create a php varialble from ajax data returned from another php script

I have a php script that creates a webpage with my select box options
Eg index.php has a html select box:
<select id="sel_option">
<option value="0">- Select Option -</option> ....
this is posted on sel_option change using ajax to a php processing script as below:
<script type="text/javascript">
$(document).ready(function(){
$("#sel_option").change(function(){
var optionid = $(this).val();
$.ajax({
url: 'procscript.php',
type: 'post',
data: {option:optionid},
dataType: 'json',
success:function(response){ ...
I would like to pull some of the returned array into Php variables again in order to change some of the tabulator group or format options
eg $("#table1").tabulator({
height:500 ,
VirtualDomHoz:true,
<? echo "groupBy:[\"group_option_from_response array\"]," ?>
So Php script1 sends option data by ajax -> php script2 which gathers data from a mysql db and returns to script1
I have tried creating session variables in php script 2 and it works on first selection , but after that it seems to cache the initial sessions in the browser , the response sessions from the second php script do not seem to copy over to the first script in subsequent calls. I think it might because the first page never reloads , all selections are done within the loaded first page using js??
If what I am trying to do is if not possible by php can I rewrite the php section in tabulator below using some js code?
$("#table1").tabulator({
height:500 ,
VirtualDomHoz:true,
<? echo "groupBy:[\"group_option_from_response array\"]," ?>
placeholder:"No Data Set",
columns:[
{title:"ID", field:"ID",width:30},
{title:"F_name", field:"f_name", sorter:"string"},
<? echo "{title:\"different var\", field:\"field2\", sorter:"string"},"; ?>
Thanks for looking !
Steve
Receive your data through ajax, then create the tabulator object. If there is data coming through ajax for that object, you can add it in, then instantiate it.
success:function(response){ ...
response = JSON.parse(response);
createTabulator(response,"table1")
});
function createTabulator(data, idToUse) {
var tabobject = {
height:500 ,
VirtualDomHoz:true,
placeholder:"No Data Set"
}
if (data.groupBy) {
tabobject.groupBy = [data.groupBy]
}
var cols = [
{title:"ID", field:"ID",width:30},
{title:"F_name", field:"f_name", sorter:"string"}
]
// if there is columns data coming in, bring it as an array...
data.columns.forEach(item => {
cols.push({title: item.title, field: item.field, sorter:"string"})
})
tabobject.columns = cols;
$("#"+idToUse).tabulator(tabobject);
}
There are so many ways to achieve what you want. I think the best way is just to push the variable to the ajax request.
$.ajax({
...
data: {
option:optionid,
groupoption: "groupoptionvalue"
}
...
});
The first time you just have to send it empty. PHP will always be able to handle the value since you will always capture it at the very beginning.
If your variable is an object or an array, just use JSON.parse/JSON.stringify in javascript and json_encode/json_decode in PHP for them to communicate.

How to pass resource from php to javascript

So I have three different separate files:
functions.php (all functions for the database)
main.html (my main program)
main.js (all javascript functions)
Now, I want to call a function in PHP through AJAX. To do that, I need to pass $conn.
$conn = sqlsrv_connect($serverName, $connectionInfo);
It's a resource, so I can't use json_encode.
The way I set the everything up now is that the php-file is required in the html so I can use the functions and when I change the
value of a dropdown, the js is called.
How can I pass the $conn variable to Javascript?
Regards
It doesn't work like that.
You should never be directly making calls to the database from the front-end.
Think of it as three separate levels. Your HTML/JS is the front-end, your PHP is your server, and your Database is on its own level.
So when the user does something on the front-end, say changes the value of a field and you want to update that in the database the following actions should happen:
Event triggers on JS
AJAX is called as a result of the event being triggered
PHP server receives the AJAX request and executes code to modify database
(optional) PHP server sends something back to the front-end to tell it that the request was successful
Read up on the concept of MVC: https://developer.mozilla.org/en-US/docs/Web/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture
Try this in php code as I assume functions.php
$conn = sqlsrv_connect($serverName, $connectionInfo);
echo $conn;//Don't try echo anything other
In Javascript
$.ajax({
type: "POST",
url: "functions.php",
success: function(data)
{
var conn = data; // here is your conn which comes from php file
}
});
First of all include jquery latest version from cdn
Create an API Url, and use POST method
site.com/api/insert.php // to insert into table
Use $.post() api of jquery to send data
var url = ""; // enter your URL HERE
var postData = {}; // object of post data with table name, cols and values
$.post(url, postData, function(data, status) {
// do what ever you want with data
})
ps: you can also create diff insertion / selection / update / delete api for different table. (recommended)
Read more about $.post() here

How to take javascript variable in php mysql query?

I am new to Javascript and PHP. Can anyone let me know how to take javascript variable in php variable and I want to use that php variable in MySQL query to fetch the data from MySQL database. Whether it is possible to take javascript variable directly in MySQL query?
I have tried but I am unable to get the result. I have attached code below
<script>
var baccount = document.getElementById('accountid');
var bacc = baccount.value;
</script>
<?php
$abcd = '"+bacc+"';
$quer=mysql_query("SELECT * from fpay_user where account_id='$abcd'");
$result=mysql_fetch_array($quer);
$rbal = $result['balance'];
echo $rbal;
?>
You need understand the difference of client language and server language.
In your code, JavaScript is executed in browser, while the PHP is executed in your server. To make the PHP knows what happened in the client, your client must send this information to the server, through query string, form post or raw data post.
For your case, you can send an Ajax request from the JavaScript to the server, (using native XMLHttpRequest, or jQuery)
$.ajax({
type: "POST",
url: url,
data: {bacc:value},
});
Then your PHP can access it via $_POST["bacc"]
Do understand that although you could write it in the same file (which is a bad practice), they are executed in different place (client or server)
It is not as simple as that. Javascript runs in the browser (the client) and php runs on the web server (the host). These are two different computers. To pass data from the client to the host, you can make an an http request from javascript to a specific url on the server. When the server sends its response you can process it in javascript again.
An example (using jQuery) would be:
<script>
// success will be called when the server sent a response.
function success(result) {
// result.responseJSON is a javascript object: { balance: 1234 }
let balance = result.responseJSON.balance
}
$.ajax({
url: '/path/to/script.php',
data: {
bacc: baccount.value
},
success: success,
dataType: 'json'
});
</script>
In php you can fetch the passed value, do your query and return the result:
<?php
// get the passed value
$abcd = $_GET['bacc'];
// do the query SAFELY. See explanation below.
$quer = mysql_query("SELECT * from fpay_user where account_id='" . mysql_escape_string($abcd) . "'");
$result=mysql_fetch_array($quer);
// Now return the result as json string
header('Content-Type: application/json');
// This will encode the result as: "{balance: 1234}"
echo json_encode($result);
One very important thing. You should always sanitize the received values with something like mysql_escape_string. If you do not do that, your software is susceptible to SQL injection. I have added this function call to your example.

php encoded json to template and javascript

I'm using Codeigniter and Smarty (template engine) and therefore using templates.
I have a method that calls the template which has all html, css and js functions:
public function index()
{
//dashboard text
$this->data['title'] = 'Dashboard';
$this->data['subtitle'] = 'feeds, users, and more';
//load the donut graph data
$fbyg = $this->feed_model->countFeedsByGroups();
echo json_encode($fbyg);
//parses the dashboard template
$this->smartyci->display('dashboard.tpl', $this->data);
}
the thing is that I need to send some information to one of the js files bounded to my dashboard.tpl in order to render a graphic.
So I know I have to encode the php array into jSon object and send it to the template. But, how do I do this when I have not only to send and echo with the json but also I have to display my template sending for it other information?
The other question is, How do I receive the json and get the data? I'm trying and so far no results:
From my dashboard.tpl:
<script src="{site_url()}application/views/js/test.js"></script>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script>
From test.js:
$.getJSON('admin.php', function(data) {
console.log(data.vgro_name);
});
You could set it like
$this->data['fbyg'] = json_encode($fbyg);
And then in your javascript do
var yourVar = <?php echo $fbyg ?>;
A cleaner solution would be to make an ajax call to a function that will return something like
$fbyg = $this->feed_model->countFeedsByGroups();
echo json_encode($fbyg);
after the page has loaded.
Edit jQuery ajax get:
$.ajax({
type: "GET",
url: "urlToYourFunction",
success: function(data){
var yourVar = data;
}
});
I've only ever made get and post requests with angularjs and jquery, but here's another stackoverflow post detailing how to do it with regular javascript:
https://stackoverflow.com/a/18078705/3739551
I hope this helps!

Ajax after success, how to pass data to a variable to php

I have script like this
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
I don't know how I can pass data response to php code ?
For Example: if I alert response, it's show 123 .so I want pass value 123 to a variable in php
$id = 123
response is the result passed BY php, not TO php. What's passed to php is the id and the task.
In your tab.php, you can access these two values :
<?php
$id = $_POST['id'];
$task = $_POST['task'];
//do anything you want with it...
?>
This is not the right workflow. PHP executes on runtime, so every time the page has finished loading you can't really put variables back into PHP (unless you reload the page). This is where AJAX comes in, so you can call PHP scripts from JavaScript / jQuery and don't have to reload the page every time.
The right thing to do is to either store the variable you have generated in the tab.php script in a database, $_SESSION, $_COOKIE or something similar like so:
//put this at the top of all your php scripts you want to use the variable in
session_start();
//now store the variable you wanted to pass (in tab.php)
$_SESSION['returnValue'] = $myValue;
Now if you want to use the variable in other pages just echo it like so (remember to add session_start() at the top of the PHP script.
echo $_SESSION['returnValue'];
First of all, start by reading this
To answer your question,
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
The result from id and task are sent via $_POST (type:"POST") to the page tab.php (url:"./tab.php"). If you want to do that on a different page, just change the url in your ajax call: url:"./any_other_page.php" and the posted values will be sent there
Finally, read THIS post as well. It is greatly written and very well explained.
Hope it helps!
Keep on coding!
Ares.

Categories

Resources