Trigger php - get path - add img - javascript

I'm new to PDO and HTML. How do I trigger the php file to get this random image path as the 'brand' image path in to my javascript?
php:
$query = $db->prepare('SELECT img, subject FROM img_db WHERE availability = ? ORDER BY RAND() LIMIT 1');
$array = array('Y');
$query->execute($array);
$result = $query->fetchAll(PDO::FETCH_COLUMN, 0);
var_dump($result);
js:
(function() {
var image = {
'brand': { 'url':'img/bimg.jpg', 'img':null },
'item': { 'url':'img/fimg.jpg', 'img':null }
};
var canvas = {'temp':null, 'draw':null};
var mouseDown = false;

There are many attempts, but here's simplest one:
Prepare your array:
$arr = array();
forach($results as $result){
$arr[$result['subject']] = array('url' => $result['img']);
}
Convert your results to JSON
$json = json_encode($arr);
if you are using MVC framework, pass your $json to view.
Next, in JavaScript part of your page:
(function() {
var image = <?php echo $json; ?>;
var canvas = {'temp':null, 'draw':null};
var mouseDown = false;
You can also load this data using ajax.

Related

Get json encode data from another ajax function

I'm using prestashop 1.6, I have an ajax function where I encode some data which I successfully retrieved on console withecho. Now I have to decode this json data in another ajax function to get a value for a specific variable. Sorry I'm a newbie with prestashop 1.6.
My first ajax function :
public function ajaxProcessAddQrVideo(){
$target_dir = _PS_IMG_DIR_.DS.'video_qr';
$id_product = Tools::getValue('id_product');
$stamp = strtotime('now');
$filename = 'video_qr_'.$id_product.'_'.$stamp.'.jpg';
$target_file = $target_dir.DS.$filename;
$upload = $_FILES['video_qr_attachment_file'];
$err = array();
$uploaded = false;
if($upload['type'] !='image/jpeg'){
array_push($err,"Veuillez entrer un fichier JPG");
}
if(empty($err)){
$uploaded = #move_uploaded_file($upload['tmp_name'], $target_file);
$this->context->smarty->assign('uploaded', $uploaded);
$this->context->smarty->assign('filename', $filename);
}
$this->json =array(
'uploaded'=>$uploaded,
'err'=>$err,
'id_product'=>$id_product,
'stamp'=>$stamp,
'file_name'=>$filename,
);
echo json_encode($this->json);
exit;
}
And I want to get the value of 'file_name' in my second ajax function:
public function ajaxProcessAddVideo(){
$img_path = json_decode($this->json,true);
$filename = $img_path['file_name'];
$id_lang = Context::getContext()->language->id;
$script = Tools::getValue('script');
$id_product = Tools::getValue('id_product');
$id_group_vid = Tools::getValue('cust_group');
//add qr_code video
$qr_code =$filename;
$err = true;
$insert = false;
$videos = array();
$vid = new MpsVideo();
$vid->id_product = $id_product;
$vid->url = $script;
$vid->cust_group = $id_group_vid;
$vid->date_add = date('Y-m-d H:i:s');
$vid->active = 1;
$vid->qrcode = $qr_code;
$is_existing = Db::getInstance()->getValue("SELECT COUNT(id_mps_video) FROM `ps_mps_video` WHERE id_product=$id_product AND url = '$script'");
if($is_existing==0){
$insert = $vid->save();
$id_group = explode(',',$id_group_vid);
$group_name = array();
foreach($id_group as $k){
$group = new Group($k);
$group_name[] = $group->name[$id_lang];
}
$vid->group_names = implode('<br/>',$group_name);
}
echo json_encode(array(
'err'=>$err,
'video_exists'=>$is_existing,
'insert'=>$insert,
'vid'=>$vid,
));
exit;
}
I don't know how to achieve this but I know its possible. If someone can help understand this, I would be very grateful.
the result of the first function is a json, that result must be read from another file and then passed to your second function. Or else the same function should read that json:
$data = file_get_contents("file/file_json_result.php");
$img_path = json_decode($data, true);

Highcharts update at specific time interval

I have HighCharts in a div tag that feeds from a MySQL table. I get this data by using PHP and converting JSON.
<?php
$query = "some query here ";
$result = $conn->query($query);
if (!$result) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
if (mysqli_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
//array
$table = array();
while($row= mysqli_fetch_assoc($result)) {
$table[] =$row;
};
$jsonTable= json_encode($table)
?>
And I can see the graph correctly by using this :
$(function () {
var chartData = <?php echo $jsonTable ?>;
var seriesA = [];
var seriesB = [];
for (i=0; i<chartData.length; i++){
tempDate = Date.parse(chartData[i].ctime);
seriesA.push([Date.parse(chartData[i].ctime), parseInt(chartData[i].totalKbpsin)]);
seriesB.push([Date.parse(chartData[i].ctime), parseInt(chartData[i].totalKbpsout)]);
};
But, I want to update my chart every 1 hour with new data.
How can I do that?
Solved!
To refresh data in dpecific time interval, I select to call another PHP page which output is only JSON data.
Then,usnig setInterval solves my problem.
Here is code:
function DrawContainerJson () {
var seriesA = [];
var seriesB = [];
var url = "https://domain.name/test/json.php";
$.getJSON(url, function(chartData) {
// loop through the JSON data and push to the temporary series
for (i=0; i<chartData.length; i++){
tempDate = Date.parse(chartData[i].ctime);
seriesA.push([Date.parse(chartData[i].ctime), parseInt(chartData[i].totalKbpsin)]);
seriesB.push([Date.parse(chartData[i].ctime), parseInt(chartData[i].totalKbpsout)]);
};
var opt = SetChartOption(seriesA, seriesB);
$('#container_json').highcharts(opt);
});
}
$(document).ready(function() {
DrawContainerJson();
//Refresh
setInterval(function(){
DrawContainerJson();
},60000); //1 min refresh
});
Regards,

PHP file ouputs the javascript code itself and not running

I'm trying to create an Edit Modal. Provided that I have the html code for this, I write this javascript/jquery code:
<script type='text/javascript'>
$(function() {
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo " <script type'text/javascript'> alert('1');</script>";
$unitID = $r['unitID'];
$unitStatus = $r['unitStatus'];
$unitNumber = $r['unitNumber'];
$floorNumber = $r['floorCode'];
$unitType = $r['unitType'];
$t = $db->query("select floorLevel, floor_buildingID from tblFloors where floorLevel = '$floorNumber'");
while( $u = $t->fetch(PDO::FETCH_ASSOC)){
$floorLevel = $u['floorLevel'];
$floor_buildingID = $u['floor_buildingID'];
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = $unitType");
while($x = $w->fetch(PDO::FETCH_ASSOC)){
$unitTypeName = $x['unitTypeName'];
?>
$("#editModal<?php echo $unitID; ?>").click(function(){
$("#editUnitNumber").val("<?php echo $unitNumber;?>");
$("#editUnitType").val("<?php echo $unitType; ?>").material_select('update');
$("#editFloorNumber").val("<?php echo $floorNumber; ?>");
});
<?php }}}?>
});
The code above is used to write the data from the modal, but instead it output this:
$("#editModal5").click(function(){ $("#editUnitNumber").val("12002"); $("#editUnitType").val("4").material_select('update'); $("#editFloorNumber").val("12"); }); });
How do I solve that? What causes this?
Use json to pass data from php to javascript, instead of echoing everything out in one place. It may seem an overkill but it's readable, and is more beneficial on the long run.
The code below is not tested, but it should give you a general idea on how to approach these things. I did not include the second and third queries within the first while loop. You can nest the results from those queries in the $unit array and access the relevant data via additional loops in javascript.
Also, ideally you wouldn't just echo out the decoded array right after the php, a better solution would be to call a function in the footer, that would generate a script tag with all data that is used by javascript. Another approach is to use AJAX and get a json response only when you need it, then you would feed that same json to the loop.
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
$units = [];
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$unit = [
'unitID' => $r['unitID'],
'unitStatus' => $r['unitStatus'],
'unitNumber' => $r['unitNumber'],
'floorNumber' => $r['floorCode'],
'unitType' => $r['unitType']
];
$units[] = $unit;
}
$units_json = json_encode($units);
?>
<script type='text/javascript'>
$(function() {
var units = '<?php echo $units_json ?>';
var units_array = JSON.parse(units);
// do some validation here
for (var i = 0; i < units_array.length; i++) {
// do some validation here
$("#editModal" + units_array[i].unitID).click(function(){
$("#editUnitNumber").val(units_array[i].unitNumber);
$("#editUnitType").val(units_array[i].unitType).material_select('update');
$("#editFloorNumber").val(units_array[i].floorNumber);
});
};
});
</script>

fullcalendar.js is not reading the php json feed

i want to pre-poulate my fullcalendar instance via a php json feed.
The page is loading fine (no 404 or sth like that) but the calendar is not showing any of the events.
generating the json:
<?php
require("../config/config.php");
$uid = $_SESSION['uid'];
$res = $db->query("SELECT * FROM slots WHERE tid = '$uid'");
$data = array();
while($row = $res->fetch_assoc())
{
$event = array();
$event['editable'] = false;
$event['id'] = "fixE_".$row['id'];
$event['title'] = getSlotStatus($row['status']);
$event['sid'] = $row['sid'];
$event['status'] = $row['status'];
$event['start'] = $row['start'];
$event['end'] = $row['end'];
$event['standby'] = $row['standby'];
if(strpos($data['status'],"_old"))
{
$event['textColor'] = '#000000';
$event['color'] = '#cccccc';
$event['className'] = 'lessonSlotOld';
}
else
{
$event['color'] = getColorCode($row['status']);
if($row['standby'])
{
$event['borderColor'] = '#0000FF';
}
}
$data[] = $event;
}
echo json_encode(array("events"=>$data));?>
and here's the part of the fullcalendar code where i am inserting the feed:
events:
{
url: 'include/fetchSlots.php',
type: 'POST',
error: function(){alert("There was an error fetching events")}
},
the json output of the php looks like the following (this is just a part because the whole response would be too much ;) )
{"events":[{"editable":false,"id":"fixE_164","title":"Slot is closed","sid":"0","status":"closed","start":"2015-06-06T04:00:00+08:00","end":"2015-06-06T04:30:00+08:00","standby":"0","color":"#B20000"}]}
Ok so here's the solution/the mistake.
The only problem that fullcalendar has is the line where the actual json is posted:
echo json_encode(array("events"=>$data));
fullcalendar doesnt want the "events" and it doesnt want the twice wrapped array. so the solution to this is simply to output the data-array directly:
echo json_encode($data);
then, the events are all loaded correctly.
ah and for all watchmen out there, yes i found the mistake with the wrong named variable ;)
if(strpos($data['status'],"_old"))
to
if(strpos($row['status'],"_old"))

json_encode($myVar); is giving map, I want a string array

I have the following HTML fragment, using PHP and JavaScript:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script>
var imageIndex = 0; // index into imageNames array
var imageHeight = 400; // height of image; changed by user clicking size buttons
var imageNames; // names of images user can view in this album
function pageLoaded() // execute this when the page loads.
{
// PHP -- generate the array of image file names
<?php
function getImageNames($directory)
{
$handle = opendir($directory); // looking in the given directory
$file = readdir($handle); // get a handle on dir,
while ($file !== false) // then get names of files in dir
{
$files[] = $file;
$file = readdir($handle);
}
if ($files[0] === ".") { unset($files[0]); } // Unix specific?
if ($files[1] === "..") { unset($files[1]); }
foreach($files as $index => $file) // only keep files with image extensions
{ $pieces = explode(".", $file);
$extension = strtolower(end($pieces));
if ($extension !== "jpg") { unset($files[$index]); }
}
$files = array_values($files); // reset array
natcasesort($files); // and sort it.
return $files;
}
?>
<?php $imageDirectory = $_GET['directory'] . '/';
$imageNames = getImageNames($imageDirectory);
?>
imageNames = <?php echo json_encode($imageNames); ?>;
imageHeight = 400;
imageIndex = 0;
reloadImage(); // loads the first image based on height and index
}
There is more after this, but this part doesn't refer to anything there, and my problem already exists by this point in the HTML output.
The problem is that, 5 lines from the end, I do a json_encode of an array of filenames. The output I get from this looks thusly:
imageNames = [{"59":"01-hornAndMusic.JPG","58":"02-DSC_0009.JPG","57":"03-DSC_0010.JPG","56":"04-Discussion.JPG","55":"05-DSC_0015.JPG","54":"06-DSC_0016.JPG","53":"07-DSC_0019.JPG","52":"08-strings.JPG","51":"09-strings2.JPG","50":"10-rehearsing.JPG","49":"11-StringsBigger2-001.JPG","48":"12-DSC_0041.JPG","47":"13-DSC_0046.JPG","46":"14-ensemble.JPG","45":"15-ensemble2.JPG","44":"16-DSC_0052.JPG","43":"17-rehearsing3.JPG","42":"18-rehearsing4.JPG","41":"19-rehearsing-001.JPG","40":"20-stringsBigger2.JPG","39":"21-rehearsing-002.JPG","38":"22-rehearsing-003.JPG","37":"23-ensemble3.JPG","36":"24-winds.JPG","35":"25-rehearsing-004.JPG","34":"26-stringsEvenBigger.JPG","33":"27-concentration.JPG","32":"28-concertMistress2.JPG","31":"29-stringsMore.JPG","30":"30-stringsMore-001.JPG","29":"31-stringsMore-002.JPG","28":"32-stringsMore-003.JPG","27":"33-stringsMore-004.JPG","26":"34-stringsMore-005.JPG","25":"35-DSC_0076.JPG","24":"36-stringsMore-007.JPG","23":"37-stringsMore-008.JPG","22":"38-stringsMore-009.JPG","21":"39-oboes.JPG","20":"40-winds-001.JPG","19":"41-DSC_0085.JPG","18":"42-DSC_0086.JPG","17":"43-percussion.JPG","16":"44-DSC_0088.JPG","15":"45-violinAtRest.JPG","14":"46-laughterInTheWoodwinds.JPG","13":"47-conducting-001.JPG","12":"48-DSC_0095.JPG","11":"49-DSC_0096.JPG","10":"50-AllTogetherNow.JPG","9":"51-DSC_0106.JPG","8":"52-horns.JPG","7":"53-DSC_0111.JPG","6":"54-conducting.JPG","5":"55-conducting-002.JPG","4":"56-conducting-003.JPG","3":"57-conducting-005.JPG","2":"58-DSC_0120.JPG","1":"59-DSC_0122.JPG","0":"60-everybody.JPG"}];
so I have the keys as well as the values of this hybrid PHP map/array thingie. What I want is just the values, put into a string array in the JavaScript.
I've gotten this to work sometimes, but not others, and I don't know the difference.
I think applying array_values function on $imageNames before encoding them should do the trick.
imageNames = <?php echo json_encode(array_values($imageNames)); ?>;
I'd do this:
imageNames = <?php echo json_encode(array_values($imageNames)); ?>;

Categories