Cannot send special characters via jQuery ajax

27,178

Solution 1

Data (tags) must be encoded before sending it to server using encodeURIComponent()

Solution 2

Below code is working fine for sending & and "" or any special characters via ajax call:

specialChar1= "JΛ̊KE#2@#*&($^@%#*@#%))*$&@*(""" ;
specialchar2 ="??&!!--##";
url = "/get/" + encodeURIComponent( specialChar1) +"/"+  encodeURIComponent ( specialchar2 )
Share:
27,178
Jonathan Clark
Author by

Jonathan Clark

I am a single man working in a computer store here in New York. Trying to learn how to code in Python. Soon getting there.

Updated on July 05, 2020

Comments

  • Jonathan Clark
    Jonathan Clark almost 4 years

    I am developing a webpage where user is searching for files using tags. I am using jQuery Ajax to do the remote call to the API (database). It all works fine when I use non special characters like a-z but fails when using for example åäö.

    On the serverside I am using PHP. I print the tag to see if it "arrives" and all a-z works fine but the åäö is not displaying at all. They seem to not "arrive".

    What can be wrong?

    This is my jQuery code:

    var tags = $('#tags').val();
    
    $.ajax ({
        type: "POST",
        url: base_url + "search", 
        data: "tags=" + tags + "&limit=" + limit, 
        beforeSend: function (html) {
                $("#search_results").html("Searching for files...");
        },
        success: function (html) {
                $("#search_results").html(html);
        },
        error: function (html) {
                $("#search_results").html('Something went wrong!');
        }
    });
    

    This is my server side code:

    echo ($_POST['tags']);
    

    I search and looked at related questions about this here on SO but non helped me unfortunately.

    UPDATE

    Using this solved it! Works fine now.

    {tags: encodeURIComponent(tags), limit: limit}
    
  • Jonathan Clark
    Jonathan Clark over 12 years
    This don´t work either: data: "tags=" + encodeURIComponent(tags) + "&limit=" + limit
  • Vadim Gulyakin
    Vadim Gulyakin over 12 years
    Make sure that all parts of your flow are in UTF-8 check: HTML page; request encoding; server side encoding; AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); meta http-equiv="content-type" content="text/html; charset=UTF-8" Basically you will have to trace on which step character encoding is being lost.
  • shasi kanth
    shasi kanth about 10 years
    Thanks, it solved my issue with sending special characters in Jquery AJAX request in Internet Explorer.