0

I'm sending JavaScript values via POST method using AJAX. Everything works fine except that I'm unable to send strings with & (ampersands). I tried encodeURIcomponent but nothing seems to work. Everything after the ampersand gets lost.

This is my code:

AJAX call

function chpr(gffo){

  var fd=gffo;

  var vl=document.getElementById(message).value;
  vl = encodeURIComponent(vl);

  if((vl)!=""){

    var xmlhttp;    

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        document.getElementById("msg").innerHTML=xmlhttp.responseText;
      }
    }

    xmlhttp.open("POST","example.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("q="+fd+"&w="+vl);

  }

}

On the PHP side I'm fetching it as:

$w = $_POST['w'];

So for example if I want to send Me & You,

on the PHP side it fetches just Me.

Nisse Engström
  • 4,555
  • 22
  • 24
  • 38
user3225075
  • 343
  • 1
  • 3
  • 22

3 Answers3

1

Encode ampersands as %26 (URI percent encoding, cf. rfc 3986, 2.1).

collapsar
  • 15,446
  • 3
  • 28
  • 56
0

You can get all values which is sending by ajax please use below code it will be help you.

<?php
$q = $_POST['q'];
$w = $_POST['w'];
?>

You can also use $_REQUEST place of $_POST

-1

Here is how to send content with XmlHttpRequest:

var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

From: Send POST data using XMLHttpRequest

This post: http://www.tutorialspoint.com/php/php_get_post.htm explains how to get the values from PHP:

<?php
  if( $_POST["name"] || $_POST["age"] )
  {
     echo "Welcome ". $_POST['name']. "<br />";
     echo "You are ". $_POST['age']. " years old.";
     exit();
  }
?>
<html>
<body>
  <form action="<?php $_PHP_SELF ?>" method="POST">

  Name: <input type="text" name="name" />
  Age: <input type="text" name="age" />

  <input type="submit" />
  </form>
</body>
</html>
Community
  • 1
  • 1
Georgi-it
  • 3,458
  • 1
  • 17
  • 23
  • 1
    I'm not sure how this answers the question. The OP is successfully sending and receiving information so general information about how to send and receive (unencoded...) values is not really helpful. – jeroen Apr 20 '15 at 09:35