user2612912
user2612912

Reputation: 63

xmlhttprequest not passing variable from javascript to php

I am make an interactive map in D3. I stored all data in MySQL database. Since the user is able to select year to see all data, I have to pass the year to server side(php) to query about the data of the specific year.

I do not know specific function in D3.js to help us pass variables to php, so I use XMLHTTP to send information to php.
My javascript:

a = "ARGGDP"
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "database/allcountry.php?a=a", true);
xmlHttp.addEventListener("load", ajaxCallback, false);
xmlHttp.send(null);

function ajaxCallback(event){
    alert( "loaded");
}

My php

header("Content-Type: application/json");

$a = $_GET['a'];
$username = "root"; 

However, it shows "Undefined index: a". Any idea about what should I do to fix this problem?

Upvotes: 0

Views: 1001

Answers (3)

Hüseyin BABAL
Hüseyin BABAL

Reputation: 15550

You can use following;

function sendAjax(data) {
  var xmlhttp;
  if (window.XMLHttpRequest) {
    xmlhttp=new XMLHttpRequest();
  } else {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200) {
      alert("loaded")
    }
  }
  xmlhttp.open("GET","database/allcountry.php?a=" + data,true);
  xmlhttp.send();
}

sendAjax("ARGGDP");

In php

$a = $_GET['a'];
echo $a;

Upvotes: 1

Bilal
Bilal

Reputation: 429

Your ajax request is working, the undefined index: a notice means the $_GET variable does not have a key 'a', maybe you are modifying $_GET somewhere in your code?

Upvotes: 0

BenBornschein
BenBornschein

Reputation: 91

You missed a ; at the end of your var "a" and didn't add the var to your url.

a = "ARGGDP";
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "database/allcountry.php?a="+a, true);
xmlHttp.addEventListener("load", ajaxCallback, false);
xmlHttp.send();

function ajaxCallback(event){
    alert( "loaded");
}

PHP

echo "<pre>";
print_r($_GET);
echo "</pre>";

Upvotes: 1

Related Questions