How can I create a Dynamic DropDownBox in SapUi5? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I have one test folder in ProjectExplorer . In that folder i have multiple JSON files. I want to create a DropDownBox which will have all the files name containing in that folder. Also , when i click on any file I want to Display that file in a TextArea . I want to do this in SapUi5. Please Suggest
What I have tried so far
var oText = new sap.ui.commons.Label({
text : "Saved Files"
});
var SavedFiles = new sap.ui.commons.DropdownBox();
var oItem = new sap.ui.core.ListItem();
#!/usr/bin/perl
$basedir = "data"; //folder location
#files = ('*.json');
chdir($basedir);
foreach $file (#files)
{
$ls = `ls $file`;
#ls = split(/\s+/,$ls);
foreach $temp_file (#ls)
{
if (-d $file)
{
$filename = "$file$temp_file";
if (-T $filename)
{
push(#FILES,$filename);
}
}
elsif (-T $temp_file)
{
push(#FILES,$temp_file);
}
}
}
foreach $FILE (#FILES)
{
oItem.setText("filename");
SavedFiles.addItem(oItem);
}

It can be done, but you need to make the directory browsable.
Create a .htaccess file in the directory you need to read, and in that file add the following:
Options +Indexes
Implement the following:
var aFiles = [];
$.ajax({
url : "http://localhost:8010/", // or whatever URL you use
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(json)$/) ) {
aFiles.push(val);
}
});
console.log(aFiles); //aFiles holds an array with all the *.json files
}
});

Related

How can I enable user to select one image from the multiple images that he has just uploaded without refreshing the page?

I have a form where user can upload multiple images. I need a way to enable user to select one image from the images he just uploaded as his main picture before submitting the form.
I have loaded the previews using JavaScript file reader. I have tried to add a name via JavaScript to the image user has selected, so it can be accessed as a post element in the PHP script. But it is not working since it cannot be accessed as a file. I have spent 3 full days over this before posting this question. It'll be a huge help I anyone could tell me on how to approach this problem.
Following is the form :
<input type="file" name="files[]" multiple="true" id="file">
<div class="list"></div>
Javascript code for loading previews:
var imagesPreview = function(input, p) {
var id=1;
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img class="thumb" id="'+id+'">')).attr('src', event.target.result).appendTo(p);
id++;
}
reader.readAsDataURL(input.files[i]);
}
}
};
PHP code for uploading files:
$total = count($_FILES['files']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
//Setup our new file path
$newFilePath = "gig_pics/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
move_uploaded_file($tmpFilePath, $newFilePath);
$file_sql = "INSERT INTO `gig_pics`(id,gig_id,pic) VALUES ('','$gid','$newFilePath')";
$file_res = mysqli_query($conn,$file_sql);
}
}
And after adding the name with jquery, I tried accessing the image as post
$main_img_path = $_POST['selectImage'];
$main_img_path = $_FILES['selectImage'];
But I could do anything.
I think your problem lies in the way you are selecting the specific file from the list of files:
$main_img_path = $_FILES['selectImage'];
I've not used PHP in a while, but in my opinion if you are already looping through the files on the server, why not check for the main image while looping? Something like this (assuming $_POST['selectImage'] contains the temp file name of the selected image):
$total = count($_FILES['files']['name']);
// Loop through each file
for($i=0; $i<$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != ""){
if ($tmpFilePath === $_POST['selectImage']) {
// This is the selected image
}
//Setup our new file path
$newFilePath = "gig_pics/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
move_uploaded_file($tmpFilePath, $newFilePath);
$file_sql = "INSERT INTO `gig_pics`(id,gig_id,pic) VALUES ('','$gid','$newFilePath')";
$file_res = mysqli_query($conn,$file_sql);
}
}
Like I said, this depends on what $_POST['selectImage'] contains as I'm not sure what you are storing there.

How to reload number without refresh [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
My .php is reading some variables from pos.txt and I need to show them live, without refreshing the page. I've used <meta http-equiv="refresh" content="<?php echo $sec?>;URL='<?php echo $page?>'">, but it's annoying. I've read something about ajax, but I can't really understand how it works.
$line = file_get_contents('pos.txt');
list($date, $time, $x, $y, $z) = explode(' ', $line);
For this you have to use AJAX. You have to learn this http://www.w3schools.com/ajax/default.asp.
Once you learn it you will use it allways.
Just make a ajax call from your display page to your php file.
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && xmlhttp.status==200)
{
var response = ajax.responseText;
// Here is your response
}
}
ajax.open("POST", "request/path/response.php");
ajax.send(any_data);
Details
http://api.jquery.com/jquery.ajax/
$.ajax({
url: "[_YOUR_URL_]/post.txt",
}).done(function(data) {
$("#some_id").val(date.find("some data").text);
});
The code of above obvisouly won't work, but the code you will use can be that simple.
And as stated above once you go ajax you wont go back.
Using the jQuery wrapper makes the ajax bunches easier. You will want to spend an hour or two reading about it as well as looking at various samples
The easiest way is to use jquery ajax:
http://api.jquery.com/jquery.ajax/
You want to do something like this:
$.ajax({
url: "pos.txt",
}).done(function(data) {
var split = data.split(' ');
var date = split[0];
var time = split[1];
var x = split[2];
var y = split[3];
var z = split[4];
//then insert these variables into the elements you need
$('#date').val(date);
});
Try this it will work:
<html>
<head>
<script>
var ajax = new XMLHttpRequest();
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && xmlhttp.status==200)
{
var response = ajax.responseText;
document.getElementById('get-data').innerHtml = response;
}
}
ajax.open("GET", "pos.txt");
ajax.send(any_data);
</script>
</head>
<body>
<div id="get-data">
</div>
</body>
</html>

Ajax & PHP uploading files [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I'm starting with web programming with javascript and i have a little problem with uploading file.
I find this: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/
but I have no idea how to use upload.php file in mvc project. What to use as an action of form and where should be plasted this php code?
Can anyone give mi some hints?
you can upload you're file with ajax if you create a controller with php:
<?php
$valid_exts = array('jpeg', 'jpg', 'png', 'gif'); // Autorized extensions
$max_size = 200 * 1024; // Max file size
$path = 'uploads/'; // Folder where to upload
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if( ! empty($_FILES['image']) )
{
// Get the extension of the file
$ext = strtolower(pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION));
// Test the file format if it's allowed
if (in_array($ext, $valid_exts) AND $_FILES['image']['size'] < $max_size)
{
$path = $path . uniqid(). '.' .$ext;
// Put the file in the folder of uploads
if (move_uploaded_file($_FILES['image']['tmp_name'], $path))
echo $path; // returning the path
else
echo 'uploads/err.gif'; // returning the error message or path or whatever
}
else
echo 'uploads/err.gif';
}
else
echo 'uploads/err.gif';
}
else
echo 'uploads/err.gif';
?>
In you're view, you have to include jQuery.form library and. you create a form, and inside the form you put an image and a button, the form should have the link of you're php file as action, and call this function:
$('#form').ajaxUpload($('#button'),$('#image_preview'));
The definition of ajaxUpload function is this:
jQuery.fn.ajaxUpload = function(Button,Preview)
{
var Frm = $(this); // form
var Btn = Button; // upload button
var Prev = Preview; // preview area
Btn.click(function()
{
// implement with ajaxForm Plugin
Frm.ajaxForm(
{
beforeSend: function()
{
Btn.attr('disabled', 'disabled');
Prev.fadeOut();
},
success: function(Result)
{
Frm.resetForm();
Btn.removeAttr('disabled');
Prev.attr("src",Result).fadeIn();
},
error: function(Result)
{
Btn.removeAttr('disabled');
Prev.attr("src",Result).fadeIn();
}
});
});
};

How do you access other files stored on an website with JavaScript?

I am trying to write a webpage for a list of files to download. The files are stored with the webpage and I want the webpage to dynamically list all the files in the folder to download. That way when more are added I don't have to modify the webpage. I know how to use JavaScript to create links on the webpage but I need to use it to find the names of the files first.
I found a website that had code for navigating files like a file browser but it only uses a string to store the current location.
This is in the header:
<script type="text/javascript"><!--
var myloc = window.location.href;
var locarray = myloc.split("/");
delete locarray[(locarray.length-1)];
var fileref = locarray.join("/");
//--></script>
this is in the body:
<form>
<input type=button value="Show Files" onClick="window.location=fileref;">
</form>
However this doesn't really help since I am trying to create download links to files not have a file browser.
Edit:
When you host a traditional HTML page you upload the htmlfile and any images or content for the page to what ever server you use.
I want to use javascript to dynamically link to every file hosted with the webpage.
I am trying to combine this with hosting the files in a Dropbox public folder for a simple way to make the files available.
If you want a list of files on the server you will need to use a server-side script to gather their names:
JS--
//use AJAX to get the list of files from a server-side script
$.getJSON('path/to/server-side.php', { 'get_list' : 'true' }, function (serverResponse) {
//check the response to make sure it's a success
if (serverResponse.status == 'success') {
var len = serverResponse.output.length,
out = [];
//iterate through the serverResponse variable
for (var i = 0; i < len; i++) {
//add output to the `out` variable
out.push('<li>' + serverResponse.output[i] + '</li>');
}
//place new serverResponse output into DOM
$('#my-link-container').html('<ul>' + out.join('') + '</ul>');
} else {
alert('An Error Occured');
}
});
PHP--
<?php
//check to make sure the `get_list` GET variable exists
if (isset($_GET['get_list'])) {
//open the directory you want to use for your downloads
$handle = opendir('path/to/directory');
$output = array();
//iterate through the files in this directory
while ($file = readdir($handle)) {
//only add the file to the output if it is not in a black-list
if (!in_array($file, array('.', '..', 'error_log'))) {
$output[] = $file;
}
}
if (!empty($output)) {
//if there are files found then output them as JSON
echo json_encode(array('status' => 'success', 'output' => $output));
} else {
//if no files are found then output an error msg in JSON
echo json_encode(array('status' => 'error', 'output' => array()));
}
} else {
//if no `get_list` GET variable is found then output an error in JSON
echo json_encode(array('status' => 'error', 'output' => array()));
}
?>

Zend_Form Jquery & fileUploadErrorIniSize

Edit, I fixed it by changing my JS to:
$('.zend_form input:not([type="file"]), .zend_form textarea').each(function() {
data[$(this).attr('name')] = $(this).val();
});
Hello,
As I posted earlier, I followed a ZendCast that allowed you to use jQuery to detect and display to users problem with their form.
However, file fields always return: fileUploadErrorIniSize (File 'image_front_url' exceeds the defined ini size" even if the file is within size limits.
TPL For Forms:
<?php $this->headScript()->captureStart(); ?>
$(function() {
$('.zend_form input, .zend_form textarea').blur(function() {
var formElementId = ($(this).parent().prev().find('label').attr('for'));
doValidation(formElementId);
});
});
function doValidation(id) {
var url = '/<?php echo MODULE; ?>/json/validateform/form_name/<?php echo get_class($this->form); ?>';
var data = {};
$('.zend_form input, .zend_form textarea').each(function() {
data[$(this).attr('name')] = $(this).val();
});
$.post(url, data, function(resp) {
$('#'+id).parent().find('.errors').remove();
$('#'+id).parent().append(getErrorHtml(resp[id], id));
}, 'json');
};
function getErrorHtml(formErrors, id) {
var o = '';
if (formErrors != null) {
var o = '<ul id="errors-'+id+'" class="errors">';
for (errorKey in formErrors) {
o += '<li>'+formErrors[errorKey]+'</li>';
}
o += '</ul>';
}
return o;
}
<?php $this->headScript()->captureEnd(); ?>
<?php
if (is_object($this->form) && $this->form->getErrorMessages()) {
echo $this->partial('partials/errors.phtml', array('errors' => $this->form->getErrorMessages(), 'translate' => $this->translate));
}
?>
<?php if (isset($this->errorMsg)) { ?>
<p><?php echo $this->errorMsg; ?></p>
<?php } ?>
<?php echo $this->form; ?>
Which is directed to
<?php
class Administration_JsonController extends Zend_Controller_Action {
public function validateformAction() {
$form_name = $this->_getParam('form_name');
$form = new $form_name();
$data = $this->_getAllParams();
$form->isValidPartial($data);
$json = $form->getMessages();
$this->_helper->json($json);
}
}
Example of returned json:
{"name":{"isEmpty":"Value is required and can't be empty"},"name_url":{"isEmpty":"Value is required and can't be empty"},"image_site_url":{"fileUploadErrorIniSize":"File 'image_site_url' exceeds the defined ini size"},"image_url":{"fileUploadErrorIniSize":"File 'image_url' exceeds the defined ini size"},"image_front_url":{"fileUploadErrorIniSize":"File 'image_front_url' exceeds the defined ini size"},"image_back_url":{"fileUploadErrorIniSize":"File 'image_back_url' exceeds the defined ini size"}}
I noticed a few people had this issue and they said that isValidPartial fixes it, so I changed
$form->isValid($data);
to
$form->isValidPartial($data);
but it didn't fix this issue.
Any ideas?
The problem is that you can't treat file fields in the same manner as regular text fields.
When you call $('input').val(), you get an actual text value for the text field, but for the file field you get the file name - and not the file contents.
Then your script tries to validate your file name as a file and, apparently, fails. In order for file validator to succeed you need to pass actual file contents to the script.
So, basically, you need to upload a file asynchronously to the server to perform all the necessary validations.
Unfortunately, uploading files via Ajax is not quite a trivial thing to do. Your basic options are uploading files via iFrame or swfObject. You can take a look at the broad selection of plugins suitable for this purpose here.
My personal choice for asynchronous file upload would be file-uploader jQuery plugin.
Are you putting an Encrypt type on your form?
I have found two different forum posts about this, including a stack post:
odd Zend_Form_Element_File behavior
You need to add enctype="multipart/form-data" to your form tag.
Basically what is happening is the form is using its default "application/x-www-form-urlencoded" method of encryption before it is sent to the server. File uploading is not supported with this method.

Categories

Resources