There are many reasons why the invasion did not work. Follow the link below to read a very detailed discussion of the invasion and its problems. In general, there were two major problems.
First, the invasion did not have the sort of US support that it would have needed. For example, the Cuban Air Force was supposed to be destroyed by US-backed air strikes. This was not done completely and the Cuban Air Force was able to sink some of the invasion force's ships and shoot down its airplanes. The US did not want to openly support the invasion and was not willing/able to help.
Second, the invasion was not as popular with the Cuban people (particularly those in the region of the Bay of Pigs) as it was expected to be. It was expected that the invasion would get support from people in Cuba. This did not happen as most of the people who disliked Castro had already left the island.
The lack of US support and support from the Cuban populace were the main causes of the failure.