encodeURIComponent() and how it can help in your jQuery AJAX calls

April 11, 2011 — Mike Hommé
Mike Hommé's picture

I'll refine this post to make it easier to read later but am publishing now, to get my thoughts out. Maybe it'll help in this state.

For starters I'm working with PHP, MySQL, jQuery 1.5.1

When passing data from a jQueryUI dialog to a PHP script via AJAX (jQuery), which performs a very basic database transaction, either INSERT or UPDATE, and the POST'd data includes an amprasand for one of the values, such as "I want to include this & that for fun", everything after the "&" doesn't make it into the record. Now you're left with "I want to include this ", "& that for fun" doesn't get inserted or added.

Obviously this is not what we want, right?

I tried obvious things server side including htmlentities(), addslashes(), urlencode() and htmlspecialchars() yet, nothing worked.

Then, I tried encodeURIComponent() in my client-side code, in the dialog init... problem solved.

Makes sense now, but for anyone with a brain that works like mine, which I hope you don't, I hope this helps.

Some Example Code:

// Encoding form values that may include special characters with
// the built in Javascript function encodeURIComponent()
// such as description and category.

var new_sku = $("#new_sku").val();
var new_description =  encodeURIComponent($("#new_description").val());
var new_category = encodeURIComponent($("#new_category").val());
var new_price = $("#new_price").val();

var dataString = 
'new_sku=' + new_sku + 
'&new_description=' + new_description + 
'&new_category=' + new_category + 
'&new_price=' + new_price;

$.ajax({	  
   url: "../ajax/product_add.php",
   data: dataString,
   type: "POST",
   dataType: "html",
   async:false
}

This works for me.

Comments welcome, I'm I still doing it wrong?

Comments (3)

Guest's picture

Thank you!

Thank you!! I struggled with this until i found your site and the above example!

Guest's picture

Thanks for this

Worked like a charm :). I was digging around forever for "escaping special characters" etc for my contact form, though I couldn't find the exact answer until I came across this function.

I would enjoy a read on how the function differs from all the other traditional workarounds though.

Mike Hommé's picture

You're welcome...

I would love a read on how it differs. I think the clean up on the client side, before it's sent to the server, is the the take away. Glad it helped you!