I'm using Dynatree for the first time and wrote a PHP script that returns a properly formatted JSON array.
I've read the Dynatree documentation, but can't figure out how to pass in the JSON array from my PHP script so its contents can be loaded as the tree structure.
At the top of my HTML file, I'm using <?php include('tree.php') ?> which automatically returns the formatted JSON array (named $categories). I'd also be fine with calling a function from JavaScript to retrieve the tree if that makes it easier.
Can someone show me how to deliver my array to Dynatree?
You can use a data- attribute, like this:
<?php
$dynaConfig = array('children'=>array(
array('title' => 'Alice'),
array('title' => 'Bob')
));
$dynaConfigJSON = json_encode($dynaConfig);
// HTML head goes here
echo '<div id="tree" data-dyna="' . htmlspecialchars($dynaConfigJSON) . '">';
?>
<script>
$(function() {
var dtConfig = $.parseJSON($('#tree').attr('data-dyna'));
$('#tree').dynatree(dtConfig);
});
Here's a live example, and the corresponding full source code.
You can also separate the code of php in a file like tree.php and then call it in javascript.
<div id="tree"> </div>
<script type="text/javascript">
$(function(){
$("#tree").dynatree({
initAjax: {
url: "tree.php"
}
}
}
</script>
Related
Hi i have post form in jquery with php , the form call other page and get the result with json from jquery , for example when i use jquery and call to this page in php i get this for read json from jquery :
<?php
print '{"login":"datos_fails_lock"}';
?>
The problem in this case it´s i can only show this and no include other text in the results , if include more os this code the script no works , i like json detect this code but also i want show html and at the moment i can´t do this
It´s posible when i call other page from form of jquery i can include other informations as html and works json from this page
Sorry i explain the best i can
Regards !
Instead of printing your own json text layout, why not use PHP json_encode to do it for you. that way you can have the array you want including html and have that function encode it.
Example:
<?php
print json_encode(array('login' => 'datos_fails_lock'));
?>
At the PHP side:
<?php
// compute html
$html = '<div><p>...</p></div>';
// compute json
$json = '{"login":"datos_fails_lock"}';
$response = array('html' => $html, 'json' => $json);
print json_encode($response);
?>
At the JavaScript side:
var response = JSON.parse( xhr.responseText );
// append html to a div
$( '#response' ).html( response.html );
// parse json response
var jsonObj = JSON.parse( response.json );
To the best I can understand,
if you are looking to get json encoded values from your php file and show with jquery that called the file you do something like:
In you php file:
<?
echo json_encode(array(
'login' => 'datos_fails_lock',
'something_else' => 'Other thing'
));
?>
and from jQuery if it is post submission, you can use some thing like:
$.post('ajax/process.php', function(data) {
$('.result').html(data.login);
$('.other_thing').html(data.something_else);
});
The best inline solution:
<?php
$myObjectOrArray = (object) array('test' => array('test' => array('test' => 'testValue')));
$javascriptGateway = rawurlencode(json_encode(myObjectOrArray));
?>
<script type="text/javascript">
//<!--
var myObjectOrArray = JSON.stringify(unescape('<?php echo $javascriptGateway;?>'));
alert(myObjectOrArray.test.test.test); //result: testValue
//-->
</script>
I use this solution so I can pass my php object containing special char into a javascript object.
Section 1
I'm trying to return an Array from PHP (after having created the file using fwrite)
I include that file on my next .load method (inside a Div) the new PHP file contains an include 'somefile.php'; there is my array ... and I would simply try to collect from PHP and use it the array with JS....
I once saw something like this ...
$(function(){
alert('<?php for_each($array as $key => $value){
echo $value; // Just an example
}
?>')
});
I wrote this piece of code on the fly so there might be a few sytax errors;
This works fine using PHP inside JS ...
I'm not sure if I heard PHP loads first and then JS ? or was it the other way around ?
Section 2
How about using JS inside PHP ?
for example ....
<?php
echo "var myArray = New Array();"
echo "myArray = ('Apple','Banana','Orange','Kiwis');"
echo "return myArray";
?>
and then being able to fetch the data strait with JS ?
<script type="text/javascript">
for(i=0;i<myArray.length;i++){
alert(myArray[i]);
</script>
So how easy can I manipulate both languages in regards to RETURNING the array for example so it could be used in the global scope?
PHP runs first, so you can use it to write JavaScript code, that will get run once the page has been processed by the browser.
This would build JavaScript code with an array from PHP:
<script>
var myArray = <?php echo json_encode(array('apple', 'orange', 'kiwi'); ?>;
myArray.forEach(alert)
</script>
The other way around, passing data from JavaScript to PHP, can only be accomplished with some form of AJAX.
using PHP in JS : In short, you can echo the values in JS codes, e.g.
window.location = '<?php echo $url; ?>';
using JS in PHP : You can use AJAX . post the values to a PHP script
The PHP runs on the server, so from Javascript's point-of-view (running in the client's browser) it's like the PHP was never even there.
You can easily pass the PHP array to Javascript using PHP's json_encode() function:
$yourPHPArray = array("blah","blah","blah");
echo "var theArray=" . json_encode($yourPHPArray) . ";";
echo "for(var i=0;i<theArray.length;i++)";
echo "{";
echo " window.alert(theArray[i]);";
echo "}";
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now </button>
<script type="text/javascript">
function funk(){
alert("asdasd");
<?php echo "asdasda";?>
}
</script>
When the button is pressed I want to execute PHP code (at this point to echo asadasda)
You could use http://phpjs.org/ http://locutus.io/php/ it ports a bunch of PHP functionality to javascript, but if it's just echos, and the script is in a php file, you could do something like this:
alert("<?php echo "asdasda";?>");
don't worry about the shifty-looking use of double-quotes, PHP will render that before the browser sees it.
as for using ajax, the easiest way is to use a library, like jQuery. With that you can do:
$.ajax({
url: 'test.php',
success: function(data) {
$('.result').html(data);
}
});
and test.php would be:
<?php
echo 'asdasda';
?>
it would write the contents of test.php to whatever element has the result class.
Interaction of Javascript and PHP
We all grew up knowing that Javascript ran on the Client Side (ie the browser)
and PHP was a server side tool (ie the Server side). CLEARLY the two just cant interact.
But -- good news; it can be made to work and here's how.
The objective is to get some dynamic info (say server configuration items) from the server into the Javascript environment so it can be used when needed - - typically this implies DHTML modification to the presentation.
First, to clarify the DHTML usage I'll cite this DHTML example:
<script type="text/javascript">
function updateContent() {
var frameObj = document.getElementById("frameContent");
var y = (frameObj.contentWindow || frameObj.contentDocument);
if (y.document) y = y.document;
y.body.style.backgroundColor="red"; // demonstration of failure to alter the display
// create a default, simplistic alteration usinga fixed string.
var textMsg = 'Say good night Gracy';
y.write(textMsg);
y.body.style.backgroundColor="#00ee00"; // visual confirmation that the updateContent() was effective
}
</script>
Assuming we have an html file with the ID="frameContent" somewhere,
then we can alter the display with a simple < body onload="updateContent()" >
Golly gee; we don't need PHP to do that now do we! But that creates a structure for
applying PHP provided content.
We change the webpage in question into a PHTML type to allow the server side PHP access
to the content:
**foo.html becomes foo.phtml**
and we add to the top of that page. We also cause the php data to be loaded
into globals for later access - - like this:
<?php
global $msg1, $msg2, $textMsgPHP;
function getContent($filename) {
if ($theData = file_get_contents($filename, FALSE)) {
return "$theData";
} else {
echo "FAILED!";
}
}
function returnContent($filename) {
if ( $theData = getContent($filename) ) {
// this works ONLY if $theData is one linear line (ie remove all \n)
$textPHP = trim(preg_replace('/\r\n|\r|\n/', '', $theData));
return "$textPHP";
} else {
echo '<span class="ERR">Error opening source file :(\n</span>'; # $filename!\n";
}
}
// preload the dynamic contents now for use later in the javascript (somewhere)
$msg1 = returnContent('dummy_frame_data.txt');
$msg2 = returnContent('dummy_frame_data_0.txt');
$textMsgPHP = returnContent('dummy_frame_data_1.txt');
?>
Now our javascripts can get to the PHP globals like this:
// by accessig the globals
var textMsg = '< ? php global $textMsgPHP; echo "$textMsgPHP"; ? >';
In the javascript, replace
var textMsg = 'Say good night Gracy';
with:
// using php returnContent()
var textMsg = '< ? php $msgX = returnContent('dummy_div_data_3.txt'); echo "$msgX" ? >';
Summary:
the webpage to be modified MUST be a phtml or some php file
the first thing in that file MUST be the < ? php to get the dynamic data ?>
the php data MUST contain its own css styling (if content is in a frame)
the javascript to use the dynamic data must be in this same file
and we drop in/outof PHP as necessary to access the dynamic data
Notice:- use single quotes in the outer javascript and ONLY double quotes in the dynamic php data
To be resolved: calling updateContent() with a filename and
using it via onClick() instead of onLoad()
An example could be provided in the Sample_Dynamic_Frame.zip for your inspection, but didn't find a means to attach it
You can't run PHP with javascript. JavaScript is a client side technology (runs in the users browser) and PHP is a server side technology (run on the server).
If you want to do this you have to make an ajax request to a PHP script and have that return the results you are looking for.
Why do you want to do this?
If you just want to echo a message from PHP in a certain place on the page when the user clicks the button, you could do something like this:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
document.getElementById('resultMsg').innerHTML('<?php echo "asdasda";?>');
}
</script>
However, assuming your script needs to do some server-side processing such as adding the item to a cart, you may like to check out jQuery's http://api.jquery.com/load/ - use jQuery to load the path to the php script which does the processing. In your example you could do:
<button type="button" id="okButton" onclick="funk()" value="okButton">Order now</button>
<div id="resultMsg"></div>
<script type="text/javascript">
function funk(){
alert("asdasd");
$('#resultMsg').load('path/to/php/script/order_item.php');
}
</script>
This runs the php script and loads whatever message it returns into <div id="resultMsg">.
order_item.php would add the item to cart and just echo whatever message you would like displayed. To get the example working this will suffice as order_item.php:
<?php
// do adding to cart stuff here
echo 'Added to cart';
?>
For this to work you will need to include jQuery on your page, by adding this in your <head> tag:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
Any server side stuff such as php declaration must get evaluated in the host file (file with a .php extension) inside the script tags such as below
<script type="text/javascript">
var1 = "<?php echo 'Hello';?>";
</script>
Then in the .js file, you can use the variable
alert(var1);
If you try to evaluate php declaration in the .js file, it will NOT work
put your php into a hidden div and than call it with javascript
php part
<div id="mybox" style="visibility:hidden;"> some php here </div>
javascript part
var myfield = document.getElementById("mybox");
myfield.visibility = 'visible';
now, you can do anything with myfield...
We can use php in JavaScript by creating a form element and put the action as a .php page.
Then we use JavaScript to submit that form.
EX:
<!doctype html>
<html>
<head>
<title>PHP Executed with JS</title>
</head>
<body>
<form action="phpCode.php" id="phpCode">.
</form> <!-- This is the form-->
<script>
function runPhp() {
var php =
document.getElementById("phpCode")
php.submit() //submit the form
}
</script>
</body>
The PHP file name would be phpCode.php.
In that file would be your PHP code.
May be this way:
<?php
if($_SERVER['REQUEST_METHOD']=="POST") {
echo 'asdasda';
}
?>
<form method="post">
<button type="submit" id="okButton">Order now</button>
</form>
If you do not want to include the jquery library you can simple do the following
a) ad an iframe, size 0px so it is not visible, href is blank
b) execute this within your js code function
window.frames['iframename'].location.replace('http://....your.php');
This will execute the php script and you can for example make a database update...
Use ajax to send request and echo the response
when successfully executed. Like this:
$.get("site.com/ajax", function(status,data){
alert(status);
});
This can be achieved with jquery library.
You could run PHP at the start of the Page and grap the results from inputs
<?php
c = a * b;
?>
<input type="hidden" name="c" value="<?php c ?>"/>
<button type="submit">Submit</button>
</form>
<script>
let cValue = $('input[name="c"]').val();
alert(cValue);
</script>
I'm trying to figure out the least obtrusive and least computationally expensive way to store PHP objects coming from my MySQL database such that their data can be rendered by JavaScript on click by a user.
Currently, I'm storing the data as custom attributes on a button. But this generates a lot of code and I've heard is "slow". I'm wondering if I should JSON encode my PHP object, $items (see below), and how that JavaScript would then look. Note I'm using Codeigniter for the PHP so that's what up with the alternate foreach loop syntax.
Here's where I'm at so far with the HTML/PHP:
<img id="img"></img><a id="url"></a> <!--elements where data is rendered on click-->
<? foreach($items as $item):?>
<button data-id="<?=$item->id?>" data-url="<?=$item->url?>" data-img="<?=$item->img?>">click<?=$item->id?></button>
<?endforeach;?>
And here's my JS:
$(document.body).on('click', 'button', function(){
var $this=$(this), id=$this.data('id'), url=$this.data('url'), img=$this.data('img');
$('#img').attr('src', img);
$('#url').attr('href', url).html(url);
});
Most of my site's data is coming from PHP via MySQL and I've long been confused by the issue of when should I convert that data to a JavaScript array/JSON or not.
If you json_encode your $items array (assuming it only consists of data you will want in JS), you can assign this to a JS variable:
<script>var items = <?php echo json_encode($items); ?></script>
You can then remove the data-url and data-img attributes. Then, within your JS code:
var $this = $(this), id = $this.data('id'), url = items[id].url, img = items[id].img;
// the rest of your code
Edit: when you move the click handler in a separate file, you would get something like this:
function setup_click(items) {
var $img = $('#img'), $url = $('#url');
$('button').click(function(evt) {
var id = $(this).data('id'),
url = String(items[id].url),
img=String(items[id].img);
$url.attr('href', url).html(url);
$img.attr('src', img);
});
}
here's a JSfiddle showing off the javascript/JSON part: http://jsfiddle.net/fz5ZT/55/
To call this in one shot from your template:
<script src="[your ext script file path].js"></script>
<script>setup_click(<?php echo json_encode($items); ?>);</script>
Hope that helps :)
I've got a JSON value that has been converted from a JavaScript object using JSON.stringify. I'm trying to parse the contents of the JSON using PHP, but I haven't had any luck. I'm sure I'm doing something really basic wrong.
In file1.php, I've got something like:
<html>
<head>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script src='/json2.js'></script>
<script>
var irxmlnewsreleases = new Array();
irxmlnewsreleases[0]={
"attachmentfileid":12039
};
var news_release = JSON.stringify(irxmlnewsreleases);
$(document).ready(function () {
$("#response").text(news_release);
});
</script>
</head>
<body>
<div id="response"></div>
</body>
</html>
I'm then trying to read this data from file1.php using json_decode in file2.php.
I tried first (wrongly) using file_get_contents and have been bashing at this for a while without success. I guess the issue is obviously that the JSON value doesn't exist until the JavaScript is run, so PHP is of course never able to read the value of the jQuery-generated div content. What I don't know is how to get that value.
The JSON is being generated successfully in file1.php and is valid JSON (I've run it through jsonlint).
What's a better way of getting the value of that dynamically-generated JSON into PHP?
$(document).ready(function () {
$("#response").text(news_release);
$.post('file2.php', { php_post_var1: news_release }, function (data) {
//do something with the PHP script output here if you want
});
});
Then in your PHP script file2.php do something like
<?php
$news_release = $_POST['php_post_var1'];
echo 'PHP received ' . $news_release;
?>