2

I have three codes the first one is html:

<html>
<head>
<script type = "text/javascript" src = "AJAX.js"></script>
</head>

<body>
<form method = "GET" >
    <input type = "text" id ="a" ><br>
    <input type = "text" id = "b"><br>
    <input type = "button" value ="click"  onclick = "process()"><br>
    <textarea id = "underbutton" ></textarea><br>
</form>
<body>
</html>

Now javaScript (AJAX) :

function process() {
    if(xmlHttp.readyState==0 || xmlHttp.readyState==4){

        a = document.getElementById("a").value;
                b = document.getElementById("b").value;
        xmlHttp.onreadystatechange = handleServerResponse;
        xmlHttp.open("GET","file.php?a="+a+"&b="+b,true);
        xmlHttp.send();
    }
}

function handleServerResponse (){
    if(xmlHttp.readyState==4 && xmlHttp.status==200)
        {

        response = xmlHttp.responseText;
        document.getElementById("underbutton").innerHTML =  response ;


        }

}

Now php file :

<?php  

echo $_GET['a'].'<br>';
echo $_GET['b'].'<br>';

?>

everything is working but the problem is when I type in the first texbox (a) the word hello and the second (b) the code & and click the button ; it must print out hello&.
but it prints hello!!
just hello without &.

I noted that I was sending to php file is this : file.php?a=hello&b=&.
the last & must be %26

So to print out & I must send : file.php?a=hello&b=%26.

How can I fix that ??

user2229472
  • 509
  • 3
  • 10
  • You can't, really. The `&` has a special meaning in a query string - it's the parameter separator. It needs to be encoded if you want to include it as a value. – andrewsi May 14 '13 at 17:51
  • http://stackoverflow.com/questions/11294107/how-can-i-send-the-ampersand-character-via-ajax – ioums May 14 '13 at 17:54

5 Answers5

3

Change in the JavaScript:

- a = document.getElementById("a").value;
- b = document.getElementById("b").value;
+ a = encodeURIComponent(document.getElementById("a").value);
+ b = encodeURIComponent(document.getElementById("b").value);
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405
3

You have to URL-encode your values:

xmlHttp.open("GET","file.php?a="+encodeURIComponent(a)+"&b="+encodeURIComponent(b),true);

You need this because the parameters in your URL are splitted on '&' and so its like:

a=hello & b= & *(here could be a third parameter)*

kelunik
  • 6,750
  • 2
  • 41
  • 70
1

Using jQuery.AJAX() will take care of the problem for you, I think.

Code Whisperer
  • 22,959
  • 20
  • 67
  • 85
1

Use encodeURIComponent()

xmlHttp.open("GET","file.php?a="+encodeURIComponent(a)+"&b="+encodeURIComponent(b),true);
Tamil Selvan C
  • 19,913
  • 12
  • 49
  • 70
0

To encode an ampersand (&) in URLs, you use &amp;. What happens when you replace it with that?

dnord
  • 1,702
  • 2
  • 18
  • 34