Outdated Computer Tech
Outdated Computer Tech

Reputation: 2026

ampersand symbol in ajax query being ignored

i've isolated the problem to my ajax not allowing ampersand symbols to be inserted into the query. So for example the str or string being inputted is Fish & Chips. Only Fish Shows.

function showBrand(str) {
var xmlhttp;
if (str=="") {
  document.getElementById("txtBrand").innerHTML="";
  return;
}
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("txtBrand").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","getBrand.php?q="+str,true); // <-- Problem?
xmlhttp.send();

}

When the Query gets sent to getBrand.php, and when you enter a & symbol it converts it into a variable in the url im assuming. Being terrible at ajax i don't how to fix this problem.. Anyone have any suggestions?

Upvotes: 0

Views: 138

Answers (2)

Barmar
Barmar

Reputation: 780871

& is used for separating multiple parameters in a query string. You need to use encodeURIComponent to ensure that all special characters in the parameter are encoded.

xmlhttp.open("GET","getBrand.php?q="+encodeURIComponent(str),true);

Upvotes: 1

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11707

Try this:

 xmlhttp.open("GET","getBrand.php?q="+encodeURIComponent(str),true);

Upvotes: 1

Related Questions