Pass a PHP array to a JavaScript function [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I am trying to get a PHP array variable into a JavaScript variable.
This is my code:
<html>
<head>
<script type="text/javascript">
function drawChart(row,day,week,month,date)
{
// Some code...
}
</script>
</head>
<body>
<?php
for($counter = 0; $counter<count($au); $counter++)
{
switch($au[$counter]->id)
{
case pageID.'/insights/page_active_users/day':
$day[] = $au[$counter]->value;
break;
case pageID.'/insights/page_active_users/week':
$week[] = $au[$counter]->value;
break;
case pageID.'/insights/page_active_users/month':
$month[] = $au[$counter]->value;
break;
}
}
?>
<script>
drawChart(600/50, '<?php echo $day; ?>', '<?php echo $week; ?>', '<?php echo $month; ?>', '<?php echo createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day')))); ?>');
</script>
</body>
</html>
I can't get value of the PHP array.
How do I fix this problem?

Use JSON.
In the following example $php_variable can be any PHP variable.
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
In your code, you could use like the following:
drawChart(600/50, <?php echo json_encode($day); ?>, ...)
In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..) like the below:
var s = "<JSON-String>";
var obj = JSON.parse(s);

You can pass PHP arrays to JavaScript using json_encode PHP function.
<?php
$phpArray = array(
0 => "Mon",
1 => "Tue",
2 => "Wed",
3 => "Thu",
4 => "Fri",
5 => "Sat",
6 => "Sun",
)
?>
<script type="text/javascript">
var jArray = <?php echo json_encode($phpArray); ?>;
for(var i=0; i<jArray.length; i++){
alert(jArray[i]);
}
</script>

Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here
$employee = array(
"employee_id" => 10011,
"Name" => "Nathan",
"Skills" =>
array(
"analyzing",
"documentation" =>
array(
"desktop",
"mobile"
)
)
);
Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{
"employee_id": 10011,
"Name": "Nathan",
"Skills": {
"0": "analyzing",
"documentation": [
"desktop",
"mobile"
]
}
}
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
url: "employee.php",
async: false,
cache: false,
data: {
employee_id: 10011
},
success: function (jsonString) {
var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
});

In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:
<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);
<!-- Then pass it to the JavaScript function: -->
drawChart(<?php echo count($day); ?>, day, week, month);
</script>

Related

Pass PHP values to Jquery Calendar

I am working on a JQuery event calendar that I would like to populate with multiple values from PHP. I've got a foreach pulling all PHP values needed, but I'm not sure how to properly populate the events array in JQuery with the values that I have PHP gathering.
Thanks in advance for any advice here.
Here is the PHP foreach that gathers all of the event data needed.
<?php foreach ($collection as $content) : ?>
<?php
$eventTitle = $content->getData('title');
$ogDate = $content -> render('mmedia_library_publish_date', array('type' => 'date_short'));
// REFORMAT DATES FROM PHP TO A CALENDAR FRIENDLY FORMAT
$newDate = date('Y-d-m', strtotime($ogDate));
echo $newDate;
?>
<?php endforeach; ?>
Here is the jQuery that populates the calendar, with some dummy events in-place, for reference on the formatting that is needed.
<script type="text/javascript">
require([
'jquery',
'calendar-gc',
'domReady!'
], function ($) {
require(['jquery'],function(e){
var calendar = $("#calendar").calendarGC({
dayBegin: 0,
prevIcon: '<',
nextIcon: '>',
onPrevMonth: function (e) {
console.log("prev");
console.log(e)
},
onNextMonth: function (e) {
console.log("next");
console.log(e)
},
// *********** ADD EVENTS FROM PHP HERE *************
events: [
{
date: new Date("2022-03-15"),
eventName: "EVENT 1",
className: "badge bg-danger",
onclick(e, data) {
console.log(data);
},
dateColor: "red"
},
{
date: new Date("2022-03-20"),
eventName: "EVENT 2",
className: "badge bg-danger",
onclick(e, data) {
console.log(data);
},
dateColor: "red"
},
{
date: new Date("2022-03-22"),
eventName: "EVENT 3",
className: "badge bg-success",
onclick(e, data) {
console.log(data);
},
dateColor: "green"
}
],
onclickDate: function (e, data) {
console.log(e, data);
}
});
})
});
</script>
Not that I recommend this approach but can you try something like
//...
$dateArr = [];
foreach () {
...
$dateArr[] = $newDate;
..
}
echo sprintf('<script>let eventStr = %s;</script>', implode(',', $dateArr));
and then later or at the end of page,
let cal = [];
let dates = eventStr.split(',');
dates.forEach(date => cal.push({
date: new Date(date),
eventName: "EVENT 2",
className: "badge bg-danger",
onclick(e, data) {
console.log(data);
},
dateColor: "red"
})
);
haven't tested it but something like this will make values available on the page and then when you initialize the calendar, you can use that array instead.
var calendar = $("#calendar").calendarGC({
...
...
events: cal,
...
});
Just wanted to post my solution to the original question. The comment/post from Adison Masih pointed me in the right direction (thank you), along with extensive searching, trial and error to get the array to display as needed in jquery.
Hopefully, this will help someone else out there that is looking to perform a similar task.
I ended-up building the array in PHP and format the date with the following code:
<?php $eventData = array(); ?>
<?php
$eventTitle = '<a class="eventCalTitle" href="'.$content->getLinkUrl().'">' .$content->getData('title'). '</a>';
$ogDate = $content -> render('mmedia_library_publish_date', array('type' => 'date_short'));
$newDate = date('Y-m-d', strtotime($ogDate));
$jDate = $newDate;
$tempArray = array("date" => $jDate, "eventName" => $eventTitle, "className" => "badge", "dateColor" => "#006fba");
array_push($eventData, $tempArray)
?>
After the PHP array is created, I then pass the array to jQuery, using json_encode, then further modifying the date objects, adding the new Date() function and then populating the events array with my custom event data:
const jsonData = <?php echo json_encode($eventData); ?>;
$.each(jsonData, function( i, obj ) {
var dateOrig = obj.date;
obj.date = new Date(dateOrig);
});
const option = {
dayBegin: 0,
};
option["events"] = jsonData;
$("#calendar").calendarGC(option)

Ajax result as array and JSON.parse error

I have coded an ajax request and the data is returned as an array to be used in a timepicker.
Ajax Call:
<script type="text/javascript">
$.ajaxSetup({ cache: false });
var consultdate;
var userid;
var cat;
var timezone;
var consultstart;
var consultend;
$('#consultdate').change(function() {
consultdate = $('#consultdate').val();
userid= '<?php echo $user_id;?>';
cat = '<?php echo $category;?>';
timezone = '<?php echo $time_zone;?>';
consultstart = '<?php echo $consultation_start;?>';
consultend = '<?php echo $consultation_end;?>';
//alert(consultdate);
$.ajax({
type: "POST",
url: 'user_date-time_qry.php',
cache: false,
dataType : "text",
data: {consultdate : consultdate, userid : userid, cat : cat, timezone : timezone, consultstart : consultstart, consultend: consultend },
success: function(data)
{
if (!$('input#consulttime').data("set")) {
alert(data);
var result = $.parseJSON(data);
$("input#consulttime").val('');
$('input#consulttime').prop("disabled", false);
$('input#consulttime').timepicker('remove').timepicker({'timeFormat': 'h:i A','disableTextInput': true, 'minTime':result[0] ,'maxTime': '<?php echo $consultation_end; ?>','step': 15,'disableTimeRanges':result[1]});
}
},
error : function() {
alert("Error while loading data");
}
});
});
</script>
I expect var result to be an array of json encoded values, which is used in minTime as result[0] and disableTimeRanges as result[1]
The relevant portion of user_date-time_qry.php is as follows:
UPDATED: user_date-time_qry.php
$consultation_start = '"'.$consultation_start. '"';
$consult_time_UTC = '['.implode(',',$consult_time_UTC).']';
$prebooked_time_UTC = $consult_time_UTC ; //require format as ['8.30 AM', '8.45 AM'], ['12:15 PM', '12:30 PM']
echo $result = array($consultation_start, $prebooked_time_UTC);
$result = array($consultation_start, $prebooked_time_UTC);
foreach ($result as $results) {
echo $results;
}
In console
Getting value as "06:00 PM"[]
"06:00 PM" is value 1 && [] is value 2. How to get it as separate values in ajax response ?
Update:
Since i am unable to comprehend it, trying another solution with 2 ajax calls. Thanks for all the feedback anyway.
Change this line
echo $result = array($consultation_start, $prebooked_time_UTC);
to this
$result = array($consultation_start, $prebooked_time_UTC);
echo json_encode($result);
Actually to get data in JSON format in PHP you can just store all the data in an array and use json_encode function to convert them.
The issue is here:
echo $result = array($consultation_start, $prebooked_time_UTC);
you cannot echo an array, instead you have to use json_encode like:
echo json_encode(array($consultation_start, $prebooked_time_UTC));
and do not wrap the values in quotes like:
'"'.$consultation_start. '"'
simple way:--
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.
Example Like:--
$.ajax({
type: "POST",
url: 'user_date-time_qry.php',
cache: false,
dataType : "json",
data: {consultdate : consultdate, userid : userid, cat : cat, timezone : timezone, consultstart : consultstart, consultend: consultend },
success: function(data)
{
//ENTER CODE
},
error : function() {
alert("Error while loading data");
}
});
Anoter example using this way:--
user_date-time_qry.php file all convert into json format using below example all array convert into json format using this way:--
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
echo json_encode($marks);
?>
These respone provide (ALL DATA CONVERT INTO JSON FORMAT):--
{"mohammad":{"physics":35,"maths":30,"chemistry":39},"qadir":{"physics":30,"maths":32,"chemistry":29},"zara":{"physics":31,"maths":22,"chemistry":39}}

ajax return single variable and an array variable

I have a comment form that requests a newtimestamp and newcomment variables. The newtimestamp variable is a single variable and the newcomment variable is an array returned from a foreach loop.
ajaxrequest.php:
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp = $now;
$newcomment = "<div class=post>$var1</div>";
echo json_encode(array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment));
}
I then use ajax to prepend the new comment's and set the newtimestamp on a hidden input field.
ajax:
<script>
$(document).ready(function(){
$('#commentform').on('submit',function(e) {
$.ajax({
url:'ajaxrequest.php',
data:$(this).serialize(),
type:'POST',
dataType: 'JSON',
success:function(data, response){
$("#posts").fadeOut(300);
$("#posts").prepend(data.newcomment);
$("#time").val(data.newtimestamp);
$("#posts").fadeIn(500);
$('html, body').animate({ scrollTop: $('#posts').offset().top - 100 }, 'fast');
console.log(data);
},
error:function(data){
console.log(data);
}
});
e.preventDefault();
return false;
});
});
The above method gives me a success message in console, the prepend works but only shows 1 result everytime when it should show all results from the last timestamp. The prepend and setting the value of the hidden input field do not work if the user posts a second, third etc comment.
console:
Object {newtimestamp: "2014-11-19 07:59:48", newcomment: "<div>a new comment</div> 1"}
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
Object {readyState: 4, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
I need to return the newtimestamp variable as a single variable (not an array) and set this on a hidden input field value, and I need to return the newcomment variable as an array that can be prepended to a div.
How can I do this?
Change your php file. I am not sure this is you are expecting.
ajaxrequest.php:
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp[] = $now;
$newcomment[] = "<div class=post>$var1</div>";
}
echo json_encode(array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment));
Rewrite your php code like this
$data = array();
foreach ($array2 as $print2) {
$var1 = $print2['var'];
$newtimestamp = $now;
$newcomment = "<div class=post>$var1</div>";
$data['data'][] = array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment);
}
echo json_encode($data);
now the JSON response will look something like
{"data" : [{"newtimestamp" : 72345654,"newcomment" : "comment data"},{"newtimestamp" : 72345654,"newcomment" : "comment data"}]}
loop through array of objects using jQuery each. The final code will look something like this.
$.each($response.data,function(index,value){
$("#posts").prepend(value.newcomment);
$("#time").val(value.newtimestamp);
})
NOTE: either send application/json header (so that the response will be parsed and converted to an js object by default) or parse it after receiving. This action should happen before the each loop
That's because you are echo multiple JSON string. You need to echo a single JSON string with all data.
Try something like the code below, this worked for me. You only need to fit this into your jQuery and PHP code.
<?php
$jsonArray = array();
$array2 = array(array('var'=>1),array('var'=>2));
foreach ($array2 as $print2)
{
$var1 = $print2['var'];
$newtimestamp = time();
$newcomment = "<div class=post>$var1</div>";
$jsonArray[] = array('newtimestamp' => $newtimestamp, 'newcomment' => $newcomment);
}
print_r($jsonArray);
$data = json_encode($jsonArray);
?>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
var data = jQuery.parseJSON('<?=$data?>');
$.each(data, function(item, value){
console.log(value['newtimestamp']);
});
</script>

Pass array with ajax and php

I need to add a class to some elements based on the time without page reload
I am creating this array when the page loads. I have a start time, an end time and an identifier.
$hrs = array(
array("2013-07-27 21:00", "2013-07-27 22:00", "one"),
array("2013-07-27 22:00", "2013-07-27 23:00", "two"),
array("2013-07-27 23:00", "2013-07-28 00:00", "three"),
);
Then I get the current time and grab the identifier from the array. I tried running this script in a separate file time.php using setInterval but I can't pass $hrs.
<ul>
<li class="one">1</li>
<li class="two">2</li>
<li class="three">3</li>
</ul>
var className = "<?php echo $class_name"; ?>
$(className).addClass("red");
what is the proper way of running this so I won't need to refresh the page? I did something like this but it alerts error:
* Working code below ****
<script>
var hrs = '<?php echo json_encode($hrs); ?>';
//get active class from time.php
$.ajax({
url : 'http://domain.com/time.php',
type : 'POST',
data : { val : hrs },
dataType : 'json',
success : function (result) {
className = result['current_class'];
},
error : function () {
alert("error");
}
})
</script>
time.php
$hrs = json_decode($_POST['val']);
date_default_timezone_set('Europe/Bucharest');
$date = date('Y/m/d H:i');
$test = strtotime($date);
$now = date("Y-m-d H:i", $test);
$class_name = "";
foreach ($_POST['val'] as $h) {
if ($h[0] <= $now and $now <= $h[1]) {
$class_name = $h[2];fa
break;
}
}
$class = array(
'current_class' => ( $class_name ),
);
echo json_encode($class);
If you are sending data using POST
type : 'POST',
You have to access it using $_POST, you are using $_GET.
$_POST['val']
Replace:
var hrs = '<?php echo $hrs; ?>';
To:
var hrs = '<?php echo json_encode($hrs) ?>';
Neither language has any clue about the internals of the other language, your best bet to pass a full array is to encode the AJAX side array to JSON, pass that to your PHP script, and then use json_decode to decode it into a PHP array.
You could also try passing the parameters with square brackets on the end, with the same name as php interprets this as an array. i.e.
file.php?p[]=1&p[]=2&p[]=3&p[]=4&p[]=5
Would result in $_GET['p'] being a 5 item array containing 1 - 5.
The same is also true of post, if you post multiple p[]'s, you will end up with $_POST['p'] as an array of all your elements.

Trying to get integer out of json for current time comparison

<?php
date_default_timezone_set('America/Los_Angeles');
$date = date('Gi', time());
?>
<script type="text/javascript">
var locTime = <?php echo json_encode($date) ?>;
var jTime = null;
$.getJSON( "urltojson", function(result) {
console.log("sucess1");
jTime = result["crossroads"]["monday"][0];
console.log("sucess2");
console.log(jTime)
})
</script>
json -
{ "crossroads":
{
"monday": [
{"breakfastopen": 700},
{"breakfastclose": 1100},
{"lunchopen": 1100},
{"lunchclose": 1400},
{"dinneropen": 1700},
{"dinnerclose": 2100}
]
}
}
in console jTime output is always
Object {breakfastopen: 700}
How do i get jTime to trim down and show only '700'?
What I'm trying to do is get the local hours to compare with the integer in json array. So far i have no luck of brining the json variable to jTime and have it compare against locTime.
It should be returning an object so to get access it should be
data.crossroads.monday[0].breakfastopen
{} denote objects [] are arrays

Categories