Aries
Aries

Reputation: 301

Jquery Ajax Call is Corrupting my data


please help to explain why my ajax calls via jquery is corrupting my data? i already setup my mysql database to use utf8_general_ci,

  1. i already tried adding items to my mysql database via phpmyadmin and the chinese characters are complete and have no changes.
  2. I also tried creating a simple php page to insert the same set of chinese characters, run the php page and check the output in phpmyadmin.. again no changes for the same set
  3. This time insert the same set of chinese characters via jquery $.ajax, but first dont send to the mysql but print to html.. SAME set and no changes done...
  4. Using the the php page in #2 use ajax and INSERT now to database... some characters are now missing and have been change to '???'..

any idea whats going on? i also tried echoing my $query and it prompts me the character already missing before it was actually send to the database

thanks

Upvotes: 1

Views: 1970

Answers (1)

Niko
Niko

Reputation: 6269

in order to get around this, try setting the ocntenttype in the ajax request:

...
    jQuery.ajax({
        type: "POST",
        url: "../ajax/setting",
        cache: false,
        dataType: "json",
        data: "user.id=current&update=true&user.setting=" + key + "&user.settingValue=" + escape(value),
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        beforeSend: function(x) {
            if((x) && (x.overrideMimeType))
                x.overrideMimeType("application/j-son; charset=UTF-8");
        },
...

the beforeSend trick might also help in your case. I found out that dpending on how you send the data it might be encoded quite different. If you want to submit a long data with charset make sure to encode it first:

ie. submitdata is a json string:

submitType = "POST";
submitdata = "data=" + encodeURIComponent(submitdata);
jQuery.ajax({
    type: submitType,
    url: url,
    cache: false,
    data: submitdata,
    dataType: "json",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    beforeSend: function(x) {
        if((x) && (x.overrideMimeType))
            x.overrideMimeType("application/j-son; charset=UTF-8");
        return true;
    },

on the server I take the request parameter "data" and convert it into an object.

Hope this helps

Upvotes: 4

Related Questions