Answer the question
In order to leave comments, you need to log in
How to transfer a variable from a PHP file to a JS file?
The problem is allegedly solved by Google, but for some reason I can not solve it.
I have 2 files, one gives data from the server (php), the other (js) in which I should use the received data. Well, let's say we get something like this (this is an example):
<?php
$data = array(
array(
'title' => 'Arduino #1',
'id' => 1,
'image' => 'http://www.casemods.ru/templates/images/texts/3_4119479.jpg',
'top' => 200,
'left' => 300,
'width' => 800,
'height' => 760,
'points' => array(
'id' => 1,
'objectId' => 1,
'top' => 300,
'left' => 500,
'tip' => 500,
),
),
array(
'title' => 'Arduino #2',
'id' => 2,
'image' => 'img/objects/arduino.png',
'top' => 200,
'left' => 300,
'width' => 800,
'height' => 760,
'points' => array(
'id' => 1,
'objectId' => 2,
'top' => 300,
'left' => 500,
'tip' => 500,
),
)
);
echo json_encode($data);
Answer the question
In order to leave comments, you need to log in
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: 'http://test_php_json_page/',
dataType: 'json'
}).done(function(data){
$.each(data, function(key, value){
console.log(key, ' :', value);
})
}).fail(function(){
console.log('error');
});
});
</script>
<?php
$data = 'some_var_for_js';
?>
<html>
<head>
<script type="text/javascript">
var data = <?php echo $data; ?>;
</script>
</head>
...
<?php
$data = array(
array(
'title' => 'Arduino #1',
'id' => 1,
'image' => 'http://www.casemods.ru/templates/images/texts/3_4119479.jpg',
'top' => 200,
'left' => 300,
'width' => 800,
'height' => 760,
'points' => array(
'id' => 1,
'objectId' => 1,
'top' => 300,
'left' => 500,
'tip' => 500,
),
),
array(
'title' => 'Arduino #2',
'id' => 2,
'image' => 'img/objects/arduino.png',
'top' => 200,
'left' => 300,
'width' => 800,
'height' => 760,
'points' => array(
'id' => 1,
'objectId' => 2,
'top' => 300,
'left' => 500,
'tip' => 500,
),
)
);
?>
<script type="text/javascript">
var data = <?php echo json_encode($data); ?>;
console.log(data[0]["title"]);
</script>
CJavaScript::encode($var)
https://github.com/yiisoft/yii/blob/1.1.14/framewo...
The server (php) cannot send anything, it can only respond. Make a request to the server on the Ajax page and return data with a variable using json. If this answer does not suit you, then you need to improve your knowledge of web development.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question