jQuery smart multiple DIV replace with LiveQuery

Here’s a nice little trick that should match class=^loadIntoDiv(.*) and load the result of the link into the div with the id matching what’s in the (.*) when clicked.

Notice it uses the Live Query Plugin.

$(function () {
  $("[class^=loadIntoDiv] a:visible[href*='?']").livequery('click', function () {
    // The :last will get the outermost one if there are multiple levels of inheritance 
    // You might want :first for your situation
    var loadIntoDiv = $(this).parents('[class^=loadIntoDiv]:last').attr('class').replace(/^.*loadIntoDiv(\S+).*$/, "$1");
    $('div#' + loadIntoDiv).load(this.href);
    return false;
  });
});

USAGE:

<div class="replaceDivOne">
  <a href="http://site1.which.will.respond.to.xhr">Click here to load site1 into div id=One</a>
  <a href="http://site2.which.will.respond.to.xhr">Click here to load site2 into div id=One</a></div>
<span class="replaceDivTwo">
  <a href="http://site1.which.will.respond.to.xhr">Click here to load site1 into div id=Two</a>
</span>

Try it out and enjoy!

Note: You will need to link to a site which will respond to an xhr request for this to work properly.  See my post about how to get rails to do that with jQuery.

Posted in General | Tagged | Leave a comment

Using JQuery with Rails

There are a number of blogs out there which talk about using JQuery with Rails.  There are many more which don’t seem to quite get the unobtrusive nature of jQuery.

I’d recently started along the path of using only jQuery with my app and I immediately ran into a problem with Internet Explorer (IE) and with Google’s Chrome browser when it came time to use the Javascript load function to load an external request into an element on my page with an xhr request.  The problem was that from the perspective of my rails controller, both IE and Chrome appeared to be making plain old html requests, not Javascript ones, so respond_to was sending them an html response.

I’d seen the fix for this issue in a number of places, but the fix only seemed to work for Firefox, not for IE or Chrome.  After poking around a bit, I found this awesome site which helped explain the problem a bit more.

If I understand correctly, the issue is more with the browsers and how they set the Default XMLHttpRequest Accept header for you.

The standard solution that I’ve seen around is to use jQuery to set the XMLHttpRequest Accept header by adding the following to your public/javascript/application.js file:

jQuery.ajaxSetup({
  'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})

The problem with that is that it simply appends the existing Accept headers.  As we also see from what shall be henceforth known as Grauw’s Awesome Blog, you’re unlikely to be able to unset the value by passing either ” or null to the header for Opera (apparently also the current version Chrome from my experience).  Fortunately, you can unset it for IE which is a fairly popular browser as I understand it.  So here’s my attempt at a slightly better reset of the Accept header.

jQuery.ajaxSetup({
  'beforeSend': function(xhr) {
    // First unset it, then set (which otherwise appends)
    xhr.setRequestHeader("Accept", "");
    xhr.setRequestHeader("Accept", "text/javascript");
    }
})

With this, my load’s are now working in IE and Firefox.

ps.

If I really wanted to hack this into rails for all browsers, I’m thinking I could use a unique Accept header and setup a unique respond_to, or I could add something like this to my respond_to block:

format.html { render :partial =&gt; 'my_partial' if request.xhr? }

Although, I’m not sure how well that last one will degrade.

Posted in General | Tagged , , | 1 Comment

Maui

Leaving on a jet plane this morning to go to Maui for Chris’s wedding.

Should be an awesome time!

Posted in General | Tagged , | Leave a comment

Back to WordPress

This software is just awesome.
Typo was fun because it was RoR, but this is so much more slick. Wow what a pain it was to switch back tho.

I had to

  • Dump the SQLite DB, fix up the dump file (a bit manual, and a bit scripted)
  • Import the SQL into MySQL
  • Install an old version of WordPress (to try to get the categories/tags) – Failed
  • Convert the data in MySQL from Typo to WordPress with an old script I found
  • Upgrade WordPress to the latest version
  • Poke around the DB to fix a relationship that was broken by the script

If anyone has any interest, reply to this and I’ll post the details.

Posted in General | Tagged , , | Leave a comment

China, Day 9 – Xi’an

Our original plan was to see the Terra Cotta Warriors today, tour some local city sites, and then take the train out to Luoyang. But by the time we got into Xi’an on Day 8, all the hotel tour agencies were closed, and we could not find a ride to the warriors until the next day. So we decided to make the best of it and tour around Xi’an.

Xi’an (literally, “Western Peace”) is a beautiful historic city dating back to the 11th century BC. Xi’an was the capital city when China was first united under the Qin Dynasty, and was the starting point of the Silk Road, a transcontinental route linking the Roman Empire to China. But before we could begin exploring, we had to accomplish three key tasks: feed the belly, find a tour, and purchase train tickets.

We walked back to the center of town through the Muslim Quarter, picking up several delicious street foods along the way. The first was a fried pita, which tasted somewhere between an unsalted Trader Joe’s pita chip and a donut. Then, we grabbed a pancake-looking item stuffed with leeks, lamb, and cabbage and deep-fried to golden perfection. Our goal was to experience “real” Xi’an Chinese food, so we popped into a relatively full restaurant where people were slurping up noodles and eating kebabs. Unfortunately, we were quickly ushered to the empty second floor and handed an English menu with outrageous prices. We ate two kebabs (no sense in being rude) and left. Our second attempt was no better – we saw a place cooking pancakes filled with egg and onions and ordered one. While it smelled and looked delicious, it was super greasy and way to salty to be edible. This is the first time we felt jaded about our street food adventures.

We ended up buying a bag of walnuts and dates to munch on as we searched for a tour to the Terra Cotta Warriors. Luck was on our side and we found a reasonably priced tour at the second place we walked into. We then decided to book train tickets to Luoyang. Finding a ticket window was a real challenge, but we finally found it and booked two train tickets on the “hard seats,” which saved us lots of cash.

Administrative tasks completed, we grabbed a cab to take us to the Da Yan (Giant Wild Goose) Pagoda. This astounding seven story structure was built in AD 652 to house Sanskrit texts (Buddhist scripture) and relics brought from India by the Chinese monk Xuanzang. Unfortunately, the Pagoda itself was closed to visitors due to concerns over its structural integrity after the earthquake. But we had a wonderful time exploring the side temples and museums, which housed beautiful ancient images of Buddha and jade and wood reliefs depicting Xuanzang’s journey and the history of Buddhism. We also ran into the Lutheran travelers, who had just arrived in Xi’an after a 2-day train ride from southern China!

After the Pagoda, we returned to the Muslim Quarter. First, determined to get good street food, we stopped into an open-air restaurant for a quick bite. Our determination paid off! We ate a whole host of kebabs and some delicious noodles in a peanut sauce, all for under $8. Then we decided to explore the Great Mosque of Xi’an. Built over 1,200 years ago, this is one of the oldest and most renowned mosques in China, and continues to be a functional place of worship for the over 50,000 Hui Muslims who live in Xi’an. The mosque is located smack in the middle of a crowded tangle of street markets, making it nearly impossible to find. But the hunt was very much worth it. We were puzzled, then amazed, by the juxtaposition of Arabic lettering with Chinese architecture, such as a Chinese-style pavilion with the Arabic words for “One God” carved into the entrance. Quite accidentally, our visit coincided with evening prayers, so we were fortunate to hear the call to prayer and observe the male Muslims enter the great prayer hall to worship.

Pleased with this discovery, we headed back to the center of town to climb the Xi’an Bell and Drum Towers. It is an understatement to say that these towers blew the Beijing Drum and Bell Towers out of the water, though our experience may have been tainted by our continued sheer luck. Both towers were beautifully illuminated with red paper lanterns and offered impressive views of the city. Best of all, we arrived at each tower just in time to see a performance using traditional Chinese instruments! What fun! The Drum Tower show featured various percussion instruments, while the Bell Tower show had wind instruments and (you guessed it) bells.

After this full day of sightseeing, we meandered back to our hotel. We stopped into a market to grab breakfast foods and realized that we were hungry for dinner. Feeling that we had pushed our luck to the maximum for one 24-hour period, and being quite tired of Chinese food, we totally sold out and went to McDonald’s for dinner. We each enjoyed a Quarter Pounder with cheese, fries, and a delicious chocolate sundae. Nothing like commercial cooking to satisfy the American palette…!

Posted in General | Tagged , | 1 Comment

China, Day 8 – Hot Air Balloon and Arrival in Xi’an

We woke up before the sunrise and were greeted by the balloon company owner who drove us out to a field where his staff was prepping the rainbow-colored hot air balloon. The morning was misty, cool, and quiet. We jumped into the tiny basket that barely fit us, another woman from California, and the balloon pilot. Moments later, we were in the air floating above Yangshuo.

The balloon experience was pretty magical. It was so quiet that our voices never exceeded a whisper. At first I was jittery, but I quickly became relaxed. Our flight lasted about 40 minutes, during which time we climbed high above the karst peaks and gently hovered over an orange grove, where the pilot picked an unripe orange for me. We landed in the middle of a roadway and jumped out of the basket to avoid the oncoming cars!

Feeling rejuvenated by the experience, we headed back to the hotel, where we packed up and checked out. We grabbed some sweet bao off the street for breakfast – one was stuffed with sugar and peanuts and the other looked like a cinnamon roll, but with sugar and green onions instead. We stopped into a bakery and tasted some rich pastries, including a sesame cake stuffed with a sweetened squash (in Spain we call it “calabacin” and it is one of my favorites) and a cheesy danish. A funeral procession walked by, mourners lighting firecrackers and throwing paper confetti on the road before the coffin. It was somber, but celebratory.

We then relaxed on a park bench and read for several hours. Hungry again, we stopped into the noodle soup house and ordered noodles with local vegetables. This ended up being super tasty and cheap to boot. We chatted with some Chinese students who were learning English and were eager to practice. Their open warmth was really sweet.

After a long, lazy afternoon (in hindsight, we could have squeezed in one more sight, but we were tired), our car drove us back to the Guilin airport for our flight. We landed in Xi’an around 9:00PM. To my chagrin, we could not find my printed itinerary that had our hotel name. Feeling quite lost, we boarded a bus that would take us to the center of the city. We found an internet gaming center that was jam-packed with kids playing online games, logged on to email, and found our hotel information. We then walked through the Muslim Quarter, a bustling, busy street, and up a side street to the Grand New World Hotel.

The hotel wasn’t in the city center, but was close enough (although at 11:00PM and laden with our bags, it seemed like the longest walk ever!). Plus, it was fabulous. Definitely 5-star accommodations at a 3-star price (under $60 a night!).

Posted in General | Tagged , | Leave a comment

China, Day 7 – The (REAL, Famous!) Yangshuo Water Cave

We slept in today, a much needed rest after six days of early-morning “wake-up and go!” adventures. Feeling lazy, we meandered around town in search of brunch, and found some delicious looking options at “Mei You” restaurant. I had the French toast special, which came with yummy fresh fruit, scrambled eggs and some so-so bacon. Billy got toast, fried eggs, bacon, a banana pancake, and some delicious fresh watermelon juice. And I had coffee, a delicious treat after consuming way too much green iced tea.

Although our spirits and stomachs were revived by this “Western” breakfast, Billy’s legs and butt still hadn’t forgiven him for the rough bike ride the day before. So we rented an electric scooter to get to our day’s adventure: the famous Yangshuo Water Cave and Moon Hill. Incidentally, the electric scooter is the way to go, what with high gas prices. We’re seriously considering getting one for my daily commute to work.

Countless tourist brochures advertized local “water caves.” But we wanted to see THE Water Cave, a vast cavern with an underground waterfall, rivers, and mud baths. After asking at various tourist agencies and getting conflicting responses, we decided to just drive out to the water cave illustrated on our very rough (and, as we had found out the previous day, inaccurate) map. Thank goodness for the scooter – we passed the water cave turnoff and had to backtrack, which would have taken forever on bikes.

Once at the ticket office, we realized that the price was much higher than we had seen quoted around town. No worries – everything is negotiable in China! I used my skills to get us half price tickets and was quite pleased with myself. We then waited for the minivan that would take us out to the cave entrance.

The drive out was long and super bumpy. Part of the fun! When we arrived, we were provided with “no slip” flip flops (glorified shower shoes), hard hats, and “torches” (flashlights). We got on a rickety boat and headed for the entrance, which reminded me of the entrance to the Blue Grotto in Capri, Italy – we had to duck down in order to get in, and remain ducked down until we were inside the cave.

The cave itself was massive. Think of the largest cathedral you have ever been in, and then multiply it by a thousand. Add weirdly-shaped stalagmites growing from the ground that look slimy, but are solid rock to the touch. Throw in miles of long stalactites hanging from a height so tall that you can’t possibly see the top. There were random pools of clear blue water and squishy-looking, shimmery hills. The cave was so vast and so silent that we both got an eerie, almost scary feeling. The path was fairly well maintained as we climbed countless stairs into the center of the cave. We must have walked over 10 kilometers through the interior, and each turn provided new landscape. Thinking we might be trudging through rivers and mud, we did not bring the camera in, and were sad that we hadn’t.

We originally went in with a Chinese tour group, but were later pawned off on an “English-speaking” guide who was leading a group of British guys and a German girl. They were a blast and we’re glad we joined them. Where our Chinese group had been timid (and smoking! Seriously? Do you really need a cigarette when you’re seeing nature in all its glory?), these guys were ready to strip down and jump into the pools and waterfall. Bill and I climbed to the edge of the waterfall and stood under the frigid cold water. Bill, being more daring then me, also jumped into the pools and river. I was scared of the blind fish (little shrimpy looking guys that might, MIGHT have teeth. Or tentacles. You don’t know). Our British friends had cameras and snapped a couple pictures of us (thanks, Jonny Prince!).

On our way out, we hit the mud bath. It was like walking into warm melted chocolate, only much less tasty. I know this because some kids decided to have a mud fight as we gingerly walked in, and a glob hit me squarely on the face. Once in, we floated on the surface. This is one time we were thankful for the tourist aspect – there was a Disneyland-esque photographer taking pictures, and we bought one for 10 yuan. Because when will we ever float in a mud bath in China again?!

We rinsed off in the makeshift shower and headed out of the cave. It was freezing cold! We changed into warm clothes and waited for our minivan to pick us up. And waited. And waited. And waited. After nearly an hour, a teeny-tiny van arrived. We all packed in and hit the bumpy road back, each bump magnified by the teeny-tininess of the van. Part of the fun?!

Then it was back to the scooter and back on the road to Yangshuo. On the way back, we stopped at the Moon Hill Café, a nice outdoors restaurant that provided excellent pictures of a karst peak that has a hole in it which resembles the moon. We plugged in the scooter and ordered spicy sausage-stuffed peppers and homestyle dumplings, which were made with delicate eggs instead of wonton wrappers and stuffed with a sausage and mint filling. Billy enjoyed a hot chocolate and I had ginger tea (literally, hot water with a huge hunk of ginger) to stave off the cold.

We also stopped at the bus station to check schedules for a bus back to Guilin for our flight to Xi’an the following night. I entered, leaving Billy to watch the scooter, and was immediately overwhelmed. Billy went in and came out ten seconds later with a picture of the bus schedule to Guilin. He’s just good like that. We also scooted around the back roads of Yangshuo and bought some bananas from a local market.

Back at our hotel, we decided to splurge and book the hot air balloon ride for the following morning. It was on the pricey side, but, after mulling it over for a few days and meeting the balloon owner, we went for it. And, deciding we could afford it, we booked a car service to take us back to Guilin the following day.

Posted in General | Tagged , | Leave a comment

China, Day 6 – Yangshuo Countryside (and Bill’s Birthday!)

Today was Billy’s birthday, and we woke up to dismal rainy weather. Determined not to let it spoil our plans, we donned our very fashionable bright orange rain parkas and met our friends. Being good sports, they agreed that we should still rent bikes and tour the countryside despite the weather.

We had a quick bite at the Dumpling Dynasty, where we ate 20 dumplings for about 50 cents. Genvieve and Carmelle gave Billy a birthday present (a beautifully painted tiny ceramic elephant with an upturned trunk – good luck, they said), and, after renting our mountain bikes, we hit the road.

Using a very rough map provided by the CITS tour guide we met the first day, we biked down a stretch of highway past two towns. Twenty minutes into the trek, we were soaking wet and worried that we had gone too far and missed a turnout that would take us into the countryside and off the road. But an older local woman who had followed us since Yangshuo motioned that we should keep going. Later, she motioned that we should turn left. Billy thought that she was just being nice, but, mere seconds after our left turn she began her hard sell for a bamboo raft to take us down the river. Despite our many “bu yao’s” (“don’t want” – one of the most useful Chinese phrases we learned) and waving of hands, she continued to follow us.

It was Children’s Day in China, and the town children were dressed in fun costumes with face paint and fun hairdos. We stopped momentarily to watch an outdoor children’s performance at a local elementary school, but, noting that we were quickly becoming the stars ourselves, we moved on.

We arrived at a river dock, where locals had set up their bamboo rafts to take tourists down the river. The older woman and her fellow raft owners motioned that, due to the rain, the bike paths were muddy and dangerous. We couldn’t possibly do a countryside bike ride, they indicated through charades and emphatic “no’s!” Determined to have an adventure, we ignored their comments and, to their incredulity, took off down a muddy path toward a small village. We came across an old bridge and risked the camera’s well-being by taking several terrific shots in the rain.

Our trek took us through fields and villages, often on paths that were hardly walk-able, let alone bike-worthy. But we trudged on! At some points, we got off the bikes and walked them through the mud, our shoes sinking into the soft soil of farmers’ planted fields. When we thought the rain was over and took off our ponchos, it began again. But every minute was worth it. We past the Camel Sleeping karst peak, and also had a momentary glance at Moon Hill. We biked through orchards and past children playing on their doorsteps. We noted, with amusement, that houses without indoor plumbing proudly displayed satellite dishes and large televisions.

Finally, after much muddy effort, we came across a wide open paved path. Oh, glorious paved path! We took the path to another river crossing, where we paid locals to take us and our bikes across the small stretch on a bamboo raft. The path took us through amazing karst landscape all the way into town. Cold, drenched, and tired, we decided to go to our respective hotels and meet up later for warm noodle soup.

We chose a hole-in-the-wall local restaurant for noodle soup. After ordering, we watched a woman chop up a chicken (likely to be eaten later that night) with a massive cleaver. Our soups arrived. Bill’s Sichuan-style was ultra spicy, and my braised beef was just right. My favorite part was the tiny bits of spicy pickled string beans sprinkled on top. The soup warmed us right up.

We parted ways with our friends and walked along the main drag, enjoying the tourist shops. Back at our room, we sat on the balcony and read for several hours until the mosquitoes became unbearable. We then popped into another local restaurant and ravenously attacked a whole “Mongolian style” chicken with crispy skin spiced just right. Delicious! On our way back, we haggled with a vendor for a beautiful wooden mask of a tiger face. Pleased with our day but exhausted, we crawled into bed.

Posted in General | Tagged , | Leave a comment

China, Day 5 – Li River Cruise & Yangshuo

We packed up our backpacks and waited for the bus that would take us to the Guilin docks for our cruise of the Li River to Yangshuo. En route, we met a pair of handsome travelers from the Midwest who were studying to become Lutheran ministers and a Scot who was traveling Asia alone. We were also told to stick with our group, the “Panda group,” to avoid getting lost in the hubbub at the docks. We felt like bonafide tourists as we followed the Panda flag across the parking lot and store area.

When we arrived, we boarded one of nearly twenty identical ships and found our Canadian friends on board! A fun reunion. Our river cruise through the amazing landscape of karst peaks lasted approximately three hours, during which we saw peaks that looked like various things – horses drinking from the river, a woman and baby looking over the water. We realized that, much more than geology, the Chinese care about what things look like, or what they symbolize. This intrigued us as it was a departure from “Western” thinking. Each peak was more amazing than the previous, and the morning mist and fog made it all the more mysterious.

We ate lunch, which had been cooked on the back of the ship, family-style with the Lutheran pair and some French tourists. The meal was filling and surprisingly tasty. Billy spent an additional 10 yuan to get us some deep-fried crawfish that tasted like little seafood potato chips, and we hoarded the bananas which were served as dessert.

We arrived at Yangshuo sooner than expected as the tropical rainstorms had flooded the river, making it run much faster than normal, and were immediately accosted by vendors at the dock. After successfully negotiating around them, we looked for our hotel, the Overseas Chinese Hotel, which we had booked through CITS in Guilin. The hotel was good – located on the main drag, it had a balcony overlooking the river and air conditioning, a must-have due to the incredibly humid climate. But the bed and bathroom were minimal, and the room smelled of mildew. Still, we had a Western toilet and a clean place to stay, so we checked in.

At one point several years ago, Yangshuo must have been a sleepy little village with the occasional traveler. Today, it, and all its inhabitants, cater entirely to the tourism industry. After meeting with a CITS agent who tried to sell us overpriced tours and rentals before we even left our hotel lobby (which we declined) and debating whether or not to book a hot air balloon tour (it was expensive), we ventured out to the town. There we found Western restaurants, hundreds of tiny hostels, lots of overpriced shops, and “tour guides” at every turn offering rides on bamboo rafts (“bam-boo? You want bam-boo? I have bam-boo!”), bicycle tours of the countryside, illegal DVDs (“DVD? Indiana Jones FOUR, the new one. FOUR. The new one!”) and other goods. Overwhelmed by the sales-y aspect, we quickly found a bicycle rental shop, rented two mountain bikes, and biked out of the main town.

After mere minutes of biking, the landscape turned from “tourist-central” to “real China,” and became peaceful and serene. We biked through a field until a farmer tending his crops shooed us away. We went past an isolated guest house that looked like fairly nice accommodations, and then through a tiny village past a man walking his water buffalo. Billy discovered a flight of stairs on the side of a karst peak, and we decided to lock our bikes and climb it. We instantly felt like Indiana Jones (FOUR! The new one!) as we trekked up the steep rock stairs carved right into the side of the peak, trying to avoid massive spider webs and mosquitoes galore. After about a 20-minute climb, the stairway ended, and we scrambled up the rocks to the top of the karst peak. The view was stellar and well worth the climb.

As daylight turned to dusk, we cycled back towards town, stopping in on a tai chi/kung fu school to check their class schedule. We then returned our bikes, and hit the hotel shower.

Being somewhat tired of Chinese food, and with so many Western restaurants available, we decided to have pizza for dinner. Alas, the pizza was sorely lacking. But we got a laugh from the pull-tab Watson’s Ginger Ale, and shared a delicious ice cream sundae for dessert. We also ran into Carmelle and Genvieve and decided to spend the following day touring the countryside together.

Posted in General | Tagged , | Leave a comment

China, Day 4 – Longji Rice Terraces

Posted in General | Tagged , | Leave a comment