jquery

All posts tagged jquery

send-file-iconupload-files-icon-ts7tteez

As we continue to push forward on development our users have asked for a robust way of dragging and dropping images and linking them to a work order.  I was putting this off for a while because I thought it would be a pretty difficult task but after a few Google searches I found a great jQuery plugin from blueimp called jQuery-File-Upload.  Take a look at their demo and check out how awesome it is.  We didn’t need any of the fancy bells and whistles that came with the Basic Plus UI so this tutorial focuses on just the Basic but you can scale yours how you’d like.  The tutorial will also focus on getting it to work and save to a MySQL database through Django.

To start off let’s get the drag and drop area set up on our page.  To do that you’ll need to add these things to your HTML template, Django tags are added because that is what we are using to render the page.

image_upload.html

With the code above you should be ready to drag and drop files immediately, at least from the front end perspective. Now let’s set up the server side of things. Make sure you add your URL from the fileupload to your urls.py file. Then create a view for that URL that looks something like this.

views.py

The view handles all of the uploaded files one at a time and saves them to wherever we would like. In this case we are making a database entry that houses the file in an ImageField and we have a CharField for a name that we can change without altering the file path used in the ImageField. The JSON output is important as it will read the data sent back and can output our newly added images right to the screen.  That’s all there is to it.

Now there may be some circumstances where you would like to add more data to the request than just the images you have dragged over.  In our case we wanted the work order number to be attached as well and saved in the file name.  Using jQuery File Upload we can add data anytime something is dropped by adding a bind call to all fileuploadsubmit method calls.  I added the following lines of code in the HTML template just underneath the var url line.

This will add the workorder id to the POST request data on every call using the fileupload. Another thing to note is you can add a check to see if you really want to submit the uploads like I have done. If the workorder is not active do not upload any images. You can customize this any way you’d like since it is all just JavaScript and jQuery code.

Another problem I ran into was having multiple file upload elements on the same page. This was really frustrating and reading through their documentation they had a fix that worked pretty well with a couple of tweaks.

First, to make all of the drag and drop areas work independently of one another you change the fileupload elements from having an id of fileupload to a class of fileupload. This will need to change on the above code for bind as well. But you can’t simply change it on the $(‘#fileupload’).fileupload() becuase then it will upload once for every drag and drop element on the page. You instead have to take it a step back and add these lines.

This allows every fileupload classed element to take files individually. But this was annoying because users had to drop the files right on the button to make it work. As you can see there is a new parameter we’ve added called dropZone. This tells the fileupload what area of the page to watch for. If you want to make this area bigger or smaller that is totally up to you. I changed mine to dropZone: $(this).parents(".panel-body") to allow the user to drop images anywhere inside the panel body and they will start the upload.

I hope this was useful to someone. We are actually going in a different direction with our image uploads but we may need this in the future and I wanted to document how I got it all working with both jQuery File Upload and Django.

EDIT

Thanks to Tuan Nguyen for pointing out that in its default configuration each image is uploaded in its own request.  To join these into one request, open up the jQuery-File-Upload/js/jquery.fileupload.js file and search for the line singleUploadFiles: and set it to true.  You can also limit the number of files to be uploaded right below by changing limitMultiFileUploads:.

jquery_logo

I write a lot of posts that use jQuery but I haven’t gone through the basics of getting started with jQuery on your new website.  There are just a couple of steps that you need to do to get started with using jQuery and getting it started right.

The first thing you’ll need to do is load jQuery into your website.  The easiest way to do that is to add the following line inside the <body> of your base HTML template that will be used throughout the site.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

Google hosts a number of web libraries and they are a great way to get the latest version of various libraries without have to hit your servers with serving those same files.  If you are using an older version, or an altered version, of jQuery you’ll want to host it yourself but this is the simplest way to get started.

Once that has been loaded into the <body> of your base HTML file you can start writing JavaScript using jQuery.  The best way to ensure that your code is run in a timely fashion, namely after the page has been completely loaded, you’ll want to run document.ready.  The jQuery document.ready is run once everything has been loaded into the DOM, in other words once everything, all the inputs and CSS, has been loaded in this function will run.  It’s best to put a lot of your code within this function to ensure that everything that the triggers will be applied to are loaded and can have these triggers applied.  Your JavaScript file should look something like this.

Feel free to put whatever you want inside of that ready function.  You can even make calls to other JavaScript functions you have in the file.  I hope this helps people get started with jQuery.  I’ve seen a lot of people struggle with getting it imported into their site and have it run smoothly.  If you have any tips or questions about jQuery feel free to leave a comment below.

A very important tool when working with JQuery is the ability to traverse through elements in the DOM.  When a user clicks on a button you may want to change the color of the nearest row to display the click.  Maybe after an input you want to change the nearest column to be hidden or show that input value.  Whenever you need to walk through the elements in your page JQuery has a way to do it.  All of the methods shown here can be called with no arguments but are more helpful if you call them with a selector of some kind either an id, class, or element type.

The first question you have to ask yourself is where is the element I’m looking for from my current location?  For instance, that button that was clicked is on a row.  The row element contains the button so we need to travel upwards.  When traveling up you can do one of two things, $.parent() or $.parents().  The difference between the two is that the latter travels more than just a single level in the DOM.  Obviously that makes it a bit less efficient but it is exhaustive.  If you know you’ll need to travel up a layer or two to find the parent element you’re looking for then use parents.  The example below demonstrates the button changing the parent row it is in.

$( "button" ).parents("tr").css("font-family", "Times New Roman" );

If you need to go down in the DOM you can use either $.children() or $.find().  Again the difference is that the latter travels more than one layer.  An interesting thing that may happen is when you are at the level you want to be but need to find an element at that same level.  That is where $.siblings() comes in.  It will search for the element on the current level of the DOM you are in.  Combining these methods together can help you locate elements all throughout your page.  For example, once I needed to find the nearest error messages div because I had one near a variety of inputs and place text inside of it.  I first used $.parents('error-row') to find the row it was in.  Then used $.children('.error-display') to find the div within that held the text.

Obviously naming things uniquely with id’s is the safest way to go as you can reference things directly but in the case of a complicated page with many layers and hidden elements it may be nice to traverse your page to find your elements.  It also may be easier to simply change the nearest element rather than name every little item on your page.  JQuery traversal has its place and remember if you can’t find it at one level you may need to go up one more.

Bootstrap comes with a lot of different JavaScript tools to make your website more user friendly.  Today I’m going to cover Tabs and then give a more advanced example for making your tabs have dynamic content using AJAX.  We all know what tabs look like and in a website they can be very useful to group similar content without having to create a new page for each chunk of data.  Below is an example of the basic Bootstrap tabs.

You’ll notice that there are two sections to the tabs. The first is the nav-bar ul. This is where you give each tab a title. You can even do drop downs here because they are normal Bootstrap nav items.  That’s all there is to the basic Bootstrap tabs.  They work wonders and you can see the live demo on their site here.

To make each tab load in data via AJAX you’ll need to tap into Bootstrap’s triggers.  Here’s what I did using the same example as above and the JQuery below.

The trigger is fired when the tab is changed and the e.target is the event target, or in our case the newly activated tab.  Since the tab’s href points to the id of the element we want to change data we can use that to point our data to when it comes.  I’ve added a check to make sure we are only making the AJAX call if that tab is empty to help on load times of large data sets but you can remove that if you’d like.

That’s all there is to it.  Nothing too difficult but useful when you need tabs and need to change that data without reloading the page.  Let me know how you are using tabs below in the comments.

One of the best ways to make a page of data better is having a nice, visual way of looking at the data and graphs and charts do a great job of that.  Figuring out which graph works best for your situation is up to you but in almost all of the cases jqPlot has a way of rendering that on your website.  JqPlot is an open-source project with a ton of features, graph and chart types, and visual options to make wonderful graphs for your site.  Today I’m going to go over a few of the different types of graphs and then give some more advanced tips on using jqPlot.

Line Graph and Others

One of the big features of jqPlot is its plug-ability.  You don’t need to load every jqPlot script in on every page you only need to load in the relevant script used for the graphs on your page.  This cuts down on loading time and makes your code easier to read.

Line graphs are the most basic of graphs and they are so easy to setup with jqPlot.  Below is the code and the result.  I’ve inserted it as an image here but on your page it will be rendered as HTML.

graph

Line graphs can have multiple sets of data to have more than one line of data.  Using the options you can even change the style of each line in the graph.  Below is an example from their website and you can see the options that they have changed to make each line look different.

lines
There are a lot of different types of graphs including pie, bar,  and so many more.  Take a look through their site to see them all.  The great thing about jqPlot is they are all rendered with almost the same code.  Each jqPlot code is rendered by calling jqplot, giving an element to place the graph in, and then setting your data and giving options.  Just below is an image of how I have used the pie charts and bar graphs to display data for some of our clients, names have obviously been changed.
Supplier Overview

Advanced AJAX

Up to this point we haven’t used any AJAX calls to pull the data.  Obviously to help with page loads some AJAX calls for data would be helpful.  To do this you need a helper method that jqPlot will use to make the AJAX calls.  One thing to note is to make sure the data is returned in such a way that the graphs can use.  Generally this is in a list containing integers like the first example  For multiple series’ just do a list of lists.  Simple enough?  Let’s look at the helper method and the jqPlot AJAX calls I make.

The first variable function is used in the two jqPlot calls as an AJAX helper.  The next section, labeled Labels, is used to get the labels for the graphs.  The labels for the graph need to be there when the graph is rendered and cannot be added after.  I have the names of the series’ around the page so I just pull them.  Another way you could do it is the return a dictionary from your AJAX call and then split it in the ajaxDataRenderer function but I have done it this way.  To use the renderer you just call jqplot, give the target and the remote URL and everything should run smoothly.

The line graph is first and as you can see I have a title, which is translated using Django’s JavaScript translation, we put the labels and pad the axis to make everything flush.  The bar chart is similar in almost every way with the exception of a couple of options specific to bar charts.  Below is the result of the two graphs I’ve created.  Some of the text is a bit scrunched together so a little rework is needed but for the most part it is ready to go.  Changing fonts and sizes is simple with the jqPlot options.

example

Nothing too special but it works for me and looks great on the page.  I hope this has been informative to someone.  JqPlot is pretty vast in its documentation and can be a little overwhelming.  If there are any questions or weird things you come across feel free to comment below.