I have 1 javascript file which only contains Associative arrays.(This file will be generated by a testing tool, so no changes in this r allowed).
I need to use the values of that array in php file so that i can store these values in DB.
Please Specify how to do this?
PHP can run JavaScript via the V8 engine, although you will probably have to install it. You can use that to execute your JavaScript and (hopefully) extract the data.
Alternatively, write a web page that loads the JavaScript and then submits the data in it to a PHP script via Ajax.
Your best bet is to use JSON. PHP does not support Javascript by itself, but JSON is a common subset of Javascript that many platforms understand (which means it will be more widely supported if you need to reuse this data elsewhere).
In particular, you read the string from the file and then use json_decode:
$json_str = file_get_contents("json_file.js");
json_vals = json_decode($json_str);
Based on your comment:
<?php
$json_orig = <<<'json_oend'
var mime_samples =
[ {
'mime': 'application/xhtml+xml',
'samples': [{
'url': 'demo.testfire.net/',
'dir': '_m0/0', //it is for show trace
'linked': 2,
'len': 9645 }] },
{
'mime': 'text/html',
'samples': [{
'url': 'demo.testfire.net/.htaccess.aspx--\x3e\x22\x3e\x27\x3e\x27\x22\x3csfi000??001v275174\x3e',
'dir': '_m1/0', //it is for show trace
'linked': 2,
'len': 34 }] } ];
json_oend;
$json_str = preg_replace("/var[^=]*=/m", "", $json_orig);
$json_str = preg_replace("/;.*/m", "", $json_str);
$json_str = preg_replace("/'/m", "\"", $json_str);
$json_str = preg_replace("/\\/\\/.*/", "", $json_str);
$json_str = preg_replace("/\\\\x/", "\\u00", $json_str);
$json_val = json_decode($json_str, true);
for($i=0; $i<count($json_val); ++$i)
{
$samples = $json_val[$i]["samples"];
for($j=0; $j<count($samples); ++$j)
{
echo "$i.$j\n";
echo $samples[$j]['url'];
echo "\n";
}
}
?>
Related
I'm trying to export data from AJAX/JQUERY to Morris.JS.
Variable datachart return with data. but morris.js graph returns no Line/bar
$("#diseaseselection").change(function(){
$("#chart").empty();
var diseaseselection = $("#diseaseselection").val();
$.ajax({
url: "chart.php",
method: "POST",
data: {
diseaseselection: diseaseselection
},
success: function(data) {
Morris.Line({
element : 'chart',
data:[data],
xkey:'age',
ykeys:[ 'totalM', 'totalF'],
labels:['Total MALE', 'Total FEMALE'],
hideHover:'auto',
pointStrokeColors: ['white'],
lineWidth:'6px',
parseTime: false,
lineColors: ['Skyblue', 'Pink'],
});
}
});
});
Here is my sample PHP code
Please help me how to figure it out i badly need it thanks alot man. already trying my best
$diseaseselection = $_REQUEST['diseaseselection'];
if(isset($diseaseselection)){
$result = mysqli_query($con, "SELECT disease,age,SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) AS totalM, SUM(CASE WHEN gender = 'f' THEN 1 ELSE 0 END) AS totalF FROM mdr where disease = '$diseaseselection' GROUP BY disease , age");
$chart_data = '';
while($row = mysqli_fetch_array($result)) {
$chart_data .= "{ age:'".$row["age"]."', totalM:".$row["totalM"].", totalF:".$row["totalF"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
echo $chart_data; }
Here is my sample Output
This is based on my console log console.log(data);
Please help me how to figure it out i badly need it thanks alot man. already trying my best
{ age:'0-1', totalM:2, totalF:1},
{ age:'1-4', totalM:1, totalF:0},
{ age:'10-14', totalM:0, totalF:1},
{ age:'15-19', totalM:0, totalF:1},
{ age:'5-9', totalM:0, totalF:3},
{ age:'55-59', totalM:6, totalF:0}
There are a number of little issues here, which are kind of all tied up in the same key problem - what your PHP is producing is not valid JSON data.
If you copy and paste your sample data into a validator such as JSONLint you'll that it fails in a couple of ways:
1) You've got a list of objects, but in order to be a valid list (or array, as it's usually known) the items must be wrapped in square brackets ([ and ]) at the beginning and end.
2) The property names (e.g. age, totalM, and totalF) must have double quote marks (") around them.
3) The string values (e.g. 0-1, 1-4 etc) must have double quote marks around them, not single quote marks.
A valid version of your sample JSON would look like this:
[
{ "age": "0-1", "totalM": 2, "totalF": 1 },
{ "age": "1-4", "totalM": 1, "totalF": 0 },
{ "age": "10-14", "totalM": 0, "totalF": 1 },
{ "age": "15-19", "totalM": 0, "totalF": 1 },
{ "age": "5-9", "totalM": 0, "totalF": 3 },
{ "age": "55-59", "totalM": 6, "totalF": 0 }
]
You might find this tutorial useful as a quick way to learn the syntax.
However, useful as it is to know the syntax, you don't actually have to create it manually via your PHP, as you are doing now. In fact that's quite a bad idea to do that, because it leaves you vulnerable to silly mistakes (like not adding the square brackets), and at risk of accidental syntax errors in the JSON (e.g. imagine one of your string values itself contained a double-quote mark: if you didn't use a suitable escape character in front of it, then in the JSON it would look like the end of the property, and what followed would then be invalid).
The result of the problems above is that your PHP returns a string of invalid data back to the browser, and that cannot be used to populate the chart.
It's far better to simply construct a normal array in PHP, and then use the built-in json_encode() function to take care of turning that object into valid JSON. This is commonly accepted as best practice, and if you follow any introductory PHP/JSON tutorial it will show this function to you.
To add to the problems creating the JSON server-side, there's a client-side issue too: even if you did return valid JSON, at that point it's still a string - in order for it to be used in your chart you'd have to parse it into a JavaScript variable. If you specify dataType: "json" in your $.ajax options, jQuery will do the parsing for you automatically. Otherwise, you would make a call to JSON.parse() to do it.
Hopefully you see the overall pattern now - you take a PHP variable and turn it into JSON, which is a text representation of the data. This allows you to send it across the internet. Then when it arrives at the destination, you turn it back into a (JavaScript) variable again to be used in the code.
Here's some example PHP which will generate valid JSON in the recommended way. I've added comments at important lines:
$diseaseselection = $_REQUEST['diseaseselection'];
if(isset($diseaseselection)){
$result = mysqli_query($con, "SELECT disease,age,SUM(CASE WHEN gender = 'm' THEN 1 ELSE 0 END) AS totalM, SUM(CASE WHEN gender = 'f' THEN 1 ELSE 0 END) AS totalF FROM mdr where disease = '$diseaseselection' GROUP BY disease , age");
$chart_data = array(); //declare an array, not a string. This will become the outer array of the JSON.
while($row = mysqli_fetch_array($result)) {
//add a new item to the array
//each new item is an associative array with key-value pairs - this will become an object in the JSON
$chart_data [] = array(
"age" => $row["age"],
"totalM" => $row["totalM"],
"totalF" => $row["totalF"]
);
}
$json = json_encode($chart_data); //encode the array into a valid JSON object
echo $json; //output the JSON
}
And here's the relevant part of the JavaScript code to receive it
$.ajax({
url: "chart.php",
method: "POST",
data: {
diseaseselection: diseaseselection
},
dataType: "json", //parse the response data as JSON automatically
success: function(data) {
Morris.Line({
element: 'chart',
data: data, //supply the response data (which is now a JS variable) directly, no extra brackets
xkey: 'age',
ykeys: ['totalM', 'totalF'],
labels: ['Total MALE', 'Total FEMALE'],
hideHover: 'auto',
pointStrokeColors: ['white'],
lineWidth: '6px',
parseTime: false,
lineColors: ['Skyblue', 'Pink'],
});
}
});
Here's a working demo of just the AJAX and chart part (using a dummy server to provide the JSON): https://jsfiddle.net/7o9ptajr/1/
I'm trying to move some processing from client to server side.
I am doing this via AJAX.
In this case t is a URL like this: https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2.
First problem, I need to send a bunch of these URLs through this little function, to just pull out "1081244497" using my example. The following accomplishes this in javascript, but not sure how to make it loop in PHP.
var e = t.match(/id(\d+)/);
if (e) {
podcastid= e[1];
} else {
podcastid = t.match(/\d+/);
}
The next part is trickier. I can pass one of these podcastid at a time into AJAX and get back what I need, like so:
$.ajax({
url: 'https://itunes.apple.com/lookup',
data: {
id: podcastid,
entity: 'podcast'
},
type: 'GET',
dataType: 'jsonp',
timeout: 5000,
success: function(data) {
console.log(data.results);
},
});
What I don't know how to do is accomplish this same thing in PHP, but also using the list of podcastids without passing one at a time (but that might be the only way).
Thoughts on how to get started here?
MAJOR EDIT
Okay...let me clarify what I need now given some of the comments.
I have this in PHP:
$sxml = simplexml_load_file($url);
$jObj = json_decode($json);
$new = new stdClass(); // create a new object
foreach( $sxml->entry as $entry ) {
$t = new stdClass();
$t->id = $entry->id;
$new->entries[] = $t; // create an array of objects
}
$newJsonString = json_encode($new);
var_dump($new);
This gives me:
object(stdClass)#27 (1) {
["entries"]=>
array(2) {
[0]=>
object(stdClass)#31 (1) {
["id"]=>
object(SimpleXMLElement)#32 (1) {
[0]=>
string(64) "https://itunes.apple.com/us/podcast/serial/id917918570?mt=2&uo=2"
}
}
[1]=>
object(stdClass)#30 (1) {
["id"]=>
object(SimpleXMLElement)#34 (1) {
[0]=>
string(77) "https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2"
}
}
}
}
What I need now is to pull out each of the strings (the URLs) and then run them through a function like the following to just end up with this: "917918570,1081244497", which is just a piece of the URL, joined by a commas.
I have this function to get the id number for one at a time, but struggling with how the foreach would work (plus I know there has to be a better way to do this function):
$t="https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2";
$some =(parse_url($t));
$newsome = ($some['path']);
$bomb = explode("/", $newsome);
$newb = ($bomb[4]);
$mrbill = (str_replace("id","",$newb,$i));
print_r($mrbill);
//outputs 1081244497
find match preg_match() and http_build_query() to turn array into query string. And file_get_contents() for the request of the data. and json_decode() to parse the json responce into php array.
in the end it should look like this.
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?'.http_build_query(['id'=>25,'entity'=>'podcast'])));
if(preg_match("/id(\d+)/", $string,$matches)){
$matches[0];
}
You may have to mess with this a little. This should get you on the right track though. If you have problems you can always use print_r() or var_dump() to debug.
As far as the Apple API use , to seperate ids
https://itunes.apple.com/lookup?id=909253,284910350
you will get multiple results that come back into an array and you can use a foreach() loop to parse them out.
EDIT
Here is a full example that gets the artist name from a list of urls
$urls = [
'https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2.',
'https://itunes.apple.com/us/podcast/dan-carlins-hardcore-history/id173001861?mt=2'
];
$podcast_ids = [];
$info = [];
foreach ($urls as $string) {
if (preg_match('/id(\d+)/', $string, $match)) {
$podcast_ids[] = $match[1];
}
}
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?' . http_build_query(['id' => implode(',', $podcast_ids)])));
foreach ($json_array->results as $item) {
$info[] = $item->artistName;
}
print '<pre>';
print_r($info);
print '</pre>';
EDIT 2
To put your object into an array just run it through this
foreach ($sxml->entries as $entry) {
$urls[] = $entry->id[0];
}
When you access and object you use -> when you access an array you use []. Json and xml will parse out in to a combination of both objects and arrays. So you just need to follow the object's path and put the right keys in the right places to unlock that gate.
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" )
I am currently making an auto-complete form. Right now, the values of suggestions are from inside a JavaScript list:
<script type="text/javascript">
$('#textarea').textext({
plugins : 'autocomplete suggestions tags filter',
suggestions: [
'Basic',
'Cobol',
'Go'
]
});
I am using a function to get my list of names from a database:
$users->selectFirstnameSurname();
$userQueryResult = $users->queryResult;
$listOfNames = $users->listOfNames;
I am taking the values by appending firstname and lastname from the database, like this:
public function selectFirstnameSurname() {
$query = $this->db->prepare("SELECT * FROM `users` ORDER BY `username`");
$listOfNames[] = '';
try{
$query->execute();
foreach ($query as $row) {
array_push ($listOfNames, $row['firstname'].' '.$row['lastname']);
}
$this->queryResult = $query->fetch();
$this->listOfNames = $listOfNames;
} catch(PDOException $e){
die($e->getMessage());
}
}
What I want to do is get the values of array $listOfNames and replace the suggestions from the script.
You need to have a way to deliver the dataset so that your javascript code can access it. If your dataset is static and JS does the filtering, you could just statically dump them as a JS Object (JSON) like
[
{
"id": 1,
"label": "user name"
},
{
"id": 2,
"label": "other user"
}
]
The exact format of the JSON of course depends on your autocomplete implementation.
Or to make it more dynamic (good idea if you have a big dataset) you could make a simple API called over AJAX to fetch the data. If you need more detail, you can refer a tutorial like http://www.pontikis.net/blog/jquery-ui-autocomplete-step-by-step
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'
});