I have a javascript function that creates an XMLHttpRequest object or ActiveObject based on the browser being used living in a file called ajax.js
HTML: user.php
<ul id="list-of-developers">
<li class="list-title"><strong data-new-link="true">DEVELOPERS</strong>
</li>
</ul>
JAVASCRIPT: ajax.js
function ajaxObj2(meth, url, contype){
var xhttp;
if (window.XMLHttpRequest)
{
xhttp = new XMLHttpRequest();
}
else
{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open(meth, url, true);
xhttp.setRequestHeader("Content-type",contype);
xhttp.setRequestHeader("Access-Control-Allow-Origin", "http://localhost:9000/");
return xhttp;
}
function ajaxReturn(x){
if(x.readyState==4 && x.status ==200)
{
return true;
}
}
In my user.php file which contains my html and the script tag including the ajax.js file in the head of the document.
Here is how the javascript connects with PHP (NB: This tag is located at the bottom of the document outside the body tag)
JAVASCRIPT: user.php (inline)
<script>
window.onload = function()
{
var u = "<?= $u ?>";
var r = "<?= $user_role ?>";
var x = ajaxObj2('GET', 'retrieveDevelopers.php','text/plain');
x.onreadystatechange = function()
{
alert("H u is: "+u+ " r is: "+r + " RESPONSE: " + x.responseText.trim());
if(ajaxReturn(x) ==true)
{
alert("got here");
var list_of_devs = document.getElementById("list-of-developers");
console.log(list_of_devs);
list_of_devs.innerHTML = x.responseText.trim();
}
}
console.log(u);
x.send("u="+u + "&r="+r);
}
</script>
PHP: in retrieveDevelopers.php
<?php
$x = $_GET["u"];
$m = $_GET["r"];
if(isset($_GET["u"]))
{
include_once("phpincludes/db_connx.php");
//echo
$person= preg_replace('#[^a-z0-9]#i','',$_GET["u"]);
$person_sql = "SELECT * FROM USERS WHERE USER_ID=(?) AND ACTIVATED=(?)";
$person_params = array($person, 1);
$person_options = array("Scrollable" => SQLSRV_CURSOR_CLIENT_BUFFERED);
$person_result = sqlsrv_query($db_connx, $person_sql,$person_params, $person_options);
$person_state = sqlsrv_num_rows($person_result);
if($person_state < 1)
{
echo "Failed to verify user";
exit();
}
else
{
echo("It Worked");
exit();
}
}
echo "failed";
exit();
?>
I get errors "Notice: Undefined index: u in line 9" and "Notice: Undefined index: r in 10"
I don't understand why this is. The database connects without issue. These files are all in the same folder except for the database connection script
Filesystem:
- /retrieveDevelopers.php
- /user.php
- /phpincludes.php/db_connx.php
- /script/ajax.js
System Info
Apache Version:2.4.17
PHP Version: 5.6.15
MICROSOFT SQL SERVER 2012
Localhost: localhost:9000