Kenil Patel Kenil Patel -4 years ago 96
PHP Question

Why does $_GET always returns null even if the data is successfully sent through AJAX?

I am writing a PHP script to dynamically Create table in Mysql based upon users' input for number of rows and columns.
I am using AJAX to send the data to the server. In-spite of successful sending, server is receiving null values in $_GET array.

Here is my entire code:

<!DOCTYPE html>
<html>
<head>
<title>Welcome</title>

<style type="text/css">
#head-text{
text-align: center;
color: blue;
font-size: 250%;
}
</style>

</head>
<body>
<h1 id="head-text">Snippt</h1>
<div class="main-content">

<frameset>
<form>
<select name="n-cols" id="n-cols" onchange="createInputFields()">
<option>Number of columns</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
</form>

<div id="main">

</div>

<div id="display">

</div>

</frameset>

</div>
</body>


<script type="text/javascript">
function createInputFields(){

var x = document.getElementById('n-cols');
var n = x.value;

if(x.selectedIndex == 0){
alert('Choose a valid index');
}
//adding the input fields based on user's input

document.getElementById('main').innerHTML ='<br>';
for(var i = 0; i < n;i++){
var field_name = "text" + i;
//alert(field_name);
document.getElementById('main').innerHTML += '<input type="text" name = "col" placeholder="column name"> &nbsp;&nbsp; <select> <option>Integer</option> <option>Varchar</option> </select><br> <br> ';
}



document.getElementById('main').innerHTML+='<input type="submit" onClick="createTable('+ n +')" Value="Create Table">';

}


function createTable(n){

var column_names = [];

for(var i=0;i<n;i++){
var column_name = document.getElementsByName('col')[i].value;
column_names.push(column_name);
}

/*
Sending the column_names array to PHP file residing on the server
*/
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}


var column_names_json = JSON.stringify(column_names);
//alert(column_names_json);
xmlhttp.open("GET","create_table.php?col_name = "+column_names_json,true);
xmlhttp.send(null);
alert('data sent');
}

</script>
</html>


create_table.php

<?php

$arr_json = $_GET['col_name'];
$arr = json_decode($arr_json);

for($x = 0; $x< count($arr); $x++){
echo $arr[$x];
echo "<br>";
}

?>


When i am printing the content of $_GET, it returns NULL.

Answer Source

Change

xmlhttp.open("GET","create_table.php?col_name = "+column_names_json,true);

To

xmlhttp.open("GET","create_table.php?col_name="+column_names_json,true);

You have spaces in your URL string.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download