How to connect frontend (js) and backend (php) in a local application? - javascript

So confused about how to connect frontend and backend?
Suppose I've got an object obj and var jsonText = JSON.stringify(obj);
how can I send this jsonText to backend (locally, non remote server, no database), using php to get this data and then save the content as a single new JSON file?
Thanks a lot!

You need to query your data from a database or from somewhere else in PHP. Then, you can echo it with PHP in a JSON format. In a second step, you can use jQuery or plain JavaScript to make an Ajax call to this PHP file and make something with it.
PHP (data.json.php):
<?php
header('Content-Type: application/json');
$output = array();
// query the data from somewhere
$output['data'] = "1234";
echo json_encode($output); // json_encode creates the json-specific formatting
?>
JavaScript (jQuery):
$.ajax({
url: "data.json.php",
success: function(result){
console.log(result);
}
});
The code is untested, but I think you should get the idea.

Related

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

covert a php array to json object , then back to array in javascript [duplicate]

I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database.
I take the values from the db with this code (file.php):
$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
$array[]=$data['Latitude'];
$array[]=$data['Longitude'];
}
echo $array;
and I call with ajax with this code:
$.post('./file.php',
function( result ){
alert(result);
});
but even if in the script php the array is correct (if I echo array[25] I obtain the right value) in Javascript I obtain "Undefined".
How can I get the array in correct way??
thanks!
edit: after encoded with json_encode($array); in php and JSON.parse(result) in javascript seems not working.
In the console I have the array, but I can't access to its values. (Array[0] gave me "undefined").
use this
echo json_encode($array);
on server side
and
var arr=JSON.parse(result);
on client side
As Ruslan Polutsygan mentioned, you cen use
echo json_encode($array);
on the PHP Side.
On the Javascript-Side you can simply add the DataType to the $.post()-Function:
$.post(
'./file.php',
function( result ){
console.log(result);
},
'json'
);
and the result-Parameter is the parsed JSON-Data.
You can also set the correct Content-Type in your PHP Script. Then jQuery should automaticly parse the JSON Data returned from your PHP Script:
header('Content-type: application/json');
See
http://api.jquery.com/jQuery.post/
http://de3.php.net/json_encode
You need to convert the php array to json, try:
echo json_encode($array);
jQuery should be able to see it's json being returned and create a javascript object out of it automatically.
$.post('./file.php', function(result)
{
$.each(result, function()
{
console.log(this.Latitude + ":" + this.Longitude);
});
});

Return JSON object from php script

I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});

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!

Working with javascript array

Hi I have a php script that successfully gets an array of data from an exsternal xml source, the array is called $file, I know that the php array is populated by using print_r($file).
I have tried to use the following php to pass to a javascript session:
//Convert to JSON Array
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
But either this hasn't worked, or the following JS code below is wrong:
var jsonarray = result["json_array"];
alert(JSON.stringify(jsonarray));
Could someone please tell me where I am going wrong?
You should not use JSON.stringify there. JSON.parse is what you are looking for. Since you want to parse existing JSON, not create new JSON.
edit: Your code is a bit odd. I'd think you want something like this
php
//Convert to JSON Array
echo json_encode($file, JSON_FORCE_OBJECT);
js
alert(JSON.parse(data)); // Where data is the contents you've fetched from the server
You have to encapsulate php code :
<?php
$jsonarray = json_encode($file, JSON_FORCE_OBJECT);
$result["json_array"]=$jsonarray;
?>
var jsonarray = <?= $result["json_array"] ?>;
alert(JSON.parse(jsonarray));

Categories

Resources