For those who aren't familiar, fan fiction refers to stories that use characters or other significant elements from an already published work. If you wrote a story about J.K. Rowling's character Harry Potter at Hogwarts using your own imagined scenarios, you'd be writing fan fiction. If you wrote about the childhood of Hagrid, a secondary character who appears in Rowling's series as an adult, you'd be writing fan fiction. Many fans indulge in their enjoyment of books, movies, and television shows by writing fan fiction. Some even post their stories on popular fan fiction web sites, where they can also read other writers' stories and post reviews.
The nitty-gritty of copyright law is this: fan fiction is considered a "derivative work" because it contains significant elements of a preexisting work. According to US Copyright law, only the owner of the copyright has the right to "prepare, or to authorize someone else to create, a new version of that work." And some authors don't grant this right to others. Anne Rice takes a strong stance against it, and fan fiction websites had to remove thousands of stories that used her characters. Still, not all authors oppose this practice. J.K. Rowling has said she is flattered by the fan fiction in response to her series. Still, she acknowledges that it should remain a non-commercial activity. In this particular case, that means posting it on a fan fiction site under your own name without any profit is bound to be ok. It isn't all right, however, to attempt to publish it in print, make money off of it, or fool fans of the books into thinking it's an official part of Rowling's series.
If you're looking to commercially publish a work based off copyrighted material, seek permission first. But be aware that it's not likely to be granted for fan fiction. You may find it more productive and rewarding to take that energy and enthusiasm and work on your own unique creations.