Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Solving this issue of sending arabic characters using ajax

I'm using an AJAX form in order to send data to another page named 'show.php'. Here is the source of pages:

form.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="ajaxsbmt.js" type="text/javascript"></script>
</head>
<div id="MyResult"></div>
    <form method="POST" action="response_norma.php" name="MyForm" onsubmit="xmlhttpPost('show.php', 'MyForm', 'MyResult', '<img src=\'indicator.gif\'>'); return false;">
      <input type="text" name="mytext" size="20">
      <input type="submit" value="Submit" name="ok">
    </form>
</body>
</html>

show.php

<?php
  echo $_REQUEST['mytext'];
?>

ajaxsbmt.js

function xmlhttpPost(strURL, formname, responsediv, responsemsg) {
  var xmlHttpReq = false;
  var self = this;
  // xhr for Mozilla/Safari/Ie7
  if (window.XMLHttpRequest) {
    self.xmlHttpReq = new XMLHttpRequest();
  }
  // xhr for all other versions of IE
  else if (window.ActiveXObject) {
    self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
  }
  self.xmlHttpReq.open('POST', strURL, true);
  self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  self.xmlHttpReq.onreadystatechange = function() {
    if (self.xmlHttpReq.readyState == 4) {
      // When ready, put the response into the form
      updatepage(self.xmlHttpReq.responseText, responsediv);
    } else {
      // While waiting for the respnse, display a message
      updatepage(responsemsg, responsediv);
    }
  }
  self.xmlHttpReq.send(getquerystring(formname));
}


function getquerystring(formname) {
  var form = document.forms[formname];
  var qstr = "";

  function GetElemValue(name, value) {
    qstr += (qstr.length > 0 ? "&" : "")
            + escape(name).replace(/\+/g, "%2B")
            + "="
            + escape(value ? value : "").replace(/\+/g, "%2B");
            ´//+ escape(value ? value : "").replace(/\n/g, "%0D");
  }

  var elemArray = form.elements;
  for (var i = 0; i < elemArray.length; i++) {
    var element = elemArray[i];
    var elemType = element.type.toUpperCase();
    var elemName = element.name;
    if (elemName) {
      if (
           elemType == "TEXT" 
        || elemType == "TEXTAREA" 
        || elemType == "PASSWORD" 
        || elemType == "BUTTON" 
        || elemType == "RESET" 
        || elemType == "SUBMIT" 
        || elemType == "FILE" 
        || elemType == "IMAGE" 
        || elemType == "HIDDEN"
      ) 
        GetElemValue(elemName, element.value);
      else if (elemType == "CHECKBOX" && element.checked) 
        GetElemValue(elemName, element.value ? element.value : "On");
      else if (elemType == "RADIO" && element.checked) 
        GetElemValue(elemName, element.value);
      else if (elemType.indexOf("SELECT") != -1)
        for (var j = 0; j < element.options.length; j++) {
          var option = element.options[j];
          if (option.selected) 
            GetElemValue(elemName, option.value ? option.value : option.text);
        }
    }
  }
  return qstr;
}

function updatepage(str, responsediv) {
  document.getElementById(responsediv).innerHTML = str;
}

PROBLEM

When I type English characters in the filed, data transfer successfully and I receive them top of the form.

But when I try to type Arabic characters, I receive another data, something like encoded words. e.g: %u0633%u0644%u0627%u0645. %u0686%u0637%u0648%u0631%u06CC instead of:
سلام. چطوری (if you have font.)

How can I solve this problem?

like image 411
Andrew Avatar asked Jun 07 '12 12:06

Andrew


People also ask

What does AJAX () method do?

The ajax() method is used to perform an AJAX (asynchronous HTTP) request. All jQuery AJAX methods use the ajax() method. This method is mostly used for requests where the other methods cannot be used.

What is AJAX with example?

AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

How do I respond to AJAX?

This AJAX Ajax. Response is the object passed as the first argument of all Ajax requests callbacks. This is a wrapper around the native xmlHttpRequest object. It normalizes cross-browser issues while adding support for JSON via the responseJSON and headerJSON properties.


2 Answers

You're using escape() and some fancy custom replacements. Don't do this.

escape() is broken and there is very little reason to use it.

The function you're looking for is called encodeURIComponent().

// use an array to hold the query string parts
var qstr = [];

qstr.appendParam = function(name, value) {
  this.push( 
     encodeURIComponent(name) 
     + (value > "" ? "=" + encodeURIComponent(value) : "")
  );
  return this;
}
qstr.toString = function () {
  return "?" + this.join("&");
}

// use like this:
qstr.appendParam("foo", "bar");
qstr.appendParam("arabic", "سلام. چطوری");

// now make a real query string.
qstr.toString() // "?foo=bar&arabic=%D8%B3%D9%84%D8%A7%D9%85.%20%DA%86%D8%B7%D9%88%D8%B1%DB%8C"

The above should replace your GetElemValue() function. Note how you can tweak objects by adding functions you need (like appendParam()) or overriding functions that are already there (like toString()).

Also note that you can return the array itself from your function getquerystring(). JavaScript calls toString() automatically in situations like this:

var url = "http://bla/" + qstr

Since toString() is overridden, the right thing will happen.

like image 112
Tomalak Avatar answered Oct 11 '22 13:10

Tomalak


<?php
  $orignialmytext = $_REQUEST['mytext'];
  $decodedmytext = urldecode($orignialmytext);
  echo $decodedmytext;
?>
like image 36
exception Avatar answered Oct 11 '22 14:10

exception