php encoded json to template and javascript - 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!

Related

Datatables - add rows with PHP

I have an issue with jquery and datatables. I want to get the informations for the datatable from an mysql database with PHP and after that update the datatable with this informations.
I already tried it with something like this:
var datatable = $("#example").DataTable();
$.get('load_session_overview.php', function(newDataArray) {
//datatable.clear();
datatable.row.add(['Random','12','18','Menu']);
datatable.row.add([newDataArray]);
datatable.draw();
});
The first line with the add is working fine, but I don't know how to format the data in the php script correctly.
And if I'm getting more rows from the php script how can I add them all the the table?
Thanks, Phil
One way to format the data correctly in your PHP script is to return it in a JSON format. You can use the json_encode() function in PHP to convert your data into a JSON string.
For example:
<?php
$data = array(
array('Random','12','18','Menu'),
array('Data1','13','19','Menu2'),
array('Data2','14','20','Menu3')
);
echo json_encode($data);
?>
Then, in your jQuery code, you can use the JSON.parse() method to convert the JSON string into a JavaScript object, and loop through the data to add each row to the table.
$.get('load_session_overview.php',
function(newDataArray) {
var data = JSON.parse(newDataArray);
for(var i = 0; i < data.length; i++) {
datatable.row.add(data[i]);
}
datatable.draw();
});
Alternatively, you can use ajax call and pass the data to it to load it in the datatable and also you can use the ajax call to update the datatable as well.
$.ajax({
url: "load_session_overview.php",
type: "GET",
dataType: "json",
success: function (data) {
datatable.clear();
datatable.rows.add(data);
datatable.draw();
}
});
This way you can load the data in the datatable and also update it as well.
There are several ways to achieve this, for instance
php writes javascript code in an html script tag
see How to print JSON array inside script tag?
XHR request
see Displaying JSON data in HTML

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.
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)); ?>");

How to pass json array of one page into another in php?

i have a php page p1.php where in a JavaScript function i have got some json array as j now i want to use this j to another php page p2.php
i have tried it by
window.location.href="p2.php?data="+j
then in p2.php
i used $_get['data'] to get the result
but after researching i come to know the format is not good for huge data.
so
i leave the idea of passing it into the url
if your j is object then you can post with jquery
example :
$.post("p2.php", { datavar : j},function(data){
})
in your p2.php
print_r( $_POST["datavar"]);
echo $_POST["datavar"]["var2"];
it's depends of many data you can move, but always is ugly send pure data by url.
But in your example, only miss transform the json (object) to string:
window.location.href="p2.php?data="+JSON.stringify(j);
If you can go in the right way, store the info in a session:
http://php.net/manual/es/reserved.variables.session.php
Then the p1.php looks like these:
<?php
session_start();
$_SESSION['json'] = isset($_POST['json']) ? $_POST['json'] : null;
// other php stuffs
?>
<!-- other html stuffs -->
<script>
var json = { your: 'json' };
(function(){
var xhr = new XMLHttpRequest();
var data = encodeURIComponent(JSON.stringify(json));
xhr.open('post', 'p1.php');
xhr.send('json='+data);
})();
</script>
These code send the info (json) via AJAX to p1.php

Using data from a PHP array in AJAX

I'm making a change to the way a site works and trying to find a solution that requires as little re-writing as possible.
At the moment, I have a file (myFile.php) which loads (using Wordpress) into a page. It uses a PHP array for outputting data. The PHP array is $property_list_featured_search and the content looks something like this:
<?php
foreach($property_list_featured_search as $individual_property){
?>
<span><?php echo $individual_property['info']['status'] ?></span>
<?php
}
?>
So in my small example, it's outputting data from $property_list_featured_search and this works OK.
My problem is that I now want to load the HTML&PHP above using jQuery AJAX. When a user clicks a button, it loads the HTML (which is stored in a file, called myFile.php into a div on the page:
function loadView(view){
$.ajax({
type: "POST",
url: 'path/to/file/property-search/myFile.php',
data: property_data,
success: function(result)
{
$("#search-page-content").html(result);
});
}
In the case above, property_data is the $property_list_featured_search data localized using Wordpress so that the file can access it. I have tested it and can confirm that the file loaded in with AJAX is able to see the data. My problem is that I now have a file with PHP echo everywhere and the data in JSON format.
Is it possible to still use this data in this way? I'm guessing because the data is JSON that it's not possible to use echo $data[key] at all like it was in the original file?
What's the best way to output all the data in the JSON file on the page?
You can try something like this:
When u get your data:
$checked = $_POST['property_data'];
$checked = array('first' => $checked[0], 'second' => $checked[1], 'third' => $checked[2], 'forth' => $checked[3]);
Then you can echo it like this:
$checked['first'], $checked['second'] and so on.
Hope this helps

Echo php content into API javascript?

I would need to echo php variables (from the server and related to service behaviour) into javascript. For example, "ssl" => "true" and adapt accordingly in javascript. The thing is I'm doing this for some API files I'm writing and I want the client to have direct access to these files (<script src="... .js">) and this forces me to hardcode info that might change in the future across multiple file references. What I'd like to do was something like this, is it possible? (the content to fetch must remain completely private - from the server folders to the php script files - and so it is really not an option to fetch this info using javascript):
api.js
<? //PHP here. (I know...)
(...)
?>
//some javascript
var is_secure = <? echo "true"/"false" ?>
(...)
So that when doing <script src="api.js"/> the user only fetches:
var is_secure = "true";
(...)
or
var is_secure = "false";
(...)
Any idea on how I could do something similar? Thank you very much...
You could just create your PHP file with this line before everything :
header("Content-Type: application/javascript");
EDIT:
I did misunderstood the question. If you want js in an php file, you should do it like this:
header("Content-Type: application/javascript");
OLD ANSWER:
I don't know if you know, but client can't see your php code...
So if You'd:
echo "Something"
The client would only see Something.
It's not clear, what you're trying to do...
If you don't want to see Something when you go directly into your "secret" php page, then you should do it like this:
JS:
jQuery.ajax({
type: "POST",
url: 'secretfile.php',
dataType: 'html',
data: {apiRequest: 1},
success: function (response) {
yourVar = response;
}
});
PHP:
If ($_POST['apiRequest']==1){
echo "Something";
}
yourVar would be = "Something"
If you'd go to this page, it wouldn't display anything;

Categories

Resources