send data from php to javascript [duplicate] - javascript

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a question regarding data transmission from php to javascript. I gather some data from database and I format them like this:
for($i=0;$i<(sizeof($lt_periods_query['period_id']));$i++){
$period_id = $lt_periods_query['period_id'][$i];
$lt_id = $lt_periods_query['lt_id'][$i];
$period_name = $lt_periods_query['period_name'][$i];
$fDate = $lt_periods_query['fromDate'][$i];
$tDate = $lt_periods_query['toDate'][$i];
$minStay = $lt_periods_query['min_stay'][$i];
$nightly_rate= $lt_periods_query['nightly_rate'][$i];
if (strStartsWith($fDate, $currentYear)=='true'){
$year = $currentYear;
} else if(strStartsWith($fDate, $nextYear)=='true'){
$year = $nextYear;
}
$temp_period_details = array();
$temp_period_details['period_id'] = $period_id;
$temp_period_details['lt_id'] = $lt_id;
$temp_period_details['period_name'] = $period_name;
$temp_period_details['fromDate'] = $fDate;
$temp_period_details['toDate'] = $tDate;
$temp_period_details['min_stay'] = $minStay;
$temp_period_details['nightly_rate'] = $nightly_rate;
$periods[$year][$period_name] = $temp_period_details;
}
And I am able to see them when I print as like this:
echo "RULE for 6 days <br>";
$days= '5';
$selPeriod = 'off_peak';
$selYear = '2011';
echo $periods[$selYear][$selPeriod]['period_id'];
echo "<br>";
echo $periods[$selYear][$selPeriod]['lt_id'];
echo "<br>";
echo $periods[$selYear][$selPeriod]['period_name'];
I know that php is working on the server side and javascript is working on the client side.
I want to get the data from javascript side by sending some parameters like this (I know why this is not working but I do not know how I can achieve such data transfers):
<script type="text/javascript">
$(function(){
getData();
function getData(){
var days= '5';
var selPeriod = 'off_peak';
var selYear = '2011';
//var xxx = '<?php echo $periods[\''+selYear+'\'][\''+selPeriod+'\'][\'fromDate\'] ;?>';
//var xxx = '<?php include($periods['2011']['off_peak'][''])?>;
}
});
Can anyone advice me a way to gather data from php to javascript by sending some parameters.

To communicate data structures from PHP to Javascript, inject a JSON value like this:
<?php
$xdata = array(
'foo' => 'bar',
'baz' => array('green','blue')
);
?>
<script type="text/javascript">
var xdata = <?php echo json_encode($xdata); ?>;
alert(xdata['foo']);
alert(xdata['baz'][0]);
// Dot notation can be used if key/name is simple:
alert(xdata.foo);
alert(xdata.baz[0]);
</script>
This can be used to properly escape scalars, arrays, objects, etc.

There's the AJAX method, and there's the echoing method. The former is more flexible, while the latter is a lot simpler and doesn't require you to cope with AJAX errors.
For the former, there are plenty of examples around the place on how to use AJAX. The latter can be achieved quite simply:
<script type="text/javascript">
var phpVar = <?php echo ($phpVar); ?>;
</script>
Which approach is approporite depends on what data your javascript needs and what it needs it for. If you're needing to do a lot of server interaction, then working with AJAX is the avenue you should be investigating. However, if all you need is an initial value to initialize a javascript, then the latter approach is a lot easier to implement.

Simple AJAX approach.
Put all your data into single array. Then use json_encode to encode your data to JSON format.
$data_array = array();
//assigning your data to single array here
$data_array['param1'] = 'value1';
echo json_encode($data_array);
Then in your JavaScript code use AJAX to call you script. For example use great jQuery library for this (http://api.jquery.com/jQuery.getJSON/).
<script type="text/javascript">
$.getJSON('http://www.example.com/my_script.php', function(data) {
alert(data.param1); //this should alert 'value1'
});

Related

send data from php array in javascript forEach loop to url of ajax call

I'm trying to loop through the results of a mysql query in php, the output of the query is an array similar to [10201,10202]. I want to take the results and loop it to the variable named id in my javascript function and loop it through the url of my ajax call. The goal is to take the id and use it in a sql query on another page to change the date of the id in our database.
mysql query:
<?php
// sql query for # print all open orders function
$sql = "SELECT Order_PID
FROM `Order`
WHERE SHIPDATE IS NULL
AND Address1 IS NOT NULL;";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)) {
$order[] = $row['Order_PID'];
}
?>
javascript function:
I'm trying to use a forEach function to iterate through the results of the array.
$('button#printOpenOrders').on('click', function(e) {
if(confirm("Are you sure you want to print all open orders and mark them as pending?")) {
e.preventDefault();
// prints all open orders
window.open("/resources/scripts/allOpenPDF.php");
var arr = $order;
arr.forEach(function(id) { // <====this function
$.ajax({
url: "/resources/scripts/pending-order.php?id=" + id, // <===this variable
datatype : "string",
success : function(data) {
location.reload(true);
}
})
})
}
});
and if it helps here is my callback script
<?php
// login validation
session_start();
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
$url = $_SERVER['DOCUMENT_ROOT'].'/index.php';
header("Location: ../../index.php");
}
// establish connection to database
include $_SERVER['DOCUMENT_ROOT'].'/resources/scripts/dbconnect.php';
$conn = openConnection();
// capture id
$id = $_GET['id'];
$pendingDate = date_create_from_format("m/d/Y", "07/26/1996");
$pendingDate = date_format($pendingDate, "Y-m-d H:i:s");
$sql = $conn->prepare("UPDATE `Order`
SET SHIPDATE = ?
WHERE Order_PID = ?");
$sql->bind_param("si", $pendingDate, $id);
$sql->execute();
echo "success";
closeConnection($conn);
?>
If parts of my code don't make sense, I'm new to this and I am using my currently limited knowledge to frankenstein all of this together. Any nudges in the right direction would be super helpful.
You can output $order variable contents, but you need to use PHP and also you must encode it using json format, so this could actually work:
var arr = <?PHP echo json_encode($order); ?>;
But it is error-prone, the syntax is not really nice to read, and if that variable somehow becomes in the format you are not expecting it could lead to another JavaScript syntax error.
But the best way in my opinion would be to make an AJAX request and get those order IDS, and after that you could create another AJAX request that would send all those Order IDS,
so you wouldn't need .forEach stuff and your logic of handling multiple orders need to be modified in order to accommodate for these changes.
But since you already have those IDS in PHP I mean stored in $order variable, you could just encode it and send it all the ids at once in a single request.

Regarding Data table source data access

I have used the datatable ajax call for listing I received the below json data in ajax call:
{
"sEcho":1,
"iTotalRecords":"1",
"iTotalDisplayRecords":"1",
"aaData":[
["Demo to Mam","2"]
],
"countOfTotalRecords":2
}
How I can use the countOfTotalRecords var value on view page?
You've to decode your JSON data using json_decode, then you have an object. Looks something like this:
$json = '{"sEcho":1,"iTotalRecords":"1","iTotalDisplayRecords":"1","aaData":[["Demo to Mam","2"]],"countOfTotalRecords"
:2}';
$decode = json_decode($json);
echo $decode->countOfTotalRecords; // this will display 2, regarding your data
use the below code
$str = '{"sEcho":1,"iTotalRecords":"1","iTotalDisplayRecords":"1","aaData":[["Demo to Mam","2"]],"countOfTotalRecords":2}';
$arr = json_decode($str);
$tcount = $arr->countOfTotalRecords;
echo $tcount;

unable to get json data from server

My server side code is:
$bus = array(
'meaning' => $name
);
$jsonstring = json_encode($bus);
echo $_GET['callback'].'(' . $jsonstring. ')';
the value displayed on the screen is correct - ?word=heart({"meaning":"heart"})
but when I am reading it with following code its printing the value of meaning as 11200665987893779229_1460521505942
$(document).ready(function(){
$.getJSON('http://mydomain?callback=?','word=heart',function(res){
document.getElementById('print').innerText=''+res.meaning;
});
});
but when I do this:
$bus = array(
'meaning' => 'heart'
);
it's printing the correct value i.e heart
I am not getting why this is happening and how to get the correct value (I am accessing data from my different domain).
JSON.parse() converts any JSON String passed into the function, to a JSON Object.
$(document).ready(function(){
$.getJSON('http://mydomain?callback=?','word=heart',function(res){
obj = JSON.parse(res);
document.getElementById('print').innerText=''+obj.meaning;
});
});
a similar post is here

JSON array values not being read by JQuery

I’m reading X,Y Coordinates from MySQL Database.
2 files(I can post the connection file if needed): coordinate_array, and map.php
coordinate_array: I am making a multidimensional arrays so I can then use json_encode($desk). I only need x,y values for the JS/Jqueryt part.
updated PHP code and JQuery CODE.. still does not work!?
<?php
include 'db_conn.php';
header('Content-Type: application/json');
$coordinate_sql = "SELECT x_coord, y_coord FROM coordinates";
$result = mysqli_query($conn,$coordinate_sql);
//see if query is good
if($result === false) {
die(mysqli_error());
}
//array that will have number of desks in map area
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk[] = array('x' => $row['x_coord'],
'y' => $row['y_coord']);
} //end while loop
echo json_encode($desk); //encode array
?>
The code above gives me this as the result for the array:
[{"x":"20","y":"20"},{"x":"30","y":"30"},{"x":"40","y":"40"},{"x":"50","y":"50"}]
map.php : This is the part where is not entirely working. I'm trying to get the values from json_encode with JQuery but I get no output on screen.
Don't know which of these two I should use
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
Need help here please
<canvas id="imageView" width="600" height="500"></canvas>
<script type="text/javascript">
//I have no idea how to get the encoded values
$.post('coordinate_array.php', {}, function(data) {
results = JSON.parse(data);
for(i = 0;i < results.length;i++) {
Paint(results[i].x, results[i].y);
}
});
I want to execute this function
//function to paint rectangles
function Paint(x,y)
{
var ctx, cv;
cv = document.getElementById('imageView');
ctx = cv.getContext('2d');
ctx.lineWidth = 5;
ctx.strokeStyle = '#000000';
//x-axis,y-axis,x-width,y-width
ctx.strokeRect(x, y, x+100 , y+100);
}
</script>
The JSON formal definition tends to have an object (or, key-associative-array: {}) as the root of any JSON object, as opposed to an array ([]).
To wrap it inside one associative object:
$deskOutput = array("coords" => $desk);
echo json_encode($deskOutput); //encode array
Then, on the JavaScript side, you will just need to get "each(data.coords," and you'll have your array.
For that matter, it seems like you're putting unnecessary complexity in your array structure at the PHP level. How about this?
$desk[] = array("x" => $row['x_coord'], "y" => $row['y_coord']));
That will create just one object for each x/y set. I'll leave it to you to figure out how you could simplify your JavaScript accordingly.
First just make $desk like this:
while($row = mysqli_fetch_assoc($result)){
//get desk array count
$desk[] = array('x' => $row['x_coord'], 'y' => $row['y_coord']);
}
echo json_encode($desk);
And call the php script like so:
$.post('coordinate_array.php', {}, function(data) {
results = JSON.parse(data);
for(i = 0;i < results.length;i++) {
Paint(results[i].x, results[i].y);
}
});
I'm going to test this really quick to make sure I got everything right.
Edit: Okay, I tested this, it works.

HighCharts, Json Format

So i'm attempting to use highcharts with the pie chart drilldown option.
Working with static data this is working perfectly. However, as I would like to use the Pie chart as a form of reporting, Ideally It needs to run with dynamic data.
The top level data is made up of requests. Each request is made up of subsequent tasks.
This is the php I have which retrieves the tasks and requests.
foreach($getRequests as $key=> $val){
$timeArr = explode(':', $val['duration']);
$decTime = ($timeArr[0]) + ($timeArr[1]/60); // this is purely to convert hh:mm to decimal time
$pieData['name'] = $val['name'];
$pieData['y'] = $decTime;
$pieData['drilldown'] = $key;
$pie[]=$pieData;
// This creates the first level of data which the $pie[] array gives the correct format, so when json_encode is applied, the data is usable
$getTasks = $task->getReportTasks($user, $status, $key, $dateRange, $date);
foreach($getTasks as $taskKey => $taskVal){
$pieTasks['id']=$key;
$pieTasks['name'] = "Tasks";
$timeArrTask = explode(':', $taskVal['duration']);
$decTimeTask = ($timeArrTask[0]) + ($timeArrTask[1]/60);
$pieTasks['data'] = array($taskVal['name'], $decTimeTask);
$pie2[] = $pieTasks;
}
}
However by applying the same logic to tasks and using json_encode, I end up with the following.
[
{"id":25684
,"name":"Tasks"
,"data":["test task1",3]
}
,{"id":25684
,"name":"Tasks"
,"data":["testtask2",14.383333333333]
}
,{"id":25689
,"name":"Tasks"
,"data":["testtask3",1]}
]
But the format I need is for tasks with the same request ID, the "id" field to be contained within the same data field.
Like so
[
{"id":25684
,"name":"Tasks"
,"data":[
["test task1",3]
,["testtask2",14.383333333333]
]
}
,{"id":25689
,"name":"Tasks"
,"data":[
["testtask3",1]
]
}
]
where because testtask2 has the same id, it is contained within the same data field.
I hope this makes sense and any help anyone can provide so I can structure this correctly would be greatly appreciated.
Not tested, but try to replace the last foreach with this code:
$pieTasks['id'] = $key;
$pieTasks['name'] = "Tasks";
$pieTasks['data'] = array();
foreach($getTasks as $taskKey => $taskVal){
$timeArrTask = explode(':', $taskVal['duration']);
$decTimeTask = ($timeArrTask[0]) + ($timeArrTask[1]/60);
$pieTasks['data'][] = array($taskVal['name'], $decTimeTask);
}
$pie2[] = $pieTasks;
Standart JSON parser can't parse double (14.383333333333) .
Try write in double quotes ( "14.383333333333" )

Categories

Resources