Code works on localhost, but not on live server - javascript

I've been working on some code and tested it on localhost, code is work on local server but when i Upload it to my server it doesn't work.
Index.php
<form action="" method="post" id="teachome">
<label>
Category</label**strong text**>
<select id="listt" type="text" name="nam" style="width:188px;" required>
<?php
$data1 = mysqli_query($con,"SELECT * FROM admin_cat");
echo "<option value=>--select--</option>";
while($rows = mysqli_fetch_array($data1)){?>
<option value="<?php echo $rows['cat']; ?>"><?php echo $rows['cat']; ?></option>
<?php } ?>
</select>
<label>Class</label>
<select id="cat" type="text" name="cls" style="width:188px;" required>
<option value="">--Select--</option>
</select>
</form>
<!--Ajax -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#listt").change(function() {
var data = $("#teachome").serialize();
//alert(data);
$.ajax({
type: 'POST',
url: 'fetch.php',
data: data,
datatype: 'json',
success: function(data) {
var obj = jQuery.parseJSON(data);
$('#cat').empty();
$.each(obj, function(index, value) {
$("#cat").append("<option>" + value.class + "</option>");
});
}
});
});
});
</script>
Fetch.php
<?php
$cat=$_POST['nam'];
$sql= mysqli_query($con,"select * from admin_class where category='$cat'")or die(mysqli_error());
$result = mysqli_fetch_all($sql, MYSQLI_BOTH);
echo json_encode($result);
?>
Internal Error 500 is occurred in Response on live server.

Related

AJAX form with e.preventDefault(); redirects to the PHP file

When I click the button to submit the form it sends me to the PHP file (Php/modify-recipes.php). I'm using AJAX with e.preventDefault();, but it doesn't seem to work. I have a similar form on my other page and it works fine. This one is a little bit different, the form is generated from another PHP file (it takes values from the database).
// AJAX (in HTML head tag)
<script>
$(function () {
$("#search-form").on('click', 'p.product', function(e){
var product = $(this).attr('id');
e.preventDefault();
$.ajax({
type: "post",
url: 'Php/display-modify-recipes.php',
data: { "id": product },
success: function(response) {
$(".modify-recipes").html(response);
$(".search-results").html("");
}
});
}
)});
$(function () {
$('#add_recipes_form').on('click', '#add', function (e) {
e.preventDefault();
let sendForm = true;
$('.required').each(function(){
if ($(this).val() == ''){
$(this).addClass('error', 4000);
$('#placeholder-text').html("Fill in the form");
$('#placeholder-text').addClass('error');
$('#add').addClass('error', 4000);
sendForm = false;
} else {
$(this).removeClass('error');
$('#placeholder-text').removeClass('error');
$('#add').removeClass('error');
}
})
$('.required2').each(function(){
if ($(this).val() == ''){
$('#placeholder-text').html("Fill in the form");
$('#placeholder-text').addClass('error');
$('#add').addClass('error');
$('#file_style').addClass('error');
sendForm = false;
} else {
$('#file_style').removeClass('error');
$('#placeholder-text').removeClass('error');
$('#add').removeClass('error');
}
})
if (sendForm) {
$.ajax({
type: "post",
url: 'Php/modify-recipes.php',
data: new FormData(this),
processData: false,
contentType: false,
success: function () {
},
error: function () {
}
});
}
});
});
</script>
// HTML
<form method="POST" enctype='multipart/form-data' id="search-form" class="aaa">
<input type="text" name="search-bar" class="search-bar" placeholder="Search">
<div class="search-results"></div>
</form>
<div class="modify-recipes"></div>
// Php/display-modify-recipes.php
<?php
function display_mod_form(){
$con = mysqli_connect("localhost", "root", "", "cookbook");
$product = $_POST["id"];
$sql = "SELECT * FROM product WHERE id = '$product'";
$res = mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($res)) {
$id = $row['id'];
$name = $row['name'];
$description = $row['description'];
$type = $row['type'];
$difficulty = $row['difficulty'];
$image = $row['image'];
?>
<form method="POST" action="Php/modify-recipes.php" enctype="multipart/form-data" id="add_recipes_form" class="add-form">
<input type="text" name="id" id="<?php echo $id ?>" value="<?php echo $id ?>" style="display:none;">
<label for="name">Name</label>
<input type="text" name="name" id="name" class="required" maxlength="28" value='<?php echo $name ?>'>
<label for="description">Desc.</label>
<input type="text" name="description" id="description" class="required" maxlength="128" value='<?php echo $description ?>'>
<label for="type">Type</label>
<select name="type" class="required">
<option value="dishes" <?php if($type == 'dishes') {echo "selected=selected"; } ?>>
Dishes
</option>
<option value="desserts" <?php if($type == 'desserts') {echo "selected=selected"; } ?>>
Desserts
</option>
<option value="snacks" <?php if($type == 'snacks') {echo "selected=selected"; } ?>>
Snacks
</option>
<option value="other" <?php if($type == 'other') {echo "selected=selected"; } ?>>
Other
</option>
</select>
<label for="difficulty">Difficulty</label>
<select name="difficulty" class="required">
<option value="easy" <?php if($difficulty == 'easy') {echo "selected=selected"; } ?>>
Ease
</option>
<option value="moderate" <?php if($difficulty == 'moderate') {echo "selected=selected"; } ?>>
Moderate
</option>
<option value="hard" <?php if($difficulty == 'hard') {echo "selected=selected"; } ?>>
Hard
</option>
</select>
<label for="image">Image (jpg, png)</label>
<label for="upload_image" id="file_style">Choose image</label>
<input type="file" style="display:none;" id="upload_image" name="image" accept="image/*" onchange="loadFile(event)" class="required2">
<div class="send-btn">
<p id="placeholder-text"></p>
<input type="submit" name="add" id="add" value="Send">
<div class="send-block"></div>
</div>
</form>
<?php
}
mysqli_close($con);
}
display_mod_form();
?>
// Php/modify-recipes.php
<?php
$con = mysqli_connect("localhost", "root", "", "cookbook");
$id = $_POST["id"];
$name = $_POST["name"];
$description = $_POST["description"];
$type = $_POST["type"];
$difficulty = $_POST["difficulty"];
if ($_FILES['image']['name'] == ""){
$sql_var = "SELECT image FROM product where id = '$id'";
$var = mysqli_query($con,$sql_var);
while($row = mysqli_fetch_assoc($var)) {
$image = $row['image'];
}
} else {
$image = $_FILES['image']['name'];
}
$sql = "
UPDATE product SET
name = '$name',
description = '$description',
type = '$type',
difficulty = '$difficulty',
image = '$image',
last_mod_date = '$mod_date'
WHERE id = '$id';
";
$target = "../Uploads/".basename($image);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
}
$var = mysqli_multi_query($con,$sql); <!-- There are more queries -->
mysqli_close($con);
?>
(Sorry for any mistakes, it's a shortened version)
There is a third ajax function and PHP file, but it's not important (simple search bar). I tried other things like action="", no action at all, etc., but it didn't work.
How to fix this?
Edit: There is only one form (when you click on p.product it displays the form according to the data in the database). The problem occurs ONLY when I'm submitting the "add_recipes_form", there is no problem with the search box. Please don't mark this question as a duplicate of a 10 year old post that is irrelevant to my problem.

Variable sent with AJAX is undefined in PHP

I'm trying to send a variable from Javascript to PHP using AJAX.
The HTML (index.html):
<div class="table-popup">
<ul>
<li id="edit-toggle">Bearbeiten</li>
<li>Zu Favoriten hinzufügen</li>
<li>Datei öffnen</li>
<li>Im Ordner öffnen</li>
<li>Löschen</li>
</ul>
</div>
<div class="main-content">
<h2 class="main-content-header">Datenbank</h2>
<div id="table">
<table>
<thead>
<tr class="table-row" tabindex="1">
<th class="fixed-header"></th>
<th>Dateiname</th>
<th>Benutzer</th>
<th>Erstelldatum</th>
<th>Änderungsdatum</th>
<th>Erste Zeile</th>
<th>Kategorie</th>
<th>Projekt</th>
</tr>
</thead>
<?php
include_once('connect.php');
$result = $connect->query("SELECT file.name AS 'filename', file.description AS 'filedescription', category.name AS 'categoryname', project.name AS 'projectname', user.name AS 'username', idFile
FROM file, category, project, file_has_project, file_has_category, user, user_has_project, user_has_category
WHERE file.idFile = file_has_project.file_idFile AND file_has_project.project_idProject = project.idProject AND file.idFile = file_has_category.file_idFile AND file_has_category.category_idCategory = category.idCategory AND user.idUser = user_has_project.user_idUser AND user_has_project.project_idProject = project.idProject AND user.idUser = user_has_category.user_idUser AND user_has_category.category_idCategory = category.idCategory AND user.idUser = '".$_SESSION['userid']."'");
//echo "<tbody><td>".$result->num_rows."</td></tbody>";
if ($result->num_rows > 0) {
echo "<tbody>";
while($row = $result->fetch_assoc()) {
echo "<tr class='table-row' tabindex='1' id='".$row['idFile']."'>";
echo "<th class='table-edit-button fixed-header'><img src='images/open.gif' /></th>";
echo "<td>".$row['filename']."</td>";
echo "<td>".$row['username']."</td>";
echo "<td>-</td>";
echo "<td>-</td>";
echo "<td>".$row['filedescription']."</td>";
echo "<td>".$row['categoryname']."</td>";
echo "<td>".$row['projectname']."</td>";
echo "</tr>";
}
echo "</tbody>";
}
?>
</table>
</div>
</div>
The Javascript which is sending the AJAX request with jQuery (functions.js):
$(document).ready(function() {
var fileID;
$('.table-edit-button').click(function() {
fileID = $(this).parent().attr('id');
});
$('#edit-toggle').click(function() {
$.ajax({
url: 'edit.php',
type: 'post',
data: { fileID : fileID },
success: function(data) {
alert("Success");
}
});
});
});
The PHP file (edit.php):
<?php
if (isset($_POST['fileID']))
$fileID = $_POST['fileID'];
?>
<div class="edit-content">
<h2 class="edit-content-header">Bearbeiten<img src="images/cross.gif" /></h2>
<div>
<form action="" method="post">
<?php echo $fileID; ?>
<input type="text" placeholder="Dateiname"/>
<input type="text" placeholder="Benutzer"/>
<textarea placeholder="Erste Zeile" rows="7em" cols="100"></textarea>
<select name="Kategorie">
<option disabled selected>Kategorie</option>
<?php
include_once('connect.php');
$result = $connect->query("SELECT name FROM category");
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['name']."'>".$row['name']."</option>";
}
}
?>
</select>
<select name="Projekt">
<option disabled selected>Projekt</option>
<?php
$result = $connect->query("SELECT name FROM project");
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['name']."'>".$row['name']."</option>";
}
}
?>
</select>
<img id="savebtn" src="images/save.gif" />
</form>
</div>
</div>
The HTML displays data from a database in a table and each row has a button next to it. With jQuery I get the id of the row where the button has been clicked. I want to send this id to my php file to do some stuff there (irrelevant for now).
The problem I'm having is that I can't access the send variable (fileID) in my edit.php file.
The alert in the success part of the AJAX call gets executed.
What do I need to fix? I thought I had everything right.
I also tried to change the url of the AJAX call to ../edit.php but that didn't work either. Then the success part wouldn't be executed.
And different variable names didn't work either.
The project structure is as follows:
project (*)
edit.php
index.php
scripts (*)
functions.js
(*) directories
Edit:
The error message: Notice: Undefined variable: fileID in C:\xampp\htdocs\kuhlnotesweb\edit.php on line 10
AJAX returns the content of the page in the data success variable. Trying console.log(data) and you should see you variable has been echoing into the returned HTML.
If not, check in the dev tools that the fileID parameter is actually attached to the request.
UPDATE
<div class="edit-content">
<h2 class="edit-content-header">Bearbeiten<img src="images/cross.gif" /></h2>
<div>
<form action="" method="post">
<?php
if (isset($_POST['fileID'])) {
echo $_POST['fileID'];
}
?>
<input type="text" placeholder="Dateiname"/>
<input type="text" placeholder="Benutzer"/>
<textarea placeholder="Erste Zeile" rows="7em" cols="100"></textarea>
<select name="Kategorie">
<option disabled selected>Kategorie</option>
<?php
include_once('connect.php');
$result = $connect->query("SELECT name FROM category");
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['name']."'>".$row['name']."</option>";
}
}
?>
</select>
<select name="Projekt">
<option disabled selected>Projekt</option>
<?php
$result = $connect->query("SELECT name FROM project");
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['name']."'>".$row['name']."</option>";
}
}
?>
</select>
<img id="savebtn" src="images/save.gif" />
</form>
</div>
</div>
The problem is a syntax error in your js when you try to pass data
your code. see js fiddle example http://jsfiddle.net/mdamia/njd8m0g5/4/. how to get the value from the tr.
data: ({ fileID : fileID }),
should be data:
{ fileID : fileID } // no ()
Tested and it works.
from jQuery AJAX
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
This is my solution now:
functions.js:
$(document).ready(function() {
var fileID, fileName, fileDescription, fileCategory, fileProject;
$('.table-edit-button').click(function() {
fileID = $(this).parent().attr('id');
});
$('#edit-toggle').click(function() {
$.ajax({
url: 'ajax-edit.php',
type: 'post',
data: { fileID : fileID },
dataType: 'json',
success: function(data) {
fileName = data.filename;
fileDescription = data.filedescription;
fileCategory = data.categoryname;
fileProject = data.projectname;
$('#edit-fileid').val(fileID);
$('#edit-filename').val(fileName);
$('#edit-description').val(fileDescription);
$('#edit-projectname').val(fileProject);
$('#edit-categoryname').val(fileCategory);
}
});
});
});
ajax-edit.php:
<?php
if (isset($_POST['fileID'])) $fileID = $_POST['fileID'];
include_once('connect.php');
$result = $connect->query("SELECT file.name AS 'filename', file.description AS 'filedescription', project.name AS 'projectname', category.name AS 'categoryname'
FROM file, project, category, file_has_project, file_has_category
WHERE file.idFile = file_has_project.file_idFile AND file_has_project.project_idProject = project.idProject AND file.idFile = file_has_category.file_idFile AND file_has_category.category_idCategory = category.idCategory AND file.idFile = '".$fileID."'");
$result = $result->fetch_assoc();
echo json_encode($result);
?>
edit.php:
<div class="edit-content">
<h2 class="edit-content-header">Bearbeiten<img src="images/cross.gif" /></h2>
<div>
<form action="edit.php" method="post">
<input type="hidden" id="edit-fileid" name="edit-fileid"/>
<input type="text" id="edit-filename" name="edit-filename" placeholder="Dateiname"/>
<input type="text" id="edit-username" name="edit-username" placeholder="Benutzer"/>
<textarea id="edit-description" name="edit-description" placeholder="Erste Zeile" rows="7em" cols="100"></textarea>
<select id="edit-categoryname" name="edit-categoryname">
<option disabled selected value="category-first">Kategorie</option>
<?php
include_once('connect.php');
$result = $connect->query("SELECT category.name FROM category,user,user_has_category WHERE user.idUser = user_has_category.user_idUser AND user_has_category.category_idCategory = category.idCategory AND user.idUser = '".$_SESSION['userid']."'");
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['name']."'>".$row['name']."</option>";
}
}
?>
</select>
<select id="edit-projectname" name="edit-projectname">
<option disabled selected value="project-first">Projekt</option>
<?php
$result = $connect->query("SELECT project.name FROM project,user,user_has_project WHERE user.idUser = user_has_project.user_idUser AND user_has_project.project_idProject = project.idProject AND user.idUser = '".$_SESSION['userid']."'");
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<option value='".$row['name']."'>".$row['name']."</option>";
}
}
?>
</select>
<input type="image" name="submit-button" id="savebtn" src="images/save.gif" />
</form>
</div>
</div>
I think there were many misunderstanding in what I was trying to achieve and how I was not able to understand how AJAX works exactly. edit.php is only a small part of HTML that gets included in index.php and the AJAX call I'm making gets made in the same file, so I was not able to use the variable I sent via AJAX in my edit.php file because at the point where I wanted to use it it wasn't even sent and thus the $_POST['fileID'] was undefined.
My solution to this was that I created a seperate php file (ajax-edit.php) where I retrieve the information I need from the database and return it as a JSON object. With this I am able to use the information from the JSON object to change the value of the input fields.
Thank you for the help everybody and I am sorry that I was so stubborn ^^.

Query MySQL database using value from a dropdown, then populate a text field with the result without refreshing the page

I have a dropdown in a form that is being populated with a list of employees from a table called 'employees' in a MySQL database (employee_id, fname, lname). This is working just fine.
What I need to do next is when an employee is selected from the dropdown, I need to query the employees table to get the employees commission percentage (commission) and then populate another text field in the form with that value.
The issue is that i need to do this without reloading the page. I have been searching Google and it looks like i need to use AJAX and JavaScript. to accomplish this, my problem is that I don't know a thing about AJAX, though i do have some experience with java script.
The employees table looks like this:
employee_id
fname
lname
commission
Below is what I have so far.
<?php
// DB connection
require_once('Connections/freight.php');
// get employee list for dropdown
$query_rsEmployeeList = "SELECT employee_id, fname, lname FROM employees ORDER BY fname ASC";
$rsEmployeeList = mysqli_query($con, $query_rsEmployeeList) or die(mysqli_error($con));
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
$totalRows_rsEmployeeList = mysqli_num_rows($rsEmployeeList);
?>
<html>
<head>
<title>demo</title>
</head>
<body>
<form id="frmAddAgents" name="frmAddAgents" method="post" action="">
Agent:
<select name="employee_id" id="employee_id">
<option selected="selected" value="">- select agent -</option>
<?php do { ?>
<option value="<?php echo $row_rsEmployeeList['employee_id']?>"><?php echo $row_rsEmployeeList['fname']?> <?php echo $row_rsEmployeeList['lname']?></option>
<?php
} while ($row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList));
$rows = mysqli_num_rows($rsEmployeeList);
if($rows > 0) {
mysqli_data_seek($rsEmployeeList, 0);
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
}
?>
</select>
Commision:
<input name="commission" type="text" id="commission" size="3" />
<input type="submit" name="button" id="button" value="Add Agent To Load" />
</form>
</body>
</html>
<?php
mysqli_free_result($rsEmployeeList);
?>
OK, I looked at the other question and although it is different, I tried to change the code around to make it work, but i'm not having any luck. When I select an item from the dropdown, nothing happens. Below is the updated code. I'm not sure if i'm on the right path or not.
<?php
// DB connection
require_once('Connections/freight.php');
// get employee list for dropdown
$query_rsEmployeeList = "SELECT employee_id, fname, lname FROM employees ORDER BY fname ASC";
$rsEmployeeList = mysqli_query($con, $query_rsEmployeeList) or die(mysqli_error($con));
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
$totalRows_rsEmployeeList = mysqli_num_rows($rsEmployeeList);
?>
<html>
<head>
<title>demo</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function() {
$("#employee_id").change(function () {
var employee_id = $(this).val();
$.ajax({
type: "GET",
url: "ajax.php",
data: {employee_id: employee_id},
dataType: "json",
success: function(data){
var comm = data[0].commission;
$('#commission').empty();
$('#commission').append('<option value="0">0.00</option>');
$('#commission').append('<option value="' + comm + '">' + comm + '</option>');
$('#commission').focus();
},
beforeSend: function(){
$('#commission').empty();
$('#commission').append('<option value="0">Loading...</option>');
},
error: function(){
$('#commission').empty();
$('#commission').append('<option value="0.00">0.00</option>');
}
})
});
});
</script>
</head>
<body>
<form id="frmAddAgents" name="frmAddAgents" method="post" action="">
Agent:
<select name="employee_id" id="employee_id">
<option selected="selected" value="">- select agent -</option>
<?php do { ?>
<option value="<?php echo $row_rsEmployeeList['employee_id']?>"><?php echo $row_rsEmployeeList['fname']?> <?php echo $row_rsEmployeeList['lname']?></option>
<?php
} while ($row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList));
$rows = mysqli_num_rows($rsEmployeeList);
if($rows > 0) {
mysqli_data_seek($rsEmployeeList, 0);
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
}
?>
</select>
Commision:
<input name="commission" type="text" id="commission" size="3" />%
<input type="submit" name="button" id="button" value="Add Agent To Load" />
</form>
</body>
</html>
<?php
mysqli_free_result($rsEmployeeList);
?>
Here is the test2.php file that ajax is using to query the database
<?php
// DB connection
require_once('Connections/freight.php');
if (isset($_GET['employee_id'])) {
$employee_id = $_GET['employee_id'];
$return_arr = array();
$result = $con->query ("SELECT commission FROM employees WHERE employee_id = $employee_id");
while($row = $result->fetch_assoc()) {
$row_array = array("commission" => $row['commission']);
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
}
?>
I figured it out. Here is the final code.
test.php
<?php
// DB connection
require_once('Connections/freight.php');
// get employee list for dropdown
$query_rsEmployeeList = "SELECT employee_id, fname, lname FROM employees ORDER BY fname ASC";
$rsEmployeeList = mysqli_query($con, $query_rsEmployeeList) or die(mysqli_error($con));
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
$totalRows_rsEmployeeList = mysqli_num_rows($rsEmployeeList);
?>
<html>
<head>
<title>demo</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function() {
$("#employee_id").change(function () {
var employee_id = $(this).val();
$.ajax({
type: "GET",
url: "ajax.php",
data: {employee_id: employee_id},
dataType: "json",
success: function(data){
var comm = data[0].commission;
$('#commission').empty();
$('#commission').val(comm);
$('#commission').focus();
},
beforeSend: function(){
$('#commission').empty();
$('#commission').val('0.00');
},
error: function(){
$('#commission').empty();
$('#commission').val('0.00');
}
})
});
});
</script>
</head>
<body>
<form id="frmAddAgents" name="frmAddAgents" method="post" action="">
Agent:
<select name="employee_id" id="employee_id">
<option selected="selected" value="">- select agent -</option>
<?php do { ?>
<option value="<?php echo $row_rsEmployeeList['employee_id']?>"><?php echo $row_rsEmployeeList['fname']?> <?php echo $row_rsEmployeeList['lname']?></option>
<?php
} while ($row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList));
$rows = mysqli_num_rows($rsEmployeeList);
if($rows > 0) {
mysqli_data_seek($rsEmployeeList, 0);
$row_rsEmployeeList = mysqli_fetch_assoc($rsEmployeeList);
}
?>
</select>
Commision:
<input name="commission" type="text" id="commission" size="3" />%
<input type="submit" name="button" id="button" value="Add Agent To Load" />
</form>
</body>
</html>
<?php
mysqli_free_result($rsEmployeeList);
?>
ajax.php
<?php
// DB connection
require_once('Connections/freight.php');
if (isset($_GET['employee_id'])) {
$employee_id = $_GET['employee_id'];
$return_arr = array();
$result = $con->query ("SELECT commission FROM employees WHERE employee_id = $employee_id");
while($row = $result->fetch_assoc()) {
$row_array = array("commission" => $row['commission']);
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
}
?>

Dependent dropdowns not working, 2nd dropdown not loading

I need help with this one, i dont know why the sub cat wont load. but the first dropdown loads all the queries. i just dont know why it wont work with the 2nd one.
here is my index.php
<?php
include('config.php');
$query_parent = mysql_query("SELECT * FROM zipcodes GROUP BY major_area") or die("Query failed: ".mysql_error());
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dependent DropDown List</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#parent_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
$.get('loadsubcat.php?parent_cat=' + $(this).val(), function(data) {
$("#sub_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
</script>
</head>
<body>
<form method="get">
<label for="category">Parent Category</label>
<select name="parent_cat" id="parent_cat">
<?php while($row = mysql_fetch_array($query_parent)): ?>
<option value="<?php echo $row['major_area']; ?>"><?php echo $row['major_area']; ?></option>
<?php endwhile; ?>
</select>
<br/><br/>
<label>Sub Category</label>
<select name="sub_cat" id="sub_cat"></select>
</form>
</body>
</html>
and here is my loadsubcat.php
<?php
include('config.php');
$parent_cat = $_GET['parent_cat'];
$query = mysql_query("SELECT city FROM zipcodes WHERE major_area = {$parent_cat}") or die(mysql_error());
while($row = mysql_fetch_array($query)) {
echo "<option value='$row[city]'>$row[city]</option>";
}
?>
please check my codes, and tell me where i did it wrong. it wont load for the 2nd drop down.
Try doing a simple AJAX function:
<script type="text/javascript">
function AjaxCall(ElemVal,PlaceId) {
$.ajax({
url: "loadsubcat.php?parent_cat="+$(ElemVal).val(),
success: function(result) {
$("#"+ PlaceId).html(result);
}
});
}
$(document).ready(function() {
$("#parent_cat").change(function() {
$("#sub-cat-load").html('<div id="loader"><img src="img/loading.gif" alt="loading subcategory" /></div>');
AjaxCall(this,'sub-cat-load');
});
});
</script>
sub_cat container
<label>Sub Category</label>
<!-- NOTICE THIS PART -->
<div id="sub-cat-load"></div>
loadsubcat.php
<?php
include('config.php');
// You may want to sanitize this variable
$parent_cat = $_GET['parent_cat'];
$query = mysql_query("SELECT city FROM zipcodes WHERE major_area = {$parent_cat}") or die(mysql_error()); ?>
<select name="sub_cat" id="sub_cat"><?php
while($row = mysql_fetch_array($query)) { ?>
<option value="<?php echo $row[city]; ?>"><?php echo $row[city]; ?></option><?php
} ?>
</select>

add and retrieve record from mysql using ajax

As shown from the diagram, I have two tables in my mysql and I would like the system to add and retrieve comment without refreshing the page.
I have three php pages involved in this function and they are 'DB.php', 'comment.php' and 'action.php'
The codes are as shown:
DB.php
<?php
$conn = mysql_connect('localhost','Practical4','1234') or die (mysql_error);
$db=mysql_select_db('Practical4', $conn) or die (mysql_error);
?>
comment.php
<----------------ajax script-------------------->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<-----retrieve hotel id from hotel table-------->
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<---------------post form------------------->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string(trim($_POST['content']));
$name=mysql_real_escape_string(trim($_POST['name']));
mysql_query("insert into comment(content,name) values ('$content','$name')");
$fetch= mysql_query("SELECT content FROM comment order by commentID desc where name = '$name'");
$row=mysql_fetch_array($fetch);
}
?>
<div class="showbox"> <?php echo $row['content']; ?> </div>
when I run this, the page display nothing when I insert the comment, can anyone help me to solve this? Thanks a lot!!
Some changes have been made as follows:
comment.php
<!-- ajax script -->
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = 'content='+ textcontent + '&name='+name;
if(textcontent=='')
{
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: true,
success: function(html){
$("#show").after(html);
document.getElementById('content').value='';
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<!-- retrieve hotel id from hotel table -->
<?php
include('DB.php');
$id=$_GET['id'];
$query = mysql_query("select * from hotel where name='$id'");
while($rows=mysql_fetch_array($query)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<!-- post form -->
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="submit" value="Post" name="submit" class="submit_button"/>
</form>
</div>
<div class="space"></div>
<div id="flash"></div>
<div id="show"></div>
action.php
<?php
include('DB.php');
$check = mysql_query("SELECT * FROM comment order by commentID desc");
if(isset($_POST['content']))
{
$content=$_POST['content'];
$name=$_POST['name'];
mysql_query("insert into comment (content,name) values ('$content','$name')");
echo '<div class="showbox">'.$content.'</div>';
}
?>
Reasons why your code failed:
name not added in dataString causing name not sent in post
some mysql errors

Categories