Sunday, October 27, 2013

Zen of Python by Tim Peters

Python has an Easter Egg :) just try to import this like this
import this
you ll get this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

File Upload with jQuery and Ajax

The requirement is simple. I should be able to upload files to the server with jQuery and ajax. Lets get started.
<html>
   <form>
     File Description:<input type="text" id="desc" />
     Choose File:<input type="file" id="chosenFile" />
     <input type="button" id="submitFile" value="submitTheFile" />
   </form>
</html>
Now, the real jQuery stuff
<script type="text/javascript">
    jQuery.noConflict();
    jQuery(document).ready(function() {
        jQuery("#submitFile").click(function() {
            jQuery.ajax({
                url: "[url to be submitted to]",
                type: "POST",
                contentType: false,
                processData: false,
                data: function() {
                    var data = new FormData();
                    data.append("fileDescription", jQuery("#desc").val());
                    data.append("chosenFile", jQuery("#chosenFile").get(0).files[0]);
                    return data;
                    // Or simply return new FormData(jQuery("form")[0]);
                }(),
                error: function(_, textStatus, errorThrown) {
                    alert("Error");
                    console.log(textStatus, errorThrown);
                },
                success: function(response, textStatus) {
                    alert("Success");
                    console.log(response, textStatus);
                }
            });
        });
    });
<script>
Important things to be noted here are
contentType: false,
                processData: false,

contentType will be determined automatically, so we don't have to set that explicitly and processData has to be false, otherwise the data will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". Next important thing is

data: function() {
                    var data = new FormData();
                    data.append("fileDescription", jQuery("#desc").val());
                    data.append("chosenFile", jQuery("#chosenFile").get(0).files[0]);
                    return data;
                    // Or simply return new FormData(jQuery("form")[0]);
                }(),
You can read about FormData here. We basically set the values being submitted. The first parameter is the key and the second parameter is the actual value to be passed. We can get the value of any form field with
jQuery("#desc").val()
expect the files. If we use the same for files, we ll get just the file name instead of the file contents. So, we have to do something like
jQuery("#chosenFile").get(0).files[0]
If we dont want to set individual values and want to pass all the fields in the form, we can simply do
data: new FormData(jQuery("form")[0])
Thats it. Enjoy Ajaxified file upload :)
References: