I've checked out some of the other similar questions but they aren't doing exactly what I'm trying to do. I'm ajaxing a php page to echo the contents of a folder on my server. Right now, I have it listing the files line by line. I would simply like to take the value of each line and add it to a select box.
If I can just come up with a way in javascript to run a loop for each line found from this php page, I can add the option to the select myself. Any idea of how to accomplish this? Everything I find online is for a different scenario and I can't find anything that'll work. Thanks
Edit: This is the closest I've gotten
var files = msg.split(" ");
$.each(files, function(index, value) {
var x = document.getElementById("Emulators");
var option = document.createElement("option");
option.text = files;
x.add(option);
});
When I do that, this is the result
Any idea why it's the last drop down is looking like that? This is what the php page is outputting
The easiest way, seeing as you're already using JS/jQuery would be to use $.append() doc.
Either do this as part of your return or loop through the file. You shouldn't need to create the file if you add it to the .success(data) the function of the ajax call. Simply have the PHP file you're calling echo out what you need in a format you can interpret, eg json_encode your output array.
Edit adding suggestion:
THE FOLLOWING IS UNTESTED AND PURELY FOR EXAMPLE:
NB: this expects test.php to output the formatted data as an array parsed through json_encode.
$.ajax({
url: "test.php"
}).success(function(data) {
var files = JSON.parse(data);
$.each(files, function(index, value) {
$('#result-div').append( value );
});
});
Here is a way to iterate through the data using the array map function to call jQuery's append function.
const mySelect = $('#my-select');
const files = ['path/file1.ext', 'path/file2.ext'];
files.map(x => {
mySelect.append( $('<option value="' + x + '">' + x + '</option>') );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="my-select"></select>
Related
I have been searching for the past hour and have not found a solution that is well suited to my situation. I have an event registration form and in order for users to have the form auto populated they can specify an id from a previous registration. There are over 20 fields.
Everything is working pretty well. I have a PHP script that creates an xml response for ajax. The xml is of form
<response>
<field1>f1</field1>
<field1>f2</field1>
etc
</response>
My javascript is
$.ajax({
type : "POST",
url : "myscript.php",
data : $(this).serialize(),
success: function(xml){
$("#field1").val($("field1",xml).text());
$("#field2").val($("field2",xml).text());
}
})
Above works fine but I don't want to manually write out each form field assignment. I want to do it in a loop. So something like this in the success function:
var fields= xmlResponse.getElementsByTagName("response");
for (i = 0; i < fields.length; i++) {
// not sure what to put here...
}
In the for loop I have to index in to the node name and value so that I can simply have a statement that would be of this form: $("#"+fields[i].nodename).val($(fields[i].nodevalue,xml).text());
I tried
$("#" + fields[0].childNodes[i]).val(fields[0].childNodes[i].nodeValue);
But that did not return the values.
Any idea on how best to do this? I feel like I am very close to having this working! Thanks!
You can use $.parseXML, and then loop over the elements with .each().
var $xml = $.parseXML(xml);
$("#response", xml).children().each(function(i, e) {
var field = e.tagName;
var value = e.innerHTML;
$("#" + field).val(value);
});
You're on the right track. What it comes down to is that when you parse an XML file, the parser doesn't care what the fields are, it'll parse it as it sees it. You would basically have to tell the script to pull certain tags with certain text. As far as I know, this is best done using the .tagName property and the tag's value and storing it in an object.
var data={}
$(this).children().each(function() {
data[this.tagName]=$(this).text();
})
You can see how this would work here:
http://jsfiddle.net/dpK7x/1/
So I'm in the midst of a rather sticky problem. I'm coming close - so close! - to solving it but not quite there. I've seen lots of examples but none that do just exactly what I want.
On a php page myreqpdo.php, I recover some data lines from a MySQL table and store them in a two-dimensional array. On my page index.php, I need to access this array via JavaScript and play with it a bit before sending it to what I need to fill.
Here is myreqpdo.php:
$locWanted = $_POST['searchTerm'];
echo json_encode(getVillesCPs($locWanted));
function getVillesCPs ($searchTerm) {
// code to access DB here
return $resultats;
}
I found this example using jQuery, but it's for an instance in which one would just like to insert the list directly into the code without any further manipulation:
<html>
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>
<!-- this UL will be populated with the data from the php array -->
<ul></ul>
<script type='text/javascript'>
$(document).ready(function(){
/* call the php that has the php array which is json_encoded */
$.getJSON('json_encoded_array.php', function(data) {
/* data will hold the php array as a javascript object */
$.each(data, function(key, val) {
$('ul').append('<li id="' + key + '">' + val.first_name + ' ' + val.last_name + ' ' + val.email + ' ' + val.age + '</li>');
});
});
});
</script>
</body>
</html>
That won't work for me, because this function is one that is triggered based on search parameters. I need something like the following pseudocode:
<script>
var myArray = {code to recover PHP array};
// manipulations for myArray here, using data to fill values of items on page
</script>
I keep thinking the answer is right under my nose, but I am really not seeing an example like what I want! Any ideas?
You don't need jQuery to insert an array from PHP in your javascript code, just insert it directly where needed:
<script>
var myArray = <?php echo json_encode(getVillesCPs($locWanted)); ?>;
// manipulations for myArray here, using data to fill values of items on page
</script>
Note that you must set a value to the $locWanted var in your PHP code before this code, otherwhise getVillesCPs will be called with an empty parameter.
EDIT: since your getVillesCPs is defined in another PHP file, include it in your main page before calling it (assuming your main page is a PHP file):
<?php
//including the PHP file containing the function
include 'myreqpdo.php';
//setting a value for $locWanted, used then in the rest of the page
$locWanted = 'Paris';
?>
<script>
var myArray = <?php echo json_encode(getVillesCPs($locWanted)); ?>;
// manipulations for myArray here, using data to fill values of items on page
</script>
And remove the 2 first lines of code in myreqpdo.php, you don't want to echo anything before the function is called.
I'm dynamically creating the json urls based on what is currently saved inside a browser cookie.
var cookie = $.cookie('faved_posts');
The contents of that cookie are 123456, 111111, 000001, and so on.
Now I'll need to request the json file for each ID that was saved in that cookie.
I have the following:
$.each(cookie, function(i, val){
$.getJSON('/ajax/posts/'+val+'.json', function(data){
var html = "<div>" + data.post.headline + "</div>";
$("#container").html(html);
});
});
I'm able to retrieve all the files
/ajax/posts/123456.json
/ajax/posts/111111.json
/ajax/posts/000001.json
The problem I'm having is I can only render the data.post.headline value from only one of the ajax files.
This is what I need outputted in html:
<div>headline for 123456</div>
<div>headline for 111111</div>
<div>headline for 000001</div>
What is the best way to do something like this? Thanks
$("#container").html(html);
.html() will replace everything that is currently in #container which would mean you would only see the html from the last execution of the loop. I believe you are looking for append() instead.
I have a csv file sitting on my server (using Apache 2) which I would like to "read" when a webpage loads. After reading the contents (two columns that are comma separated), I want to have one column be the display contents of a drop down list and the other column be the "data" contents. For instance, if I had a csv where the first row was [1,"me"], I would want the "me to be displayed to the user and the 1 to be the data that I could understand (selected value).
I know very little on javascripting and html (still learning), so any simple help would be much appreciated. To recap:
How do I read CSV file off my server (currently doing localhost)?
How do I parse this CSV file and add each row as an entry of a dropdown list?
Thanks!
How do I read CSV file off my server (currently doing localhost)?
First, you'll need to fetch the data from the CSV file so you can work with it as a native JavaScript object. Using jQuery's $.get() method, you can make an asynchronous request to the server and wait for the response. It would look something like this:
$.get(csv_path, function(data) {
var csv_string = data;
//Do stuff with the CSV data ...
});
How do I parse this CSV file and add each row as an entry of a dropdown list?
This can be accomplished with a for loop and some jQuery:
(function() {
var csv_path = "data/sample.csv",
var renderCSVDropdown = function(csv) {
var dropdown = $('select#my-dropdown');
for(var i = 0; i < csv.length; i++) {
var record = csv[i];
var entry = $('<option>').attr('value', record.someProperty);
dropdown.append(entry);
}
};
$.get(csv_path, function(data) {
var csv = CSVToArray(data);
renderCSVDropdown(csv);
});
}());
Note that this code calls a CSVToArray method, which you must also define in your code. An implementation can be found here, thanks to Ben Nadel: Javascript code to parse CSV data
I am using a multiple file upload field <input name="filesToUpload" id="filesToUpload" type="file" multiple /> in my app.
What I want to accomplish is to list the files the users chose and than allow them to delete any of them in the list.
At the end, when the form is submitted, I send the whole data via AJAX, as binary, using the FormData object.
It all works great, except for the delete part.
I know that the FileList attribute is read-only, so what I did was to distribute the files as values of hidden input fields, appended to each of the li where I list the file names. So if the user removes a li item, the hidden input field is gone with it, and at the end, I collect all remaining by appending them to the FormData object.
Problem is, every attempt I made to assign the files as values to the hidden inputs gave me weird results.
My code is something like this:
listFiles : function () {
var file, files, filesList, filesLength, read;
files = this.files;
filesList = $('.files');
filesLength = files.length;
// Clear the list
filesList.html('');
for ( var i = 0; i < filesLength; i++ ) {
file = files[i];
// This is to read the content of the file
read=new FileReader();
read.readAsBinaryString( file );
// When reading is finished
read.onloadend = function() {
filesList.append(
'<li>' +
'<span class="fileName">' + file.name + '</span>' +
'x' +
'<input type="hidden" name="file[]" value="' + read.result +'"/>' +
'</li>');
}
}
}
I just get the data from the last file, also, the DOM is broken since the data gets printed all over the place.
Demo here => http://jsfiddle.net/zKyXC/
I have tried various ways to implement the method described above ( assign each separate file to the value of an input[type="hidden"] field in order to allow file delete functionality ) but non of them were successful.
At this moment, I do not know if this is this possible to be done at all.
However, I did manege to solve the problem with an alternative solution. Here it is in case someone else finds it useful.
Instead of using input[type="hidden"] I used a global array where I stored the files upon receiving them. Then I remove items from that array the standard way you would remove objects from an array. At the end I append each item to the formData object and send it to the server.
I create and fill the global array like this:
globals.files =[].slice.call( this.files );
i remove from it like this:
$.each( files, function( index, val ) {
if ( this.name === fileText ) {
globals.files.splice( index, 1 );
}
});
Note : fileText is where I store the name of the item to be deleted.
And at the end I append it to formData :
var formData = new FormData();
$.each( files, function( ind, val ) {
formData.append( 'files[]', this );
});
And send this as the data property of a standard jQuery ajax call.
if I am not wrong, only file with quotation mark " goes wrong, if you do not escape it, value will be cut off at the first occurence of " and the rest part will be shown as html, so what you need is
read.result.replace(/"/g, '"');