Question

I have an XML request in my javascript file that is not transferring my variable correctly to PHP and I cannot figure out why. Could I possibly be missing a reference library of some sort?

Here is the function in question. I do know that the str variable has what I want inside. I am leaving old trial code in comments just in case you want to see what I have tried.

function PHP_Con(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}

if(!xmlhttp)
{
alert("Fehler");
}
else
{

/*$.ajax({
type:"POST",
url:"dbConnection.php",
data:{"test" : "str"},
success:function()
{
alert("success");
}
});*/

alert(str);
xmlhttp.open("GET","dbConnection.php?test="+str,true);                       
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send();

/*var json_string= JSON.stringify(str); // convert it into a json string. 
$.post('dbConnection.php' , {test : json_string },function(){
alert("success");
}); */

}
}

And here is my corresponding PHP code:

$test = intval($_POST['test']);
echo $test;

Also, I know about isset but I am trying to get the variable to show up. I'd rather get an error when it is not there, if that makes since...

Thank you very much. :) If there are easier ways to do this, I would be interested in that as well.

But as of now I feel like I do need to have a Form that calls a JS function, then my JS has variables retrieved from user input, and then those variables go to PHP so that they can be checked against my database... it all seems like the right order to me, but I admit to not having a very clear view of how JS variables show up in PHP and also of how PHP can respond in a way that is reflected through HTML code... for example I would like to "echo" back to a span in a p with the results of the comparison (user input against the database contents) and I have no idea of how that is done...

Was it helpful?

Solution

You are sending a GET request so you have to use $_GET instead of $_POST

$test = intval($_GET['test']);
echo $test;

a POST request would look like

xmlhttp.open("POST","dbConnection.php",true);                       
// Requestheader senden
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// Request senden
xmlhttp.send("test="+encodeURIComponent(str));   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top