I have following code to get directories of folder ,
<?php
$path = 'templates';
$files = scandir($path);
foreach($files as $result) {
if ($result != "." && $result != ".." && $result != "desktop.ini")
{
echo '<img src="img/folder.png" width="40px"><a name="'.$result.'" class = "folderLink" href="#">'.$result.'</a> <input type="hidden" name="'.$result.'" value="'.$result.'"></img><br><div class="fileListInner"></div>';
}
}
?>
Above code returns dynamic number of folder names. This code is working fine and displayed folder list on success. Here is my form,
<form id="t-files">
<a style="margin-left:160px;" class="list-directories" href="#">Select File Path</a><br><br>
<div id="fileList"></div>
</form>
Now I want to go inside each folder and list sub folders. To do it I get class name of each link and on click even call ajax function. here is the code,
// load directories - inner (settings)
$(document).on("click",".folderLink",function(e){
e.preventDefault();
$.ajax({
type: 'post',
url: 'list-directories-inner.php',
dataType: 'text',
data: $('#t-files').serialize(),
success: function (data) {
$('#fileList').html(data);
}
});
exit();
});
And list-directories-inner.php file,
<?php
foreach ($_POST as $key => $value){
echo "".$key."<br>";
}
$path = 'templates';
$files = scandir($path);
foreach($files as $result) {
if ($result != "." && $result != ".." && $result != "desktop.ini")
{
// echo '<img src="img/folder.png" width="40px">'.$result.'</img><br>';
}
}
?>
How can I pass clicked link( hidden input) name value instead of pass all hidden values? Because in the list-directories-inner.php file I want to get clicked link value to set path. Something like 'templates/post value'. I'm thinking for hours. Please help.
Not sure which link your talking about ect but I gather its the following:
<img src="img/folder.png" width="40px"><a name="'.$result.'" class = "folderLink" href="#">'.$result.'</a> <input type="hidden" name="'.$result.'" value="'.$result.'"></img><br><div class="fileListInner"></div>
If so you could add the $resultvalue to the link as a data attribute so:
<img src="img/folder.png" width="40px" /><a name="'.$result.'" class = "folderLink" href="#" data-path="'.$result.'">'.$result.'</a><br><div class="fileListInner"></div>
Notice the data-pathattribute. Then get the value on the click event.
$(document).on("click",".folderLink",function(e){
e.preventDefault();
var path = $(this).data('path');
getInnerDirectoryList(path);
});
function getInnerDirectoryList(path){
$.ajax({
type: 'post',
url: 'list-directories-inner.php',
dataType: 'text',
data: {path_url: path},
success: function (data) {...},
error: function(msg){....}
});
}
Might have something like the above?
here is a jsbin of a simple version:
https://jsbin.com/yajefi/edit?html,js,output
You should try declaring a function that takes the input id of the clicked folder which will contain the required field instead of the generic function which gets called on every click of a .folderLink class.
Simon's answer should work, but here is an alternative.
You can get the value of the hidden input (since it's the same value as the hidden input's name) like this.
$(document).on("click",".folderLink",function(e){
var folder = $(this).siblings('input:hidden').val();
e.preventDefault();
$.ajax({
type: 'post',
url: 'list-directories-inner.php',
dataType: 'text',
data: {folder: folder},
success: function (data) {
$('#fileList').html(data);
}
});
});
Related
I am trying to to an on the fly database update of a select field but there can be more than one instance on the page of this field. I had this working for a single on change select field change, but with more than one I am simply passing the values for the first one.
I have in the past dealt with creating unique DOM ids for these on the page, but in this instance with a select field and using the change function I am a bit befuddled. Also most of the situations I found in searching this were not for select fields or dealing with passing variables in this way. I am fully aware this is crude and probably there is a much better way to accomplish this task.
$('.preferenceData').change(function(){
$.ajax({
type: 'POST',
url: "save_preferences.php",
data: {data1: $('.preferenceData').val(), data2: $('#userID').val()}, // this second data element not really needed but is passing var
dataType: 'text',
success: function(html){
if(html) {
$("div#updateDisplay").replaceWith('<div id="updateDisplay">' + html + '</div>');
}
})
});
The form bit:
echo '<div id="userPref"><select class="preferenceData" name="preferenceData'.$row['uid'].'">';
$prefs = enum_select($db,'db_table_name','email_preferences');
foreach($prefs as $pref)
{
echo '<option value="'.$pref['value'].'-'.$data['topicid'].'-'.$row['uid'].'"'.($row['email_updates'] == $pref['value'] ? ' selected' : '').'>'.$pref['display'].'</option>';
}
echo '</select></div>';
The function it's passed to:
function save_preferences()
{
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
$db = new db(0);
$vars = $_POST['data1'];
$data = explode("-", $vars);
// Update Database
$data = $db->Exec('UPDATE km_vendors_users SET email_updates = "'.$data[0].'" WHERE vid = "'.$data[1].'" AND uid = "'.$data[2].'"');
if($data==false)
{
echo $db->log;
//return false;
}
else
echo '<img src="/images/icons/success_check_animated.gif">';
}
}
For your code, you are trying to pass $('.preferenceData').val() for data1, which will be fairly unexpected results (and usually not a value).
Instead you can use $(this).val() which refers the specific element that changed, and its value.
$('.preferenceData').change(function(){
$.ajax({
type: 'POST',
url: "save_preferences.php",
data: {data1: $(this).val()},
...etc...
});
});
I am trying to pass a javascript variable into a php code in the view file of the cakephp 2.
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x= book.thumbnail_url;
<?php
$file11 = WWW_ROOT . 'img' . DS . 'book_images';
define('DIRECTORY', $file11);
$content = file_get_contents($abc);
file_put_contents(DIRECTORY . '/'.$isbn.'.jpg', $content);
?>
}
}
i am trying to pass the value of x in the file_get_contents function in place of $abc so that it could save the image coming from the javascript's URL accordingly.
EDIT::
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x= book.thumbnail_url;
$.ajax({
type: "POST",
url: '/BookSearchs/test',
data: {'yourX':x}
}).done(function(result) {
alert("yes");
}).fail(function() {
alert("no");
});
}
}
This is what i wrote after implementing the answers i got . But Everytime it pops up "no". Here BookSearchs is my controller and test is my function inside it.
EDIT 2:
function handleResponse(response) {
var target = '';
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x = book.thumbnail_url;
$.ajax({
type: 'POST',
url: "BookSearchs/test",
data: {
myVal: x
},
success: function() {
alert('AjaX Success')
},
error: function() {
alert('AjaX Failed')
}
})
.done(function() {
alert('AjaX Done!');
});
}
}
return true;
}
Currently this is what i've have done so far , the form method did not work out . It was redirecting me to another page . Anyways this is my current code . And 'test' is the my function inside the controller where i want to access the myVal value using POST . Also i have this question do i need to create a physical file for test in order to make the ajax function work, because if i delete the test.ctp file then the ajax starts giving the fail message . So for now i have created a physical test.file in the BookSearchs folder in the view , although it's empty in order to make the ajax function work . I am having a doubt whether my Url in Ajax is wrong or i am not accessing the values properly in the controller.
I don't think that this is a proper way to do that in theory. But, sometime we might need this.
Before we proceed to this way, you might need to think other technologies such as NodeJs (e.g fs.readFileSync)
Basically, you can't directly do that. Because, JavaScript run on client side and PHP is run on sever side.
Anyway, there might be a few tweak to do that. But, this approach might be slow and it depends on how many loop you making.
for (id in response) {
var book = response[id];
if (typeof(book.thumbnail_url) != "undefined") {
var x= book.thumbnail_url;
$.ajax({
type: "POST",
url: '/yourcontroller/route',
data: {'yourX':x}
}).done(function(result) {
//if success, execute other code
}).fail(function() {
//DO other if fail
});
}
}
Then, read this value in your controller
$xValue = $_POST['yourX'];
$file11 = WWW_ROOT . 'img' . DS . 'book_images';
define('DIRECTORY', $file11);
$content = file_get_contents($xValue);
file_put_contents(DIRECTORY . '/'.$isbn.'.jpg', $content);
//do some checking success or fail
//I will assume success
$status = 'success';
echo json_encode(['status'=>$status]);
Usally I use a Trick to pass JS variable to a CakePhp Controller(php variable). Actionly I create a form that contain a hidden input, I'll also put the link of the page that will receive the php variable.
.ctp
<?=
$this->Html->link('<i class="fa fa-file-pdf-o"></i>' .__('Export'),
'javascript:myFunction();',
array('escape' => false, 'class' => 'btn btn-app dispatch', 'id' => 'dispatch_packages',
'style'=>'margin-right:0px;background: #f39c12;color:white;',
'disabled' => 'false'));
?>
<form id="sampleForm" name="sampleForm" style="display: none" method="post" action="<?= $this->Url->build([
'controller' => 'YourController',
'action' => 'youraction']) ?>">
<input type="hidden" name="variable" id="variable" value="">
</form>
JS
var jsVar=0;
function myFunction()
{
document.sampleForm.variable.value = jsVar;
document.forms["sampleForm"].submit();
}
I used it with the CakePhp 3.x framework & it's working very fine. You have just to write the url with the CakePhp 2.x Syntax.
Don't hesitate to comment my answer if you'll have any difficulties to apply it.
Good Luck !
PHP function
function getSerialNumber(){
$upload_dir = wp_upload_dir();
$csvFile = $upload_dir['baseurl'].'/sample.csv';
$csv = $this->csv_to_array($csvFile); //read csv
foreach ($csv as $serialnum){
$serial_num_array[] = $serialnum['product_serial'];
}
$json_array = json_encode($serial_num_array);
return $json_array;
}
Return Value
["123456","789012"]
User input
<input name="product_serial" type="text" class="form-control login-field"
value="<?php echo(isset($_POST['reg_product_serial']) ? $_POST['reg_product_serial'] : null); ?>"
placeholder="Product serial number *" id="reg-product-serial" required/>
JS Code:
<script>
jQuery(document).ready(function($){
$.ajax({
url: "registration-form.php&f=getSerialNumber",
type: "GET"
success: function(data){
console.log('eureka');
}
});
$('input#reg-product-serial').on('blur', function() {
alert($(this).val()); //alerts user input
});
});
</script>
I am unable to call PHP function and pass json values in JS code to compare user input value for reg_product_serial.
How to fetch user input entered for product_serial and validate it
with php array returned ?
If that user input does not exists in array validate user by alert
message.
I didn't quite understand why do you have an ajax request to the form and why it's on the document ready event.
As far as I understood, the following is the code I came up with.
I haven't tested it but it should be enough for understanding the direction and main idea.
If you'd need further help add a comment.
validSerials.php
function compareSerialNumber($userSerial){
$validSerial = 0;
#Consider sanitizing the $userSerial variable (!!)
$upload_dir = wp_upload_dir();
$csvFile = $upload_dir['baseurl'].'/sample.csv';
$csv = $this->csv_to_array($csvFile); //read csv
foreach ($csv as $serialnum){
if($userSerial == $serialnum['product_serial'])
$validSerial = 1;
}
echo $validSerial;
}
echo compareSerialNumber($_GET['userSerial']);
die();
JS
<script>
jQuery(document).ready(function($){
$('input#reg-product-serial').on('blur', function() {
$.ajax({
url: "validSerials.php",
data: {userSerial: $(this).val() },
type: "GET"
success: function(res){
if(res == 1)
alert('Valid Serial');
else
alert('Invalid Serial');
}
});
});
});
</script>
I have a main page in my app called index.php where i want to show some photos. Code in that file is:
<div id="main" name="main">
<input type="button" value="Photos" onclick="showIm()">
</div>
File function.php contains a function to show photos on the screen:
function showPhotos()
{
global $link;
$result = pg_query_params($link, 'SELECT photo_name FROM photos');
while($photos_row = pg_fetch_row($result))
{
echo '<a href="photos/'.$photos_row[0].'">
<img src="photos/'.$photos_row[0].'"></a>';
}
}
My last file is function.js where i try to call showPhotos using ajax
function showIm()
{
$.ajax({
url: "functions.php"
})
}
So inside the last function I want to call showPhotos() to get the results. I think that my implementation is a little complicated but I would like to know if anyone could help.
Well, you have to do something with that result! Add a success method and declare a return dataType
function showIm()
{
$.ajax({
url: "functions.php",
dataType: "html",
success: function(html) {
//do something with the response here
//the "html" variable will contain your PHP response
}
})
}
I am a bit stuck with my website, currently on the new section of my site(among others) the user rolls over a thumbnail and gets the articles abstract displayed below it, and then when they click on said thumbnail the article appears on the left of the page,
The ajax works by pulling the href from the link that surronds the thumbnail image and using that as the url for the method call, the problem is that the click version will also be using the same function call, I cannot work out how to show the different content depening on what even happends, currently I have this as my code,
<?php
if(isset($content)) {
foreach($category_name as $k => $v) {
echo "<h2 class='$v[category_name]'><a href='#'>$v[category_name]</a></h2>";
echo "<div class='$v[category_name]'>";
}
$replace = array(".", "png", "gif", "jpg");
$count = 0;
foreach($content as $k=>$v) {
$count ++;
$image_name = str_replace($replace, "", $v['image_name']);
echo "<a class='contentlink' href='index.php/home/get_content_abstract/$v[content_id]'>";
echo "<img src='/media/uploads/".strtolower($v['category_name'])."/".$image_name."_thumb.png' alt='This is the picture' />";
echo "</a>";
}
echo "</div>";
//die(var_dump($content));
}
?>
<script>
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
});
</script>
The method that gets called is,
public function get_content_abstract() {
$this->load->model('content_model');
if($query = $this->content_model->get_content_by_id($this->uri->segment(3))) {
$data['abstract'] = $query;
}
$this->load->view('template/abstract', $data);
}
This is called by the ajax following the link /get_content_abstract/3, where 3 or any other number is the articles ID.
How can I sort so that I can use this function again, but only show that body content of the article instead of the abstract if the link is clicked and mouseovered?
You can pass a call type variable and check for it in your php code. Notice I added data to your ajax calls.
$("a.contentlink").mouseover(function(){
var url = $(this).attr("href");
$.ajax ({
url: url,
type: "POST",
data: "calltype=abstract",
success : function (html) {
$('#abstract').html(html);
}
});
});
$("a.contentlink").click(function(ev) {
ev.preventDefault();
$('#main_menu').hide();
var url = $(this).attr("href");
$.ajax({
url:url,
type: "POST",
data: "calltype=full",
success : function (html) {
// alert(html)
$('#left-content').html(html);
}
})
pass a GET variable in the url of the ajax call.
You just pass an variable to the handler via GET or POST that tells the handler which content to show. As your AJAX calls are simple, you can simplify the calls and use load(). If you can't use $_GET or $_POST, just append the data in the URL:
$("a.contentlink").mouseover(function() {
// URL becomes index.php/home/get_content_abstract/3/abstract
$('#abstract').load($(this).attr("href")+'/abstract');
});
$("a.contentlink").click(function(ev) {
$('#main_menu').hide();
// URL becomes index.php/home/get_content_abstract/3/full
$('#left-content').load($(this).attr("href")+'/full');
return false;
});
And in PHP, you can use something like this:
public function get_content_abstract() {
$this->load->model('content_model');
if($this->uri->segment(4) == 'full') {
// Load full content
} else {
// Load abstract
}
$this->load->view('template/abstract', $data);
}