Query not working through JavaScript with 500 internal server error - javascript

I'm new to AJAX and I'm trying to create two dropdownlists of options from a database depending on what the user selects in two previous dropdowns. I've checked every way shape and form I've looked up but one dropdownlist doesn't return any values and the other says internal server error 500.
This is where the onChange event is, triggering the AJAX functions:
<select required="true" id="oficinaLoc" name="oficinaLoc" onchange="getAgent(this.value); selClub(this.value)">
<option value="">Seleccione Unidad</option>
<option value="680 - Centro de Tecnología de Información">680 - Centro de Tecnología de Información</option>
<option value="681 - Educación Agrícola">681 - Educación Agrícola</option>
<option value="682 - Planificación y Evaluación">682 - Planificación y Evaluación</option>
<option value="683 - Medios Educativos e Información">683 - Medios Educativos e Información</option>
<option value="684 - Ciencias de la Familia y el Consumidor">684 - Ciencias de la Familia y el Consumidor</option>
etc...
These are my AJAX functions:
function getAgent(str) {
if (str == "") {
document.getElementById("dispAgente").innerHTML = "";
return;
} else {
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("dispAgente").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getagent.php?q="+str,true);
xmlhttp.send();
}
}
function selClub(unidad) {
if (unidad == "") {
document.getElementById("dispNombre").innerHTML = "";
return;
} else {
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("dispNombre").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getnombre.php?j="+unidad,true);
xmlhttp.send();
}
}
And these are the PHP pages it calls to through the XMLHttpRequest respectively:
getagent.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$q = ($_GET['q']);
$con = mysqli_connect('intrasise.uprm.edu','jchristian','registro4h','4h');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"4h");
$sql="SELECT nombre FROM personal4h WHERE unidadProg LIKE '%".$q."%'";
$result = mysqli_query($con,$sql);
echo '<select name="agenteExt"';
while($row = mysqli_fetch_array($result)) {
echo "<option value = " . $row['nombre'] . ">" . $row['nombre'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
getnombre.php
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
$j = ($_GET['j']);
$con = mysqli_connect('intrasise.uprm.edu','jchristian','registro4h','4h');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"4h");
$sql="SELECT nombreClub FROM club4h WHERE oficinaLoc LIKE '%".$j."%'";
$result = mysqli_query($con,$sql);
echo '<select name="nombreClub"';
while($row = mysqli_fetch_array($result)) {
echo "<option value = " . $row['nombreClub'] . ">" . $row['nombreClub'] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
The getAgent function doesn't return any options in the dropdownlist even though it creates the empty select. The selClub function gives me a 500 internal server error on the xmlhttp.open("GET","getagent.php?q="+str,true); line. I really don't know what else to do, I've followed every online article I've found about this to the dot.

A 500 error is a server error, so that means the problem will be in PHP and I'm seeing alot of issues there. I'm not sure that this is a complete list,...you'll need to debug it yourself, but here's a couple that aren't helping.
$j = ($_GET['j']);
$j = $_GET['j'];
//dump the ()
echo '<select name="nombreClub"';
echo '<select name="nombreClub">';
//closing > is missing
echo "<option value = " . $row['nombre'] . ">" . $row['nombre'] . "</option>";
echo "<option value=\"".$row['nombre']."\">".$row['nombre']."</option>";
//quotes around the value are missing
If you view the errors thrown by the PHP files, then you'll be on your way.
Good luck

Related

Send multiple variable with PHP AJAX GET onclick of a button

I have two dynamically loaded dropdowns: one containing golf course holes information and another holding users- together the information will be used to generate a scorecard.
When the course is selected and a user is selected I want to click a button and then this will generate the scorecard.
Below is the code for the 'course' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT courseID, name FROM courses";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$courses[] = '<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
}
?>
Below is the code for the 'user' dropdown
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT userID, forename, surname FROM user";
$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($result))
{
$users[] = '<option value="'.$row['userID'].'">'.$row['forename'].' '.$row['surname'].'</option>';
}
?>
Below is the HTML code for the dropdowns
<form>
<select id="selectCourse" onchange="showCourse(this.value)">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
At the moment I have code that uses the 'onchange' to load the first part of the scorecard which contains the hole information about that course. I am having problems changing this to the click of the button and also consider another variable from the user dropdown.
The below code is taken from W3Schools which loaded the hole information correctly based on 'onchange'.
<script>
function showCourse(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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;
}
}
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
xmlhttp.send();
}
}
</script>
The below code shows the first half of the scorecard being generated from the selection of the first dropdown.
<?php
$cValue = mysql_real_escape_string($_GET['cValue']);
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';
$con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT DISTINCT holeNumber, strokeIndex, par FROM holes WHERE courseID= '".$cValue."'";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));
echo '<div class="scorecardTable">
<table>
<tr>
<th>HoleNumber</th>
<th>Par</th>
<th>Stroke Index</th>
<th>Score</th>
<th>Points</th>
</tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['holeNumber'] . "</td>";
echo "<td>" . $row['par'] . "</td>";
echo "<td>" . $row['strokeIndex'] . "</td>";
echo "<td> <input required type=text /></td>";
echo "<td> </td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
</html>
What I am looking to know is can I pass two variables through at this point below:
xmlhttp.open("GET","generateSC.php?cValue="+str,true);
and if so how would I get the second variable.
EDIT
<script>
function showCourse(course, user) {
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
if (user || course == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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;
}
}
xmlhttp.open("GET","generateSC.php?course="+course+"&user="+user,true);
xmlhttp.send();
}
}
</script>
I've updated what I have above... the problem now is how do i get the button to work with the two variables?
<form>
<select id="selectCourse">
<option value = "">Select Course</option>
<?php foreach($courses as $c){
echo $c;
}?>
</select>
<select id="selectUser" >
<option value = "">Select User</option>
<?php foreach($users as $u){
echo $u;
} ?>
</select>
<button type="button" >Click me</button>
</form>
Just fetch the values from both dropdowns and concatinate the URL:
var user = document.getElementById('selectUser').value;
var course = document.getElementById('selectCourse').value;
xmlhttp.open("GET","generateSC.php?cValue="+course+"&user="+user,true);
Then your generateSC php script will of course have to fetch the value from the user parameter and work with that as well.
$_GET['user'] will fetch the value from the user parameter.

ReferenceError because of word

I need to write a word in database, and i cant couse i get an error that: ReferenceError: Patikrinta is not defined Here is my ajax script which sends data to php file. Bellow there is php script if you need it. Cant find solution in stackowerflow.
$s .= "\n\t<td>";
$canEdit = getPermission('tasks', 'edit', $a['task_id']);
$canViewLog = getPermission('task_log', 'view', $a['task_id']);
$currentTasken=$a['task_id'];
$currentUser=$AppUI->user_id;
$currentPercent="5";
$currentDescription="Patikrinta";
if ($canEdit) {
$s .= ("\n\t\t".'<a href="#">'
. "\n\t\t\t".'<img src="./images/icons/tick.png" alt="' . $AppUI->_('Check')
. '" border="0" width="12" height="12" onclick="javascript:insertData('. $currentTasken .', '.$currentUser.', '.$currentPercent.', '.$currentDescription.')" />' . "\n\t\t</a>");
}
$s .= "\n\t</td>";
?>
<script type="text/javascript">
// Note that you should use `json_encode` to make sure the data is escaped properly.
var currentTasken = <?php echo json_encode($currentTasken=$a['task_id']); ?>;
var currentUser = <?php echo json_encode($currentUser=$AppUI->user_id); ?>;
function insertData(currentTasken, currentUser, currentPercent, currentDescription)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","modules/tasks/datafile.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// Here, use the JS variables but, likewise, make sure they are escaped properly with `encodeURIComponent`
xmlhttp.send("currentUser=" + encodeURIComponent(currentUser) + "&currentTasken=" + encodeURIComponent(currentTasken) + "&currentPercent=" + encodeURIComponent(currentPercent)+ "&currentDescription=" + encodeURIComponent(currentDescription));
}
</script>
Here is my php script:
<?php
$currentUser = isset($_POST['currentUser']) ? $_POST['currentUser'] : '';
$currentTasken = isset($_POST['currentTasken']) ? $_POST['currentTasken'] : '';
$currentPercent = isset($_POST['currentPercent']) ? $_POST['currentPercent'] : '';
$currentDescription = isset($_POST['currentDescription']) ? $_POST['currentDescription'] : '';
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());
$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows >= 1)
{
//$pass = md5($pass);
$ins = mysql_query("INSERT INTO dotp_task_log (task_log_creator, task_log_Task, task_log_description) VALUES ('$currentUser' , '$currentTasken', '$currentDescription')" ) ;
if($ins)
{
$check = mysql_query("SELECT * FROM dotp_tasks");
$numrows = mysql_num_rows($check);
if($numrows > 1)
{
//$pass = md5($pass);
$inss = mysql_query("UPDATE dotp_tasks SET task_percent_complete = '$currentPercent' WHERE task_id='$currentTasken'") ;
if($inss)
{
die("Succesfully added Percent!");
}
else
{
die("GERROR");
}
}
else
{
die("Log already exists!");
}
}
else
{
die("ERROR");
}
}
else
{
die("Log already exists!");
}
?>
Have you tried adding quotes around the function arguments which are strings? JS is looking for a reference to 'Patikrinta' because you are not adding quotes around the string. It should be a bit more like this:
javascript:insertData('. $currentTasken .', '.$currentUser.', '.$currentPercent.', \''.$currentDescription.'\')" />' . "\n\t\t</a>");
The other arguments work because they are being passed as numbers and Javascript interprets them as such. The difference here is the value of $currentDescription is Patikrinta which is not a number and so JS looks for a variable or object called that.
As a side note - it's worth switching to use MySQLi if you can. MySQL_* functions are deprecated.

Can't get ajax working with PHP to load a table of info from MySQL

So basically I have a drop down list that displays data from a MySQL table(accounts) that would display user accounts. When the user selects one of the accounts I want it to display all facilities(facility table) that are owned by that account.
I have the drop down displaying the accounts, but it will not run the onChange() function to load my table. Here is everything I have, can someone tell me why my function is not getting triggered at all?
Index.php
<?php
require_once('sessionstart');
require_once('header.php');
require_once('dbconn.php');
//Accounts
require_once('getaccounts.php');
//Facility
echo "<div id='facilities'>";
require_once('getfacility.php');
echo "</div>";
?>
<?php
require_once 'footer.php';
?>
getaccounts.php
<?php
//require files
require_once('sessionstart.php');
require_once('dbconn.php');
//clear options variable
$options = "";
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT account_id, account_name FROM accounts";
$data = mysqli_query($dbc, $sql);
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
$options .="<option>" . $row['account_name'] . "</option>";
}
//account drop down form
$accountDropDown="<form id='account' name='account' method='post' action='getaccounts.php'>
<label>Accounts: </label>
<select name='account' id='account' onchange='showFacilities(this.value)'>
<option selected='selected' disabled='disabled' value=''>Select account</option>
" . $options . "
</select>
</form>";
//echo out account form
echo $accountDropDown;
?>
This works how I need it to and displays all accounts within the drop down. However I can't seem to get the showFacilities() function to work.
getfacility.php
<?php
require_once('dbconn.php');
$q = intval($_GET['q']);
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM facility "
. "INNER JOIN accounts ON accounts.account_id = facility.account_id "
. "WHERE facility.account_id = '".$q."'";
$data = mysqli_query($dbc, $sql);
echo "<table>
<tr>
<th>Facility Number</th>
<th>Facility Name</th>
<th>Facility Address</th>
<th>Facility City</th>
</tr>";
//loop through data and display all accounts
while ($row = mysqli_fetch_array($data)) {
echo "<tr>";
echo "<td>" . $row['facility_number'] . "</td>";
echo "<td>" . $row['facility_name'] . "</td>";
echo "<td>" . $row['facility_address'] . "</td>";
echo "<td>" . $row['facility_city'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
footer.php (includes showFacilities())
<script>
function showFacilities(account){
//I wrote this to test and see if this function was even being triggered.
document.alert("test");
if(account == ""){
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("facilities").innerHTML = xmlhttp.responseText;
}
}
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
}
</script>
<footer>
<p>Copyright &copy</p>
</footer>
</body>
</html>
Please tell me if I am doing this all wrong, am I laying everything out properly? Why is this function not being hit?
I have tried to a bunch of different things, and I just can't seem to get this to work, any help or advice or even a push in the proper direction will be very appreciated, thanks.
Your if else clauses don't add up (so your script is generating a script error, most likely a syntax error).
else{
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
This piece doesn't have an IF to accompany it.
This would be correct:
if(account == ""){
return;
}
else {
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("facilities").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getfacility.php?q="+account,true);
xmlhttp.send();
}
On a sidenote: Why create a form wrapper around your select (the one that where you can load accounts) when you use an onchange event to fire an XmlHTTPRequest?

Pagination in php. AJAX,PHP, MYSQL

I am creating a forum kind of a website, where I display posts dynamically using ajax. When the user logs in he finds a 'orderby' drop down select option, where he can choose the order of the posts.
select menu
<select name="orderby" id="orderby" onchange="showposts(this.value)" >
<option value="1" selected>By Time</option>
<option value="2">By Genuine Count</option>
<option value="3">By Dubious Count</option>
</select>
when the page is loaded window.onload function is called, which calls the 'showposts()' function to display the posts.
onload()
window.onload=function(){
showposts();
};
showposts() function
function showposts(str){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(str != undefined){
currentType=str; //save the current type for later use
document.getElementById("postsdiv").innerHTML = "";
}else{
var e = document.getElementById("orderby");
str = e.options[e.selectedIndex].value;
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// alert(xmlhttp.responseText);
document.getElementById("postsdiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","showposts.php?q="+str,true);
xmlhttp.send();
}
a part of showposts.php page which gets posts from database if the selected option is 1
if(intval($_GET['q'])==1){
while($row = $result->fetch_assoc()) {
echo "<div class='postclass'>";
echo "<span id='postspan".$row['id']."' name='postspan".$row['id']."' >";
echo "<span id='editspan".$row['id']."' name='editspan".$row['id']."' >";
echo "</br>";
echo "Posted By: &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <span class='bold'> ".$row['user']."</span>";
if($username==$row['user']){
echo "<a href='javascript:void(0);' onclick='deletepost(".$row['id'].")' >DELETE </a>&nbsp&nbsp&nbsp";
echo "<a href='javascript:void(0)'onclick='editpost(".$row['id'].",\"".$row['subject']."\",\"".$row['post']."\")' >EDIT </a></br>";
}else{
echo "</br>";
}
echo "<a id=".$row['id']."></a>";
echo "Date & Time: ".$row['date']."</br>";
echo "<span id=genuinecount".$row['id'].">Genuine Count: ".$row['genuine']."</span></br>";
echo "<span id=dubiouscount".$row['id'].">Dubious Count: ".$row['dubious']."</span>";
echo "</br>------------------------ </br>";
echo "Subject: <span class='bold' >".$row['subject']."</span></br>";
echo "Post: ";
echo "<div class='postbox' >&nbsp•&nbsp".$row['post'] . "</div><br /></br>";
}
}
So, my question is how to add pagination for this script? Can anyone help?
query
$sql = "SELECT * FROM posts order by date desc";
$result = $connection->query($sql);
showposts() function
function showposts(str, page, pagesize){
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(str != undefined){
currentType=str; //save the current type for later use
document.getElementById("postsdiv").innerHTML = "";
}else{
var e = document.getElementById("orderby");
str = e.options[e.selectedIndex].value;
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// alert(xmlhttp.responseText);
document.getElementById("postsdiv").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","showposts.php?q="+str+'&page='+page+'&pagesize='+pagesize,true);
xmlhttp.send();
}
query
$page = intval($_GET['page');
$pagesize = intval($_GET['pagesize']);
$sql = "SELECT * FROM posts order by date desc limit "
. ($page-1)*$pagesize . ", " . $pagesize;
Example link
Page 1, 20 per page

document.getElementById("elementname").innerHTML = selectText puts EVERY option value in my page

So I am using this code:
function updateSelect(a) {
$type = a;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest(); }
else {
xmlhttp=new ActiveXObject
("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","selectbox.php?type=".$type,false);
xmlhttp.send();
selectText=xmlhttp.responseText;
document.getElementById("cultpicklist").options.length=0;
document.getElementById("cultpicklist").innerHTML = selectText;
And for some reason it gives me EVERY option value on the entire page (I have several DISTINCT select boxes)! selectText only pulls from a small subset of the database (i.e. an entirely different table from where this data is coming from) - why would it be doing this?
Here's what is generated on selectbox.php:
<?php
include "mysql_config.php";
$con = mysql_connect($host, $user, $pass);
if (!$con)
{
die('Could not connect to the database, please contact administrator');
}
mysql_select_db($db);
while ($cultrow = mysql_fetch_array($rescult)) {
ECHO '<option name="culture[]" value="'. stripslashes($cultrow['cult_id']) .'">'. stripslashes($cultrow['cult_desc']) .'</option>';
}
?>

Categories