Saving PHP array as javascript array variable - javascript

I am using the following pair of javascript and php files to get the names of all the image files in a directory.
Javascript
$(document).on("click", "ul#matchListUL li a", function(event){
event.preventDefault();
var matchLst = $(this).attr('href');
var filenames = new Array();
if (matchLst !== null && matchLst !=="") {
$.ajax({
url : "filenames.php",
dataType : "JSON",
type : "POST",
success:function(data) {
console.log(data);
}
});
}
return false;
})
filename.php
$tardir = "mysite.com/projects/" . $seldir . "/" . $match . "/*.jpg" ;
$files = glob($tardir);
$fileName = array();
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
$fileName = basename($num, ".jpg");
}
echo json_encode($fileName);
However, this just prints only one file name - essentially the last file in the folder.
How can i get all the filenames and can is save the filenames locally using local storage?

You are doing it wrong, you should do this:
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
// [] will add the value to the array
$fileName[] = basename($num, ".jpg");
}
And instead of using a for loop to go through your array, use a foreach loop instead, like this:
foreach($files as $file){
$fileName[] = basename($file, ".jpg");
}

Related

Get method in php then pass the value into json format

i'm trying to access the value that i've got from get method in my php file. My PHP file would looks like this
<?php
include 'Con.php';
header('content-Type: application/json');
$catid = $_GET["CatId"];
//array declaration
$array = array();
//declaration for the index name of the array
$text1 = "data1";
$text2 = "data2";
$text3 = "data3";
$text4 = "data4";
$text5 = "data5";
$sql = "select `Total Cliks`,`Categories_idCategories`,`Month` from Clicks where Categories_idCategories in ($catid)";
$_sql = mysqli_query($connection,$sql);
foreach ($_sql as $result) {
$Clicks = $result['Total Cliks'];
$Categories_idCategories = $result['Categories_idCategories'];
$Month = $result ['Month'];
if(array_key_exists($Month, $array[$text1]) == false){
$array[$text1][$Month] = $Clicks;
}
elseif(array_key_exists($Month, $array[$text2]) == false){
$array[$text2][$Month] = $Clicks;
}
elseif(array_key_exists($Month, $array[$text3]) == false){
$array[$text3][$Month] = $Clicks;
}
elseif(array_key_exists($Month, $array[$text4]) == false){
$array[$text4][$Month] = $Clicks;
}
elseif(array_key_exists($Month, $array[$text5]) == false){
$array[$text5][$Month] = $Clicks;
}
}
echo json_encode($array);
?>
and then in my Javascricpt file i wanted to make the reference url same as the url that i already get in "get method" in php
so the javascript code would look like this
$(document).ready(function(){
$.ajax({
url : "http://localhost:8888/ClicksChart/ckbox.php?CatId <?php $_GET["CatId"];?>",
type : "GET",
success : function(array){
console.log(array);
alert('Welcome');
In the URL, i wanted to have the url same as the value of my "Get method"
For example : in my get method i have got http://localhost:8888/ClicksChart/ckbox.php?CatId =1,2,3". so the url in the javascript file same as the value of the PHP file.
is there any way to solve this? thank you for the help
You are missing an '=' and an 'echo'
$.ajax({
url : "http://localhost:8888/ClicksChart/ckbox.php?CatId=<?php echo $_GET["CatId"];?>",
You forgot to write echo
url : "http://localhost:8888/ClicksChart/ckbox.php?CatId=<?php echo $_GET['CatId'];?>",
your parameter is missing in ajax
$.ajax({
url : "http://localhost:8888/ClicksChart/ckbox.php?CatId=<?php echo $_GET['CatId'];?>",
type : "GET",
dataType:'json',
success : function(array){
console.log(array);
alert('Welcome');

ajax when trying to access d[obj].src it return undefined

AJAX
function ajax_json_gallery(folder) {
alert(folder);
var thumbnailbox = $('#thumbnailbox');
$.ajax({
type: "POST",
url: "json_gallery_data.php",
contentType: "application/x-www-form-urlencoded",
dataType: "json",
data: "folder=" + folder,
success: function(d) {
for (var obj in d) {
if (d.hasOwnProperty(obj)) {
alert(d[obj]); //access data//
alert(d[obj].src); //undefined//
}
}
}
});
}
PHP
header('Content-Type: application/json');
$folder = "Img/Company1/Jersey1";
$dir = $folder."/";
$dirHandle = opendir($dir);
$i = 0;
$directoryfiles = array();
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$directoryfiles[] = '"img'.$i.'":{ "num":"'.$i.'","src":"'.$src.'", "name":"'.$file.'" },';
}
}
closedir($dirHandle);
echo json_encode($directoryfiles);
console.log(d)
[""img1":{ "num":"1","src":"Img/House1/Type1/Image1.png", "name":"Image1.png" },",
""img2":{ "num":"2","src":"Img/House1/Type1/Image2.png", "name":"Image2.png" },",
""img3":{ "num":"3","src":"Img/House1/Type1/Image3.png", "name":"Image3.png" },",
""img4":{ "num":"4","src":"Img/House1/Type1/Image4.png", "name":"Image4.png" },"]
x3
i am using ajax to get all image inside the folder directory , and return to ajax but when i tried to access the d[o].src it return undefined ,i had no idea what am i missing here.
Don't try to write JSON text yourself. Just create an associative array or stdClass object, add the appropriate key/values, then add that to $directoryfiles. json_encode will then do the proper encoding
$directoryfiles = array();
while ($file = readdir($dirHandle)) {
if(!is_dir($file) && preg_match("/.jpg|.gif|.png/i", $file)){
$i++;
$src = "$dir$file";
$temp = new stdClass;
$temp->num = $i;
$temp->src = $src;
$temp->name = $file;
$directoryfiles["img".$i] = $temp;
}
}
closedir($dirHandle);
echo json_encode($directoryfile);
change the format of json to,
{"img1":{ "num":"1","src":"Img/House1/Type1/Image1.png", "name":"Image1.png" },
"img2":{ "num":"2","src":"Img/House1/Type1/Image2.png", "name":"Image2.png" },
"img3":{ "num":"3","src":"Img/House1/Type1/Image3.png", "name":"Image3.png" },
"img4":{ "num":"4","src":"Img/House1/Type1/Image4.png", "name":"Image4.png" }};
then u use the code,
console.log(d.img1.src);

Why my php array return only recent/last post activities

I create a jquery which sent data to a php file and after query(If any data found at sql) php return data to jquery by json_encode for append it.
Jquery sent two type data to php file:
1st: page id
2nd: post ids (a jquery array sent them to php file)
If I used print_r($_REQUEST['CID']); exit; on php file for test what he get from jquery, Its return and display all post ids well.
But if I make any reply on particular post, Its only return recent post reply.
That means, if I have 3 post like: post-1st, post-2nd, post-3rd ; my php return only post-3rd activities.
I want my script update any post reply when it submitted at sql.
my wall.php
// id is dynamic
<div class="case" data-post-id="111"></div>
<div class="case" data-post-id="222"></div>
<div class="case" data-post-id="333"></div>
//Check for any update after 15 second interval by post id.
<script type="text/javascript" charset="utf-8">
var CID = [];
$('div[data-post-id]').each(function(i){
CID[i] = $(this).data('post-id');
});
function addrep(type, msg){
CID.forEach(function(id){
$("#newreply"+id).append("<div class='"+ type +""+ msg.id +"'><ul>"+ msg.detail +"</ul></div>");
});
}
var tutid = '<?php echo $tutid; ?>';
function waitForRep(){
$.ajax({
type: "GET",
url: "/server.php",
cache: false,
data: {
tutid : tutid,
CID : CID
},
timeout:15000,
success: function(data){
addrep("postreply", data);
setTimeout(
waitForRep,
15000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(
waitForRep,
15000);
}
});
}
$(document).ready(function(){
waitForRep();
});
</script>
server.php (may be problem in my array or something else)
while (true) {
if($_REQUEST['tutid'] && $_REQUEST['CID']){
foreach($_REQUEST['CID'] as $key => $value){
date_default_timezone_set('Asia/Dhaka');
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"SELECT * FROM comments_reply WHERE post_id =".$value." AND qazi_id=".$_REQUEST['tutid']." AND date >= '$datetime' ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));
} // array close
$rows = mysqli_fetch_assoc($res);
$row[] = array_map('utf8_encode', $rows);
$data = array();
$data['id'] = $rows['id'];
$data['qazi_id'] = $rows['qazi_id'];
//ect all
// do something and echo $data['detail'] = $detail;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} // request close
sleep(5);
} // while close
Try to declare CID array like this:
var CID = new Array();
It looks like you're looping through the CIDs and running an SQL query for each one, but you're only retrieving the results once, outside of the loop. You'll only get the last query's results if you run
$rows = mysqli_fetch_assoc($res);
outside of the CIDs foreach loop.
#koc:
Unfortunately, it won't be as simple as moving the closing loop bracket. If you're trying to retrieve multiple datasets in one AJAX call, then you'll need to handle multiple datasets in your AJAX's success callback, or in your addrep() function. Here's one way to do it, but you can do it many different ways depending on what you're ultimately trying to do:
while (true) {
if($_REQUEST['tutid'] && $_REQUEST['CID']){
$data = array();
foreach($_REQUEST['CID'] as $key => $value){
date_default_timezone_set('Asia/Dhaka');
$datetime = date('Y-m-d H:i:s', strtotime('-15 second'));
$res = mysqli_query($dbh,"
SELECT *
FROM comments_reply
WHERE post_id =".$value."
AND qazi_id=".$_REQUEST['tutid']."
AND date >= '$datetime'
ORDER BY id DESC LIMIT 1
") or die(mysqli_error($dbh));
$row = mysqli_fetch_assoc($res)
$data[] = array_map('utf8_encode', $row);
} // array close
//$rows = mysqli_fetch_assoc($res);
//$row[] = array_map('utf8_encode', $rows);
//$data = array();
//$data['id'] = $rows['id'];
//$data['qazi_id'] = $rows['qazi_id'];
//ect all
// do something and echo $data['detail'] = $detail;
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
} // request close
sleep(5);
} // while close
then in your Javascript:
...
success: function(data){
for (var i=0, len=data.length; i<len; i++) {
addrep("postreply", data[i]);
}
setTimeout(waitForRep, 15000);
},
...
But again, that's just an example. I don't really know what your datasets look like or how you want the data to be passed around and used. This is just an idea that hopefully gets you going in the right direction.

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)); ?>;

Return the uploaded file contents as JSON

I'm using angularjs to upload files. Im using this model that I've found at github:
https://github.com/danialfarid/angular-file-upload
The upload works perfect. However, after I've uploaded the file, I want to return the file contents as JSON, and then iterate of the JSON-object with Angular. But I don't know how to do this.
Here is my code:
$filename = $_FILES['file']['tmp_name'];
$csv = array_map('str_getcsv', file($filename));
foreach($csv as $c)
{
echo str_replace(array('"', ';'), ' ', $c[0]) . "\n";
}
//Return as JSON here? HOW?
Here is my controller:
as.controller('Marketing', function($scope, $http, $upload)
{
$scope.onFileSelect = function($files) {
var file = $files[0];
if (file.type.indexOf('image') == -1) {
$scope.error = 'image extension not allowed, please choose a JPEG or PNG file.'
}
if (file.size > 2097152){
$scope.error ='File size cannot exceed 2 MB';
}
$scope.upload = $upload.upload({
url: 'partials/result.php',
data: {},
file: file,
}).success(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
$scope.result = data;
});
}
});
I want the data to be and JSON-object. How can I accomplish this? When I try json_encode with PHP, it does not work.
Anyone who can help me with this?
I believe this is what you're looking for
if(isset($_FILES["file"])){
$fname = $_FILES['file']['tmp_name'];
// ...
if(move_uploaded_file($fname, "uploads/" . $fname)){
// this way
$csv = file_get_contents($fname);
$array = array_map("str_getcsv", explode("\n", $csv));
echo json_encode($array);
// or this way; have in mind delimiter
$row = str_getcsv($csv, "\n");
$length = count($row);
for($i = 0; $i < $length; $i++){
$data = str_getcsv($row[$i], ";");
$array[] = $data;
}
echo json_encode($array);
}
// ...
}

Categories