I made a star rating system for a school project and need some help improving it a bit. It's a fairly simple setup: index.php contains list-items (content is fetched from a DB) with an image and a div holding the stars for rating. Each star is a link that triggers a function which saves the rating in a database.
Here's the link! for starters.
If you click on any star, the first click will result in a green check mark on the first list-item. The idea is that this check mark will appear on each list-item when rated. That's where I need you guys to point me in the right direction. First of all I know I can't echo out multiple divs with the same id, but I had to in order for the ajax function to work (document.getElementById("rated")). Any ideas on how to solve this?
CODE
insert_receive.php:
<?php
session_start();
$sess = session_id();
$mysqli = new mysqli("", "", "", "");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $mysqli->prepare("REPLACE INTO Ratings (projId_fkey, sessionId, rvalue) VALUES ('".$_GET['projId']."','".$sess."','".$_GET['rating']."')");
$stmt->execute();
printf("✔");
?>
ajax_framework.js:
function saveClick(rating,projId)
{
var xmlhttp;
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("rated").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","insert_receive.php?rating=" + rating + "&projId=" + projId,true);
xmlhttp.send("");
}
index.php: (the part that matters)
<?php
$select = "SELECT id, projName, location FROM Projects";
if($result = $mysqli->query($select))
{
while($row = $result->fetch_assoc())
{
echo '<li id="'.$row['id'].'">';
echo '<h1 class="header">'.$row['projName']."</h1>";
echo '<img src="'.$row['location'].'" alt=""/>';
echo '<div class="rating">';
echo ''.★★★★★."";
echo ''.★★★★."";
echo ''.★★★."";
echo ''.★★."";
echo ''.★."";
echo '<div id="rated">'.""."</div>";
echo "</div>";
echo "</li>";
}
}
?>
You can use an iterator to give each element a different ID, after that, you can indeed dynamically get the element by the correct ID. For example:
echo '<div id="rated'.$row['id'].'">
and then:
document.getElementById("rated"+projId).innerHTML=xmlhttp.responseText;
This will dynamically select the element you want.
Regarding your code in general, I simply must point you in the direction of http://jquery.com/
It will make element selection much simpler, and will also normalize your use of ajax.
Change your php to:
while($row = $result->fetch_assoc())
{
echo '<li id="'.$row['id'].'">';
echo '<h1 class="header">'.$row['projName']."</h1>";
echo '<img src="'.$row['location'].'" alt=""/>';
echo '<div class="rating">';
echo ''.★★★★★."";
echo ''.★★★★."";
echo ''.★★★."";
echo ''.★★."";
echo ''.★."";
echo '<div id="rated'.$row['id'].'">'.""."</div>";//updated this line
echo "</div>";
echo "</li>";
}
And the line in your javascript to:
document.getElementById("rated"+projId).innerHTML=xmlhttp.responseText;
Use a counter$id to increment li id
<?php
$select = "SELECT id, projName, location FROM Projects";
if($result = $mysqli->query($select))
{
$id = 0;
while($row = $result->fetch_assoc())
{
echo '<li id="'.$id.'">';
echo '<h1 class="header">'.$row['projName']."</h1>";
echo '<img src="'.$row['location'].'" alt=""/>';
echo '<div class="rating">';
echo ''.★★★★★."";
echo ''.★★★★."";
echo ''.★★★."";
echo ''.★★."";
echo ''.★."";
echo '<div id="rated">'.""."</div>";
echo "</div>";
echo "</li>";
$id++;
}
}
?>
First, use a class instead, obviously.
echo '<div class="rated">'.""."</div>";
Second, in your JavaScript, instead of this line
document.getElementById("rated").innerHTML=xmlhttp.responseText;
Use this
var proj = document.getElementById(projId);
var rated = proj.getElementsByClassName('rated')[0];
rated.innerHTML=xmlhttp.responseText;
What we're doing here is that we find the element with an id matching projId. Then we find the elements with the class rated INSIDE the projID we found earlier. Now notice that getElementsByClassName returns an array regardless of the number of elements, but since we only have a single one here we just select the item at the first index [0].
Related
The code is supposed to fetch the query result and display it according to the number written in the text box, i tried (onkeydown and onkeyup) and both didn't work, i have no idea why it is not working and what is my mistake.
HTML code:
<script>
function showRoom(rid) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "getRoomAJAX.php?q="+rid, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
}
</script>
<form>
<input type="text" name="rid" onkeydown="showRoom(this.value)">
</form>
<div id="txtHint">Room...</div>
getRoomAJAX.php code:
<?php
session_start();
ob_start();
$q = $_GET["q"];
$db = new Database();
$dbc = $db->getConnection();
if (!$dbc) {
die('Could not connect: ' . mysql_error());
}
$query = "SELECT * FROM indvProj_room WHERE rid = '".$q."'";
$result = mysqli_query($dbc, $query);
//start creating the table HTML
if ($result) {
echo "<table border='1' align='center' cellspacing = '2' cellpadding = '4' width='100%'>
<tr>
<th><b>Room ID</b></th>
<th><b>Room Description</b></th>
</tr>";
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo "<tr>";;
echo "<td>" . $_SESSION['adminRoomChoice'] = $row['rid'] . "</td>";
echo "<td>" . $row['roomDesc'] . "</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo '<p class="error">Sorry, cannot find the room, are you sure of the entered Room ID?</p>';
echo '<p class = "error">' . mysqli_error($dbc) . '</p>';
}
?>
Does showRoom() get called at all? Put a console.log(rid); inside showRoom() to see if that is getting called and whether the value is being passed in correctly.
If you can determine that it's getting into the showRoom(), then follow the code down and into PHP to see where it's failing. Echo some sample text at the top of the PHP file with return; right below it. That will tell you if the error is in the XMLHttpRequest code or somewhere in the PHP file.
Normally, I don't pass any variables/params with onkeydown type of events. Usually, I call a method like this without params and then retrieve the value based on the element's id. See this answer for more detail on that: https://stackoverflow.com/a/54040431/3103434
I have a table for a sports day where there are 4 columns name, house, event, result. I have no problem creating and displaying the database but i want to be able to search in a bar and to use AJAX to automatically search all 4 columns for whats in the search bar. I am using PHPmyadmin to store the database with mySQLI. i am able to display the database on the page that i want. I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search. I have never used Ajax before so sorry for my bad code as it is all from w3schools site. the DB is called sports_day and the table is called full_results. here is my current code.
<script>
function showUser(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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","results_query.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
and on a page called results_query.php is this code
<body>
<?php
$q = intval($_GET['q']);
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql="SELECT * FROM full_results WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</body>
at the moment what happens is none of the table is shown and when i type anything in the search box the whole table appears along with in plain text at the bottom the title and all the contents of the table in a long line.
any suggestion to get my code to work would be greatly appreciated!
thanks!
The solution would be like this:
Keep your HTML search form as it is.
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
... I also want when the page starts for the whole table to be displayed and then when you start typing it just removes any items that do not match the search.
See this <div> section here,
<div class="col-sm-12">
...
</div>
You didn't put anything in this <div> section. First of all, you have to display your entire table in this section, which you can later filter out using the AJAX request. Also, assign an id to this <div> section so that it could be easier for you put the AJAX response in this <div> section. So the code for this <div> section would be like this:
<div class="col-sm-12" id="pupil-info">
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
</div>
Change your Javascript/AJAX code in the following way,
<script>
function showUser(str){
var str = str.trim();
var xmlhttp;
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("pupil-info").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","results_query.php?q="+encodeURIComponent(str),true);
xmlhttp.send();
}
</script>
Please note that you should encode the user inputted str value using encodeURIComponent() function before passing it to the results_query.php page.
Finally, on results_query.php page process your AJAX request like this:
<?php
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = "SELECT * FROM full_results";
if(isset($_GET['q']) && !empty($_GET['q'])){
$sql .= " WHERE CONCAT(id, NAME, HOUSE, EVENT, RESULT) LIKE '%".$_GET['q']."%'";
}
$result = mysqli_query($con,$sql);
echo '<table>';
echo '<tr>';
echo '<th>NAME</th>';
echo '<th>HOUSE</th>';
echo '<th>EVENT</th>';
echo '<th>RESULT</th>';
echo ' </tr>';
if(mysqli_num_rows($result)){
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['HOUSE'] . "</td>";
echo "<td>" . $row['EVENT'] . "</td>";
echo "<td>" . $row['RESULT'] . "</td>";
echo "</tr>";
}
}else{
echo "<tr>";
echo "<td colspan='4' style='text-align:center;'>No records found</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Sidenote: Learn about prepared statement because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.
If you use your 'results_query.php' file only for getting the data from database, then you don't need to create a <body> tag. If you use only PHP then you can easily skip any plane HTML. That's just a digression :)
But to the point.
You can change the way you return your data from database. I think, instead of doing a lot of echo's it is better to add result to the variable and echoing the variable at the end.
$data = '<tr>' . '<th>NAME</th>' . '<th>HOUSE</th>' . '<th>EVENT</th>' . '<th>RESULT</th>' . '</tr>';
while($row = mysqli_fetch_array($result)) {
$data .= '<tr>';
$data .= '<td>' . $row['NAME'] . '</td>';
$data .= '<td>' . $row['HOUSE'] . '</td>';
$data .= '<td>' . $row['EVENT'] . '</td>';
$data .= '<td>' . $row['RESULT'] . '</td>';
$data .= '</tr>';
}
$data .= '</table>';
mysqli_close($con);
echo $data;
See if this changes something.
What about showing entire table after the page's loaded, you will have to change both PHP and JavaScript code a little bit.
You can change your JS so it gets everything from your full_results table after page is loaded.
There are several ways to do this and you can read about them here:
pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
The easiest way would be to do this this way:
<script>
function showUser(str) {
var url;
var xmlhttp;
if (str == "") { //if empty string - get all data
url = "results_query.php";
} else { //get particular data otherwise
url = "results_query.php?q="+str;
}
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
<form>
search for pupil
<input type="text" size="30" name="user" onkeyup="showUser(this.value)">
<div id="livesearch"></div>
<br>
</form>
<div class="col-sm-12">
<div id="txtHint"><b> pupil's info will be listed here</b></div>
</div>
<script>
//calling your function with empty string because we want to get all data
showUser("");
</script>
and in the PHP file you can do something like this:
<?php
$q = 0;
//check if 'q' parameter was passed
if(isset($_GET['q'])) {
$q = intval($_GET['q']);
}
$con = mysqli_connect("localhost","root","","sports_day");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"sports_day");
$sql = ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results";
Now your JavaScript function will be called after loading your page.
It will call your PHP script with AJAX and this script should return all data from your table.
In line ($q) ? "SELECT * FROM full_results WHERE id = '".$q."'" : "SELECT * FROM full_results"; there is a simple check if $q is different from 0. Our variable will be set to 0 if no argument was passed, so whenever $q is equal to '0', we just want to get all the data from full_results and specific data otherwise.
I also added var xmlhttp because it is only local variable.
You can read more about that in here:
https://stackoverflow.com/a/1471738/7301294
I hope it will help you.
Let me know if you have any other problems and never be afraid to ask.
Good luck!
I'm trying to retrieve data from multiple table. So when the user clicks and select an item php file to retrieve the data from the corresponding table.
this is my first try on Ajax used w3 school code and trying to modify, I guess the way I'm using if condition is the problem? Before I try with the multiple table it worked.
My Script
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "Please Select type of users to view";
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","get_users.php?q="+str,true);
xmlhttp.send();
}
}
</script>
My Form
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Staff</option>
<option value="2">Admin</option>
<option value="3">Customers</option>
</select>
</form>
My PHP Page
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','X','X','X');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con);
if ($q='Admin')
{
$sql="SELECT * FROM admin";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>Email</th>
<th>Name</th>
<th>Mobile</th>
<th>Address</th>
<th>Password</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['mobile'] . "</td>";
echo "<td>" . $row['address'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
}
echo "</table>";
else if ($q='Staff')
{
echo "This is from Database B
}
else
{
echo "This is from database C";
}
mysqli_close($con);
?>
You're using $q = intval($_GET['q']); with a string value for your assignments.
intval() "Get the integer value of a variable"
<option value="1">Staff</option>
<option value="2">Admin</option>
<option value="3">Customers</option>
and using an assignment rather than a comparison for both if ($q='Admin') and else if ($q='Staff') both being strings, as opposed to integers in your options.
which should read as and with 2 equal signs if ($q=='2') and else if ($q=='1') in order to match your select's numerical value options.
Or, change them accordingly with your options to read as Staff and Admin (and Customers) in the values, while removing the intval() from the GET array; the choice is yours.
You also don't need mysqli_select_db($con); since you've declared your 4 parameters in your initial connection and would fail for another reason; technically you didn't select a database for it.
You're also missing a quote and semi-colon in (a parse syntax error)
echo "This is from Database B
which should read as
echo "This is from Database B";
Footnotes:
The page which I believe you based yourself on, seems to be http://www.w3schools.com/php/php_ajax_database.asp
If so, then I suggest you follow their example completely and modify it slowly to fit your needs. I myself have used that demo (in the distant past) before with success.
Their example uses a WHERE clause also.
$sql="SELECT * FROM user WHERE id = '".$q."'";
Edit: Just for the record, there is a missing brace for this condition:
if ($q='Admin')
{
So I have two drop-down lists Category and Sub-category. Sub-category has to be populated by an SQL query once a Category is selected.
I know how to populate from an SQL query:
<?php
mysql_connect('localhost', 'user', 'pw');
mysql_select_db('db');
$sql = "SELECT col FROM table";
$result = mysql_query($sql);
echo "<select name='col'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col'] . "'>" . $row['col'] . "</option>";
}
echo "</select>";
?>
But I don't know how to run the query and update list in jQuery:
function updateList(){
//QUERY&fill based on selection//
.val($('select[name="category"] option:selected').val());
}
I spent an hour or so on google and couldn't manage to solve this.
you have to create onchange function in selecting main category and pass it to either jquery or javascript ajax request response to get value from another file having subcategory output with sql where condition as main category value.
echo "<select name='col' onchange='loadXMLDoc()'>";
the above of main cat drop down and its ajax javascript reqest response whould be as below
<script>
function loadXMLDoc()
var maincat=document.getElementByName("col").val();
{
var xmlhttp;
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","demo_post2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("maincat_var=maincat");
}
Create a div with id as myDiv in your main page.
and the other page should have
<?php
mysql_connect('localhost', 'user', 'pw');
mysql_select_db('db');
$sql = "SELECT col FROM table where main_cat=$_POST['maincat_var']";
$result = mysql_query($sql);
echo "<select name='col2'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col'] . "'>" . $row['col'] . "</option>";
}
echo "</select>";
?>
You can try using jquery and ajax to load values of subcategory .
Try modifying and using the below code. This code may guide you..
$(document).ready(function(){
$('#submit').click(function() {
$.ajax(
{
url:"subcat.php?id='something'", // Here you can write php variableto pass to next page
success:function(result){
$("#div1").html(result);
}
});
return false;
});
});
onclicking the main category some page will be executed and its output will be displayed in a html element.
Sorry for not stated my problem. Actually I want to update my data in database.
But the problem now is even i tried to choose approve or reject the ajax still won't update.
I am new in ajax and try search around net but my code still got problem
here is my php page
<?php
$querysel = "SELECT * FROM tblinternapplication WHERE course_code = '{$course_codeapp}' ORDER BY student_id, 1 DESC " ;
$resultsel = mysql_query($querysel, $connection);
echo "<h2><div class=\"h_title\">Status still in pending</div></h2>";
echo "<table>";
echo "<thead>";
echo "<tr>";
echo "<th scope=\"col\">Matric ID</th>";
echo "<th scope=\"col\">Company name</th>";
echo "<th scope=\"col\" width = \"200\">Job Scope</th>";
echo "<th scope=\"col\">Status</th>";
echo "<th scope=\"col\">Action</th>";
echo "</tr>";
echo "</thead>";
while($rowsel = mysql_fetch_array($resultsel)){
if($rowsel['status_approval'] == NULL){
$id = $rowsel['id'];
echo "<tr>";
echo "<tr>"."<td class=\"align-center\">".$rowsel['student_id']."</td>";
echo "<td class=\"align-center\">".$rowsel['company_name']."</td>";
echo "<td class=\"align-center\" width = \"200\">".$rowsel['job_scope']."</td>";
echo "<td class=\"align-center\">";
if($rowsel['status_approval'] != NULL){
if( $rowsel['status_approval'] == 0)
{
echo "Reject";
}
else
{
echo "Approve";
}
}
else
{ echo "Pending";
}
echo "</td>";
echo "<td class=\"align-center\"><select name=\"approve\"
onchange=\"getstatus(this.value)\">";
echo "<option value=\"\">Select status:</option>";
echo "<option value=\"1\">Approve</option>";
echo "<option value=\"0\">Reject</option>";
echo "</select>";
echo "</td>";
echo "</tr>";
}
}
echo "</table>";
here is my jscript page
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function getstatus(id, approve)
{
if (approve=="")
{
}
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("GET","updatestatus.php?id=" + id + "&status=" + approve,true);
xmlhttp.send();
}
</script>
then here is my updatestatus.php
<?php require_once("../includes/session.php"); ?>
<?php require_once("sessioncourse.php"); ?>
<?php $course_codeapp = $_SESSION['course_code'] ; ?>
<?php confirm_logged_in(); ?>
<?php require_once("../includes/connection.php") ?>
<?php require_once("../includes/functions.php") ?>
<?php
$id = $_GET['id'];
$status =$_GET['status'];
$sql="UPDATE tblinternapplication set status_approval = $status WHERE id = $id ";
$result = mysql_query($sql);
?>
I work for few days but problem still cannot solve. Hope someone can help me. I will appreciate your help!
For preapre result for JS in php use json_encode() function. Make your update script somthing like this:
<?php require_once("../includes/session.php");
require_once("sessioncourse.php");
$course_codeapp = $_SESSION['course_code'] ;
confirm_logged_in();
require_once("../includes/connection.php");
require_once("../includes/functions.php");
$id = $_GET['id'];
$status =$_GET['status'];
$sql="UPDATE tblinternapplication set status_approval = $status WHERE id = $id ";
$result = mysql_query($sql);
$json = array();
while ($row = mysql_fetch_assoc($result)) {
$json[] = $row;
}
echo json_encode($json);
IMPORTANT
Dont close php tag or you may add extra space chars
AJAX
In your case using jQuery ajax was good practic. Mkae you code like this:
<script type="text/javascript">
function getstatus(id, approve)
{
$.ajax({
'url': 'updatestatus.php',
'data': {"id": id, "status": approve},
'success': function (response) {
console.log(response);
//TODO: use server response
}
});
}
</script>
echo "<td class=\"align-center\"><select name=\"approve\"
onchange=\"getstatus(this.value)\">";
In that line above, you are passing only one value. At the same time your JS function waits for 2 parameters. Currently, you have id always equal to 0 or 1 and status is always undefined.
Suppose you just need to change that line like:
echo "<td class=\"align-center\"><select name=\"approve\"
onchange=\"getstatus("+ $id +", this.value)\">";
One note:
$sql="UPDATE tblinternapplication set status_approval = $status WHERE id = $id ";
Except that you should not use mysql_* functions anymore, code above is opened to sql injections. To avoid sql injections with mysql_ extension you should do something like this:
$sql="UPDATE tblinternapplication set status_approval = ".mysql_real_escape_string($status) ." WHERE id = " .mysql_real_escape_string($id);
See docs for mysql_real_escape_string here. Also, read a warning message on that page - it tells you what you should use in replacement for mysql extension
I would suggest to use the developer tools like F12 in IE or chrome or the fiddler to check the request you are sending to the PHP code . In case you are getting any error you can easily see in the response