I am getting list of images from a folder for particular ID. Right now I am getting file names but I also want to get upload path.
How to get both data in one function.
Jquery Code:
listFilesOnServer(project_id);
function listFilesOnServer (project_id) {
var items = [];
uploadURI = uploadURI+'/'+project_id;
console.log(project_id+'--KAL--'+uploadURI);
$.getJSON(uploadURI ,function(data,path) {
console.log(data);
$('div #list-group').html("").html(items.join(""));
});
}
Controller Code:
function listFiles() {
$this->load->helper('file');
$project_id = $this->uri->segment(3);
$builders_id = $this->admin_model->getBuilderID($project_id);
$UPLD_PATH = $this->admin_model->builder_UPLD_PATH($builders_id);
$upload_path = "./application/assets/images/" . $UPLD_PATH;
$files = get_filenames($upload_path);
echo json_encode($files);
}
You should modify your controller action so that it returns an json_encode(array('files'=>$yourFiles, 'filePath'=>$yourFilePath) ); like below :
function listFiles() {
$this->load->helper('file');
$project_id = $this->uri->segment(3);
$builders_id = $this->admin_model->getBuilderID($project_id);
$UPLD_PATH = $this->admin_model->builder_UPLD_PATH($builders_id);
$upload_path = "./application/assets/images/" . $UPLD_PATH;
$files = get_filenames($upload_path);
echo json_encode(array('files'=>$files, 'uploadPath'=>$upload_path) );
exit();
}
Then modify your jquery code to handle the json response and extract the response like below :
listFilesOnServer(project_id);
function listFilesOnServer (project_id) {
var items = [];
uploadURI = uploadURI+'/'+project_id;
console.log(project_id+'--KAL--'+uploadURI);
$.getJSON(uploadURI ,function(data,path) {
//Your upload path
console.info("UPLOAD PATH: "+data.uploadPath);
//Your files
console.log(data.files);
//Your processing logic goes here
$('div #list-group').html("").html(items.join(""));
});
}
Related
I am using laravel 5.0.
I have a controller named pesananController like this:
public function ambilnamakomp(Request $request)
{
$data = DB::table('komputer')->where('id', $idkomp);
$hasil = json_encode($data);
return $hasil;
}
view bookhari.blade.php:
<script type="text/javascript">
var namakomp = "";
var urltemp = "/ambilnamakomp/" + idkomp;
$(document).ready(function () {
$.get(urltemp, function(){
namakomp = jQuery.parseJSON(hasil)
});
});
alert(namakomp);
</script>
routes I like this:
Route::get('/ambilnamakomp/{id}', 'pesananController#ambilnamakomp');
I wanted to take the form of data records in the database using ajax.
I do not understand how to send a variable from php ajax and then process it in JavaScript.
In your laravel code, you can use response helper with json method:
public function ambilnamakomp(Request $request)
{
$data = DB::table('komputer')->where('id', $idkomp);
return (new Illuminate\Http\Response())->json($data);
}
You can get data in your JQuery $.get function like this:
<script type="text/javascript">
var namakomp = "";
var urltemp = "/ambilnamakomp/" + idkomp;
$(document).ready(function () {
$.get(urltemp, function(data){
//data is object from php script
namakomp = data;
});
});
alert(namakomp);
</script>
After
$this->view->headScript()->appendFile($this->_request->getBaseUrl() . '/public/scripts/czassesji.js', 'text/javascript');
is called script
jQuery(document).ready(function() {
var licznik = 0;
var aktywny = true;
window.onblur = function(){aktywny = false;};
window.onfocus = function(){aktywny = true; licznik = 0;};
var id = setInterval(function(){wyslijImpuls()},60000);
function wyslijImpuls() {
if(aktywny == false) {
licznik++; //żeby nie tracić czasu spędzonego na stronie (np: 30 sekund), gdy uzytkownik przelączy okno/zakładkę przeglądarki
}
if(licznik < 2) {
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
}
}
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
console.log(baseUrl);
});
and I revieved error
ReferenceError: baseUrl is not defined $.post(baseUrl+'Zapiszczas/',
{'ile': 1});
My question is how to pass baseUrl value to js? I'd like to mentioned that baseUrl is defined in config.ini and accessible in php Zend controller.
You have to save that baseURL in some input hidden or in a global var in javascript, when php send the rended page , javascript can't access to php variables, one is executed in server side and the other is exectued in the client side.
<script>
baseURL = this->view->headScript()->appendFile($this->_request->getBaseUrl() . '/public/scripts/czassesji.js', 'text/javascript');
</scrip>
And then call in your next javascript script.
At the very Top of your ViewScript where you added $this->view->headScript()
//VIEW FILE
<?php
$this->view->headScript()->appendFile($this->_request->getBaseUrl() . '/public/scripts/czassesji.js', 'text/javascript');
//TRY ADDING THIS:
$this->inlineScript()->captureStart();
echo "var baseURL = '" . $baseUrl . "';";
$this->inlineScript()->captureEnd();
//.... MORE CODES...
?>
<?php
// IN YOUR CONTROLLER: SINCE YOU HAVE ACCESS TO THE $baseUrl VARIABLE HERE
// TRY THIS IN THE APPROPRIATE ACTION:
public function showAction(){
//...HANDLE YOUR BUSINESS LOGIC
$arrViewModel = array();
$arrViewModel['baseUrl'] = $pointerToBaseURL;
$viewModel = new ViewModel($arrViewModel);
//IF $viewModel ALREADY EXIST BEFORE THIS POINT:
// YOU MAY JUST ADD THE baseUrl KEY LIKE SO
// $viewModel->setVariable('baseUrl', '$pointerToBaseURL');
return $viewModel;
}
?>
// IN YOUR JQUERY... $baseUrl SHOULD NOW BE AVAILABLE
// SINCE IT IS NOW GLOBALLY SCOPED FROM YOUR VIEW:
jQuery(document).ready(function() {
var licznik = 0;
var aktywny = true;
window.onblur = function(){aktywny = false;};
window.onfocus = function(){aktywny = true; licznik = 0;};
var id = setInterval(function(){wyslijImpuls()},60000);
function wyslijImpuls() {
if(aktywny == false) {
licznik++; //żeby nie tracić czasu spędzonego na stronie (np: 30 sekund), gdy uzytkownik przelączy okno/zakładkę przeglądarki
}
if(licznik < 2) {
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
}
}
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
console.log(baseUrl);
});
I hope this helps a bit...
I have a page which generates a chart. I have a button which generates a pdf report for it. I wanted to create an image of this chart and insert it into the pdf. To create the image, I use html2canvas and get the dataurl which I store in the localstorage.
chart.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#download').click(function() {
$.ajax({
type: "POST",
url: "pdfGen.php",
data: 'hello',
success: function(data) {
alert("hi");
}
});
});
}); //END $(document).ready()
</script>
<script>
//<![CDATA[
(function() {
window.onload = function(){
html2canvas(document.getElementById('chart'), {
"onrendered": function(canvas) {
var img = new Image();
img.onload = function() {
img.onload = null;
console.log(canvas.toDataURL("image/png"));
window.localStorage.setItem("imgURL", canvas.toDataURL("image/png"));
};
img.onerror = function() {
img.onerror = null;
if(window.console.log) {
window.console.log("Not loaded image from canvas.toDataURL");
} else {
//alert("Not loaded image from canvas.toDataURL");
}
};
img.src = canvas.toDataURL("image/png");
}
});
};
})();
//]]>
</script>
<body>
Report
..more code to generate the chart
</body>
The download button calls the pdfGen.php script which uses fpdf to generate a report.
pdfGen.php
<?php
echo $_POST['data']; //gives error
/*$pdf = new FPDF();
$pdf->AddPage();
//over here I want to add the image from the chart.php page whose data url is now in the localstorage.
..more code to generate report
$pdf->output();*/
?>
How do I get the image inside the php script? I try to make the ajax call but I get undefined index data in pdfGen.php script. I got the alert HI but could not get the data on the server.
It does not seem to work.
Your ajax call is wrong.
Your call should be like this to get value hello in data variable/key
$('#download').click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "pdfGen.php",
data: 'data=hello',
success: function(data) {
alert("hi");
}
});
});
To learn more about the jQuery Ajax refer this link.
Here is an example passing localstorage from js to php session, assume using jQuery as ajax requester.
Handle
In root, add file: retrieve.php (This will RETRIEVE AND SYNC localstorage from js with session from php)
<?php
session_start();
$key = 'my-car'; // Your localstorage key
$client = (isset($_GET[$key]) && $_GET[$key] !== 'null') ? $_GET[$key] : null;
$server = isset($_SESSION[$key]) ? $_SESSION[$key] : null;
$_SESSION[$key] = $client; // Now stored in php´s session variable $_SESSION['my-car']
echo $client === $server ? 'true' : 'false'; // Tells js to reload if data was not synced
Set
In your index.html / index.php add this script: (This will PASS localstorage to php and reload if not synced after php´s session data is set)
<?php
session_start(); // Dont forget this line
$key = 'my-car';
if (isset($_SESSION[$key]) && $_SESSION[$key] !== null) {
$car = json_decode($_SESSION[$key], true);
echo $car['name']; // Will print 'Tesla'
}
?>
<script>
// Set in JS
var key = '<?php echo $key; ?>';
window.localStorage.setItem(key, JSON.stringify({
name: 'Tesla'
})); // Set to whatever you want
var data = {};
data[key] = window.localStorage.getItem(key);
// Passes to PHP using GET
jQuery.get(
location.protocol + '//' + location.host + '/retrieve.php',
data
).done(function (synced) {
if (synced !== 'true') {
// If not synced, reload
location.reload();
// Caution! If it doesnt sync correctly, infinite loop may occure
}
});
</script>
Use
And last, passing session from PHP to localstorage in js ->
In ANY php file:
<?php
start_session();
$key = 'my-car';
if (isset($_SESSION[$key]) && $_SESSION[$key] !== null) {
// Print old value
$car = json_decode($_SESSION[$key], true);
echo $car['name']; // 'Tesla'
// Update object
$car['name'] = 'Honda';
$_SESSION[$key] = json_encode($car);
// Pass to js:
echo "<script>window.localStorage.setItem('" . $key . "', '" . $_SESSION[$key] . "');</script>";
// Prints the updated object with name 'Honda'
echo "<script>console.log(window.localStorage.getItem('" . $key . "'))";
}
Note: 'my-car' can be replaced with your own keys.
I am getting userid from the url.
This is what I have at the moment. I want to replace the one with $userid but I don't know how. It doesn't work and I can't seem to find the right syntax, please can someone help?
function returnimages($dirname = "Photos/1")
Basically I am trying to create a photo slideshow using html, php and javascript. I had something working before I started adding php into my code. I had html and an external javascript that changes the photos and they fade in and out in a loop. I have a photo array in javascript. Right now I am trying to add php to my html. I want to be able to get userid via url and then from that get the photos from a specific path to the userid in the directory. Then I am hoping to create an array of these photos and use them in my javascript. Here is my php code embedded in my html:
<?php
$user_id = $_GET['userid'];
print " Hi, $user_id ";
function returnimages($dirname = "Photos/1") { //will replace 1 with userid once something starts working
$pattern="(\.jpg$)|(\.png$)|(\.jpeg$)|(\.gif$)"; //valid image extensions
$files = array();
$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){ //if this file is a valid image
//Output it as a JavaScript array element
echo 'galleryarray['.$curimage.']="'.$file .'";';
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo 'var galleryarray=new Array();'; //Define array in JavaScript
returnimages() //Output the array elements containing the image file names
?>
And my javascript:
$ (document).ready(function(){
var photodisplay =
[
$("#photo1"),
$("#photo2"),
$("#photo3"),
$("#photo4"),
$("#photo5"),
];
//photodisplay[0].hide().fadeIn(3000);
var user = new Array();
[1, 2, 3, 4, 5];
// List of images for user one
/*var userphoto = new Array();
userphoto[0] = "Photos/1/1.jpg";
userphoto[1] = "Photos/1/2.jpg";
userphoto[2] = "Photos/1/1.jpg";
userphoto[3] = "Photos/1/1.jpg";
userphoto[4] = "Photos/1/1.jpg";*/
//preloading photos
var userphoto = <? echo json_encode($galleryarray); ?>;
function preloadingPhotos() {
for (var x=0; x<5; x++)
{
photodisplay[x].attr("src", "Photos/1" + userphoto[x]);
photodisplay[x].hide();
console.log("preloaded photos");
}
displayPhoto();
}
function displayPhoto(){
photodisplay[0].fadeIn(3000);
photodisplay[0].delay(3000).fadeOut(3000, function() { //first callback func
photodisplay[1].fadeIn(3000);
photodisplay[1].delay(3000).fadeOut(3000, function() { //second callback func
photodisplay[2].fadeIn(3000);
photodisplay[2].delay(3000).fadeOut(3000, function() { //third callback func
photodisplay[3].fadeIn(3000);
photodisplay[3].delay(3000).fadeOut(3000, function() { // fourth callback func
photodisplay[4].fadeIn(3000);
photodisplay[4].delay(3000).fadeOut(3000, function() {
setTimeout(displayPhoto(), 3000);
});
});
});
});
});
}// end of function displayPhoto
window.onload = preloadingPhotos;
}); //end ready
My url to get userid:
http://example.com/code.php?user_id=1
Thank you for your time!
The problem is that you are always setting the dirname instead of letting calling the function set it. You could change:
function returnimages($dirname = "Photos/1") {
to
function returnimages($dirname) {
because otherwise the $dirname is always Photo/1. Then, when you call the function, use:
returnimages('Photos/'.$user_id);
You can concatenate in PHP by using the dot '.'. This will concatenate two string and then assign them to the variable $dirname. For example:
$dirname = "Photos/" . $_GET['ID'];
The variable $dirname can then be placed in the function returnimages, like:
returnimages($dirname);
So basically I'm making cURL request and getting response that looks like this(var_dump):
string(595) "{"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa","mc"]},"3":{"amount":1000,"allowed_payment_methods":["mc","ideal","paypal","visa"]},"6":{"amount":2500,"allowed_payment_methods":["mc","ideal","paypal"]},"8":{"amount":5000,"allowed_payment_methods":["ideal"]},"9":{"amount":10000,"allowed_payment_methods":["ideal"]}},"payment_methods":{"ideal":{"name":"ideal","allow_recurring":false},"paypal":{"name":"paypal","allow_recurring":false},"visa":{"name":"visa","allow_recurring":false},"mc":{"name":"mc","allow_recurring":false}}}"
What I want is to access it in the JS file like this:
success: function (data) {
alert(data.user_id);
}
But I don't know how to convert(?) it properly.
And my next step(question) after that will be if I can do a for loop for every purchased pack, so I can create button for each one of them
Probably something like this:
var pack;
var packs = data.purchase_packs;
for (pack= 0; pack < packs.length; pack++) {
console.log(packs[pack]);
}
I'm tried to understand your "question"....
In js:
$.post('/some/url',{query: 'somequery'},
function (data) {
try {
data = JSON.parse(data);
} catch (e) {
return false;
}
console.log(data);
});
In PHP:
data = json_decode(rtrim($myJSONEncodedString, "\0"));
if (!empty($data->purchase_packs)
foreach ($data->purchase_packs as $key => $value)
var_dump($value);
After receiving response using cURL, just echo that json string between <script></script> tag.
Then json string will look like:
<script>
var jsondata = {"user_id":1,"currency":"eur","purchase_packs":{"1":{"amount":500,"allowed_payment_methods":["ideal","paypal","visa","mc"]},"3":{"amount":1000,"allowed_payment_methods":["mc","ideal","paypal","visa"]},"6":{"amount":2500,"allowed_payment_methods":["mc","ideal","paypal"]},"8":{"amount":5000,"allowed_payment_methods":["ideal"]},"9":{"amount":10000,"allowed_payment_methods":["ideal"]}},"payment_methods":{"ideal":{"name":"ideal","allow_recurring":false},"paypal":{"name":"paypal","allow_recurring":false},"visa":{"name":"visa","allow_recurring":false},"mc":{"name":"mc","allow_recurring":false}}};
</script>
Then, your javascript code between <script></script>. Like this:
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
alert(jsondata.user_id); // return user_id value
jQuery.each(jsondata.purchase_packs, function(i, val) {
alert(val.amount); // return amount
var paymentMethod = val.allowed_payment_methods;
jQuery.each(paymentMethod, function() {
alert(this); // will return all payment gateway method
});
});
</script>
Hope will help!