jquery file upload submit callback - javascript

im using the blueimp jquery file upload plugin . this code
<script>
$('#fileupload').bind('fileuploadsubmit',function(e,data){
var inputs = data.context.find(':input');
if (inputs.filter('[required][value=""]').first().focus().length){
return false;
}
data.formData = inputs.serializeArray();
});
</script>
is supposed to send all files along with the form data to the server. For some reason its not working . Firebug says ReferenceError: $ is not defined when this page is loaded. Should i define this callback in the main js ? ( I am able to add additional form data for the selected files when uploading and save the names onto the database. When using titles for each uploaded file these values are sent saved as typed when uploaded one by one. When uploaded all at once the value is the same as the first input. This callback supposedly uploads thses data one by one.

As shown in your jsfiddle, all the script includes are placed at the bottom of the page. So you either move them before your script tags, or you move your script tags to the bottom of the page. Otherwise jQuery will not be defined when you want to use it.

Fix this :
(e, data>
to
(e, data)

Related

JS: Submit or transfer input values to another HTML File?

Description:
I created this workflow: PHP loads content from a database to certain textareas. The user can edit and save content.
I created a HTML template which can be printed directly from the web browser.
So the user clicks on the "Print" button and gets a nice template which can be printed directly from the browser.
Goal:
I want jQuery or JavaScript to load / transfer the content from the input fields to another HTML document on the server, in certain div-classes.
Is this generally possible or a good idea?
Afterwards, this becomes loaded and the print dialogue of the web browser will be opened.
Present Code:
$(document).ready(function() {
$( ".print-button" ).click(function() {
$('html').load("./views/print/template-1.html");
setTimeout(function(){
window.print();
}, 1000);
})
window.onafterprint = function(e){
$(window).off('mousemove', window.onafterprint);
window.location.href = window.location.href;
};
});
So template-1.html should get the data.
First of all I think it would be a good idea to support the build in functionality of the browser. The user should be able to hit Ctrl+P or use the menu to open the print dialog.
My suggestion would be to create a <div> element that is hidden. On some event, like when the <textarea> is changed, update the <div> element with the content. Create a stylesheet for printing where the <div> element is visible and hide elements that are not for printing (like the <textarea>).
As per the description, you have mentioned that you are allowing PHP to load the data in certain text-areas and allows user to update that, so when you update this data, it'll be saving into the database for that particular text-area.
What best you can do here is keep one unique key for that shown data and when you redirect the page bind the unique key along with the page URL, so using that key on the new page where you have the template, you can get the data using select query and you can print the data wherever you want.
Afterwords on print click, the template will have the data filled in and so the user will be able to download/print the template with data, the way you wanted.
Or
If you don't want to use the PHP for getting data on the new document, you can simply pass the data object in localstorage by using below way :
var content= <your data Object>;
localStorage.setItem('print_content', content);
Now before loading the dialogue, get the data from localstorage variable and print it to div or area wherever you want. For getting data from localstorage use below way:
var printData = localStorage.getItem('print_content');
using printData var, you'll be able to get the data and using jQuery syntax you'll be able to append or display the data to div.

How to download files in bulk from browser console using JavaScript?

I have no experience with web programming, so my question would be a very simple one. I want to download a lot of files by filling out forms in a web page. The web page's extension is .aspx, and I am interested in only one field and a button. By fooling around with the console in my browser, I figured out that executing:
document.getElementById('TxtRegNo').value = 'blahblah`;
will fill the concerned field. Also doing a
__doPostBack("ImageButton1","Click");
will download the .pdf file curresponding to blahblah. The actual value which needs to be entered is a sequence like PAG-1200 to PAG-1900. I tried using a for loop, like this:
for (var i = 21618; i < 21621; i++)
{
document.getElementById('TxtRegNo').value = 'B14-' + i;
__doPostBack("ImageButton1","Click");
}
but it doesnot work as expected. only the last document gets downloaded, and I get this in the console:
Thought this error does not come whe nI run in FireFox's console, I can still run only one file. Could anyone tell me how to do this?
Try this:
Inject jQuery to the page via the console, as explained here: Include jQuery in the JavaScript Console
In your for loop clone the form, set the values as you wish and submit the form jQuery('form').clone().find('#TxtRegNo').val('blah').parent('form').submit();
If the page contains more than one form, you should specify it. 'form' works like css selectors here. This will find all forms on the page. Just use '#elementId' or '.elementsClassName' to be more concrete, if necessary.
Maybe you also need to change the name of the form (to be able to submit the forms simulatiously). I didn't try it, this is just a guess.
If you want to split the code to several lines you can also do this:
var myFormClone = jQuery('form').clone();
myFormClone.find('#TxtRegNo').val('blah');
myFormClone.attr('name', 'uniquename_' + iterationVariableOfForLoop);
myFormClone.submit();
If the submit failes, try:
myFormClone.get(0).submit();
Good luck!

Input type FILE multiple - add files sequentially

I am developing a page (one-time use - its registration page) when a visitor opens dialog box and uploads files throught input type file multiple.
All worked fine, but my client just told me they want to be able to upload multiple files from different directories. By opening that dialog more times.
Now, normally what happens is that when I open file select dialog another time, the previously selected files got removed from the input.
Is there any way (pure HTML or JS) that I could add the possibility to "stack" files - add them to the selection (maybe some JS object later converted back to input type file?) so that files can be added to the list of files in the input?
I would say that you have two options here.
Stick to classic form
If you want to keep the classic form logic, you will have to add more file inputs to keep your old selections.
A short script will look like :
$('input[type="file"]').on('change', function() { $(this).append('<input type="file" name="file[]"/>') });
So to add more files, the user can click on the next file input.
You can then enhance it to make it nicer with design stuff and remove functionality.
The HTML5 way
While the previous idea is simple, I think it lacks of design and user friendliness.
So the other idea is a more advance way, which will need a bit more of work but will let you do what you want and more (You could add drag/drop for instance).
So the basic idea is that when the user select a file, you will get the file in Javascript, you can do it by using the FileReader object.
When you have the file content, you can just queue it on a variable.
var queue = [];
function addFile(event) {
var files = event.target.files, i = 0, j = files.length, file, reader;
reader = new FileReader();
reader.onloadend = function () {
queue.push{ reader.result };
};
for (i = 0; i < j; i += 1) {
file = files[i];
reader.readAsBinaryString(file);
}
}
Note that If you want to keep the select dialog, you will need to keep the file input.
Once your user valid the form, you should send your other inputs first by Ajax (you want to stay on the page, or you'll have to store your files like in the localStorage which I think is a bad idea).
Then you'll have to send your file to the server using Ajax requests as well, it's easy as just sending the file bits to the server. And on your server you will have to get those bits and simply put it on a file (If you have a specific language for the server part we can extend on how doing it).
You can go then further that way and have the possibility to get the progress of the upload, cancel an upload, slice your files if you have size limitation, do drag and drop,...
Of course, you will to considerate that some browsers have some issues with this object, but it tend to be good everywhere.
Note on the "classic form"/JQuery solution given by Gregoire: this will not work on the newly added inputs, as the listener is not active on them. If you modify this to use delegated events you have a working clean solution:
<div id="files">
<input type="file" name="file[]" />
</div>
$("#files").on("change", "input", function(event){
$('#files').append('<input type="file" name="file[]"/>')
});

How do I change a HTML class via PHP?

I'm currently stuck at my "Newsletter Subscribe Form". I use MailChimp to send my newsletters and have managed to redirect the visitor of my page to a custom PHP file after entering the email.
The process goes like this:
User enter email
Email silently (user doesn't see it) gets added to the MailChimp Database (Email List)
Instant redirection to a self hosted PHP script.
4. The PHP Script changes the color of the button via a CSS Class in the HTML file.
I'm stuck right at Point 4, since I don't really know how to change a CSS Class in a HTML file with PHP. It's important that the webpage still remains in HTML (otherwise i'd use a simple variable in PHP).
Do I need to parse the PHP value to AJAX or JSON which then changes the class (probably with jquery?)
If yes, could you give me an example on how to do it? I have never really used JSON or AJAX before.
Thank you guys very much :)
It's a little bit difficult to understand the question completely.
If you're trying to output a class when the page loads, that's very easy using php:
<?php
$classVariable = "myClass";
?>
<div id="someID" class="<?php echo $classVariable; ?>">Some content</div>
PHP loads once, before anything else on the page, and never runs again. You can call other scripts using AJAX which can then return data that you can use. For example (using jquery)
<script type="text/javascript">
$.get("path-to-myscript.php", function(response){
// read the response in, perhaps you grab some class name from it
// for demo purposes, lets say this response is in json formatted as a simple string:
// '{ "class" : "someClass" }'
var data = $.parseJSON(response);
var newClass = data.class;
$("#someID").attr("class", newClass);
});
</script>

Using the file name captured with the html browse button in javascript

I am trying to create a form where I can upload demographic information such as name, etc. as well as upload jpg image files. I cannot figure out how to catch the file the user chooses from the browse button. Where is the file name stored? How can I access it for the upload? How can I access it to assign it as a variable eg:
var theFileName;
function()
if (filename !=null) { //manipulate the variable };
else { //something else};
I am new to JavaScript and trying to teach myself with web sources and books and cannot seem to find an answer. In addition to an answer to this question, can anyone suggest a good web source for further information on this subject? The ultimate goal is to be able to upload the info and files with PHP into a database so it can be recalled on another page but a different user.
http://jsfiddle.net/EDfsh/
if you look into this fiddle i've made, you have the code you need ;)
It uses jQuery.
Your HTML Input
<input type="file" id="pic" >
JavaSCript:
function fileName(test){
var source=test.value;
alert(source);
}
$(function(){
$('#pic').bind('change',function(){
fileName(this);
});
});
But you cannot see the source of the file. And you don't have the rights to see the whole path. So you just get the file name.

Categories