Following on from my question yesterday, I now have the code below somewhat successfully working. It allows me to change the first form item and submits it to 'process.php' in the background and turns the field green. However the trigger only works on the first form item, in this case "cstate". It doesn't trigger when "clocation" is changed. If you change clocation and then cstate then both form submit fine so it's simply that the .change function isn't triggering when clocation is changed. I'm not good enough at JS (total JS noob) to know why it isn't working so I'd appreciate any help you can give me.
Thanks!
$sql = "select * from `$table1`";
$result = mysql_query ($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$carid = $row["car_id"];
$carnum = $row["carnum"];
$carlocation = $row["carlocation"];
$carstate = $row["carstate"];
$formname = "#form".$carid;
print '<script type="text/javascript">';
print " var cnum;";
print " cnum = '$formname',";
print "
$('form').change(function()
{
console.log(cnum);
$.ajax({
type: 'post',
url: 'process.php',
data: $(this).serialize(),
success: function() {
}
});
return false;
});
</script>";
echo "<table>";
echo "<tr id='$carid'>";
echo "<td>$carnum</td>";
echo "<td><form action='' method='post' id='form$carid'>";
echo "<select id='popup' name='cstate'>";
echo "<option value='In-Service-Bay'>In Service Bay</option>";
echo "<option value='Awaiting-Service'>Awaiting Service</option>";
echo "<option value='Service-Complete'>Service Complete</option>";
echo "</select></td>";
echo "<select id='popup' name='clocation'>";
echo "<option value='Carpark-1'>Carpark-1</option>";
echo "<option value='Carpark-2'>Carpark-2</option>";
echo "<option value='Carpark-3'>Carpark-3</option>";
echo "</select></td>";
echo "</form></tr>";
}
echo "</table>";
Use .on() and wrap code inside document.ready.
$(document).ready(function(){
$('form').on('submit',function()
{
//code here
});
});
also put this code outside the while loop. Also form does not have change event try using .submit()
Solved it by using a separate form for each input selection. Works brilliantly now.
Thanks to all those that tried to help.
Adam
Related
I am creating a application that lets you design a meal and add or remove ingredients. However, the issue I am struggling with is $_POST data. The issue I am running into is I need a button for every $_POST data form submitted.
For example, I can use view meal button to list the ingredients (as seen in the picture), however since this action refreshes the page, the $_POST[meal] data is no longer there. So when I try to remove a ingredient, it can give me the selected ingredient but not the meals name.
What is the right way to get $_POST data? I am having to basically make a new form and button for every submission. Do I need to use some sort of AJAX so it doesn't necessarily refresh the page and I lose that data? Or do I need to use the $_GET method?
<?php
if (isset($_POST['view_meal'])){
$meal = (string)$_POST['meal_names'];
$meal_fk_q = "SELECT item
FROM meal_ingredients
WHERE meal_name='$meal'
ORDER BY item";
$meal_fk_c = $conn->query($meal_fk_q);
$option_string = "";
echo "<div class='view_meal_table_wrapper'>";
while ($row = $meal_fk_c->fetch_assoc()){
$view_ingredient = $row['item'];
echo "<table class='view_meal_table'>
<tr>
<td class='view_meal cell'>$view_ingredient</td>
</tr>
</table>";
$option_string .= "<option>" . $view_ingredient . "</option>";
}
echo "</div>";
echo "<form action='createmeal.php' method='post'>
<select name='remove_ingredients'>
<option disabled selected value> -- Remove Ingredient -- </option>";
echo $option_string;
echo "</select>
<input type='submit' name='remove_ingredient' value='Remove Ingredient'>";
}
if (isset($_POST['remove_ingredient'])){
$ingr = $_POST['remove_ingredients'];
$sql = "DELETE FROM meal_ingredients
WHERE item='$ingr'";
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully";
} else {
echo "Error deleting record: " . $conn->error;
}
}
?>
Ajax is the way forwards for you on this one. There are loads more you can add to it to improve, but the basics - using jQuery:
var variable-to-send = 42;
$.ajax ({
type: 'POST',
url: 'php_file_location.php',
data: {name-in-post: variable-to-send, more: more, andmore: andmore}
success: function (response) {
// handle the returned details here
console.log(response);
}
});
Then in php you'd do $data = $_POST ['name-in-post'];
Typed on mobile so apologies if any errors
I have a drop down list called courses. When the user chooses a course, I should show him information about the teacher that gives this course. So, on change I need to get the value selected, and show him the results generated from an sql query.
This is my php code:
$sql= "SELECT id, course_period_id from schedule WHERE STUDENT_ID='$_SESSION[student_id]'";
$result=mysql_query($sql);
$options="";
while ($row=mysql_fetch_array($result)) {
$id=$row["id"];
$course_period_id=$row["course_period_id"];
$course= DBGet(DBQuery("SELECT title FROM course_periods WHERE course_period_id='$course_period_id'"));
$options.="<OPTION VALUE=\"$course[1]['TITLE']\">".$course[1]['TITLE'].'</option>';
}
echo '</TD></TR></TABLE>';
echo "<SELECT>
<OPTION VALUE=0>Choose
$options
</SELECT>";
echo '</TD></TR></TABLE>';
I want to use "href", as I created a php file "teachers_info.php" with the following code:
if(!empty($_GET['Course']))
{
$sql="SELECT teacher_id FROM course_periods where title= '$course'";
$teacher_id= DBGet(DBQuery($sql));
$result= DBGet(DBQyery(" SELECT first_name, last_name, phone, email FROM staff WHERE staff_id = '$teacher_id[1]['teacher_id']'"));
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Phone</th>
<th>E-mail</th>
</tr>";
echo "<tr>";
echo "<td>" . $result[1]['first_name'] . "</td>";
echo "<td>" . $result[1]['last_name'] . "</td>";
echo "<td>" . $result[1]['phone'] . "</td>";
echo "<td>" . $result[1]['email'] . "</td>";
echo "</tr>";
echo "</table>";
}
How can I do this?
Thanks :)
Ok this is a bad approach, for multiple reasons:
This should be done using ajax
Don't use $_SESSION for this
I'll help you out. The first thing you need is jquery. You can find it here: http://jquery.com .
Next take a look at this picture to understand how ajax works:
In short, ajax is used to make calls to the server and update the page with the response without reloading. In your case, you will make a call to the server, send course and receive the results.
Once you have jquery set up, you have to write this:
$(function(){
$("select").on("change", function(){
var value = $(this).value(); //get the selected id
$.get("requesturl.php", {course: value}, function(){
// do something with the response
}, "json");
})
})
The requesturl.php file would look as follows:
$course = $_GET["course"]
if($course){
//execute Database query and store it in $result
echo json_encode($result);
}
you can modify this code.
myform.php
<script type="text/javascript">
$(document).ready(function(){
//Below line will get value of Category and store in id
$("#Category").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "GET",
url: "Ajax_SubCategory.php",
data: dataString,
cache: false,
success: function(html)
{
//This will get values from Ajax_SubCategory.php and show in Subcategory Select option
$("#SubCategory").html(html);
}
});
});
});
</script>
<form>
<?php
mysql_connect("localhost","root","") or die("error connect");
mysql_select_db("test") or die(" error database");
echo "<select name='Category' id='Category'>";
echo "<option value='' disabled='' selected='' >--Select Category--</option>";
$q6=mysql_query("select DISTINCT Category from category");
while($r6=mysql_fetch_array($q6))
{
echo "<option value='$r6[0]' >$r6[0]</option>";
}
echo "</select>";
echo "<select name='SubCategory' id='SubCategory'>";
echo "<option value='' disabled='' selected='' >--Select Sub Category--</option>";
echo "</select>";
?>
</form>
Ajax_SubCategory.php
<?php
mysql_connect("localhost","root","") or die("error connect");
mysql_select_db("test") or die("error database");
if($_GET['id'])
{
$id=$_GET['id'];
$sql=mysql_query("select SubCategory from category where Category='$id'");
while($row=mysql_fetch_array($sql))
{
$data=$row['SubCategory'];
echo '<option value="'.$data.'">'.$data.'</option>';
//echo "<input type='checkbox' value='".$data."' >".$data.;
}
}
?>
Well if you want the PHP to get something you ned to post something. You either add a submit button or:
echo "<select name=\"course\" id=\"course\" onchange=\"this.form.submit()\">
<OPTION VALUE=0>Choose
$options
</SELECT>";
Then you can utilize if(!empty($_GET['Course'])) {
because $_GET[] need the form to be submited.
I am displaying some data from my database, and I wnat to be able to put checkboxes next to each record displayed.
Afther that I want the user to be able to submit their selection and that will then delete the selected records.
I googled a lot of things, but could not make anything work. I'm looking for smething simple.
Here is my code:
<?php
//include('conn.php');
$con=mysqli_connect();
session_start();
if (!isset($_SESSION['ID'])){
header('location:login.php');
}
//
?>
<?php
if (!$link = mysql_connect()) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db()) {
echo 'Could not select database';
exit;
}
$villageId = $_GET['village'];
$ID = $_SESSION['ID'];
$sql ="SELECT *
FROM favourites
INNER JOIN attractions ON favourites.AttractionID = attractions.AttractionID
INNER JOIN customer ON favourites.ID = customer.ID
WHERE favourites.ID = '$ID' ";
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the database\n";
echo 'MySQL Error: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo $row['Name'] ;
}
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
Can anyone give me some suggestions?
Thanks.
Simple add checkbox near data output:
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' /> ".$row['Name'];
}
As I understand you need this:
Output some rows data - checkbox
User will select some checkboxes and data, connected with that checkboxes will be deleted from the database.
Delete deleted data from the page.
How to achieve this?
You need html code below to ahieve what you want (+ you need some javascript, I will tell about it later):
<form id='myForm'>
<div id='1'>
<input type='checkbox' name='data[]' value='1' />Row 1</div>
<div id='2'>
<input type='checkbox' name='data[]' value='2' />Row 1</div>
<div id='3'>
<input type='checkbox' name='data[]' value='3' />Row 1</div>
</form>
Look the example of that code + serialize form on link onclick handler here.
Generate same output in PHP:
// execute query
echo "<form id='myForm'>";
while ($row = mysql_fetch_assoc($result)) {
echo "<div id='".$row['id']."'><input type='checkbox' value='".$row['id']."' /> ".$row['Name']." </div>";
}
echo "<a href='#' id='delete'>Delete</a>";
echo "</form>";
So, now we made 1st item of our list and half of 2nd (serialize form).
How to achieve another half of 2nd item. We have to create php script where we will delete rows from the database.
deleteScript.php script:
// connect to the base
foreach($id in $_POST['data']) {
$query = "delete from `favourites` where `id` = ".$id;
// execute your query
}
Script ready. Now you have to send request from our page to this script. Use ajax request for it:
$("#delete").on('click', function () {
var data = $("#myForm").serialize();
if(data != '') {
$.ajax({
url: "deleteScript.php",
data: data
});
}
else
{
alert("select some checkboxes");
}
});
This javascript code works with previous html code
Example here.
Now, 1st and 2nd items of our list done.
Let's delete deleted items from our page immidiately (3rd item of todo list):
$("input:checkbox:checked").each(function()
{
var id = $(this).val();
$("div#"+id).remove();
});
You can test this code here
That example was created to show you, that my approach works. But! You have to remove div's only if request had been sent successfully. So you have to edit $.ajax success handler. Check this fiddle for it.
So, now we made all items from our list.
Final example here: http://jsfiddle.net/575VS/18/
You have to copy past it just to your files :)
Hope, this will help.
Note, that you can get ajax-request response.
$.ajax({
//some properties
success: function(data) {
//response will be in data variable
}
});
If you want to redirect page right after deleting selected rows in database use this code:
if(data != '') {
$.ajax({
url: "deleteScript.php",
data: data,
success: function() {
window.location.replace("new link here");
}
});
}
Just to expand on Sharikov's answer: You need to place the checkbox in the loop as he described, but if you want to be able to pass that info to another script, that works on the user input you need several more things:
echo "<form action='receiver.php' method='post'>";
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' name='checkedBoxes[]'/> ".$row['Name'];
}
echo "<input type='submit' value='process'>";
echo "</form>";
Then on receiver.php:
foreach($_POST['checkedBoxes'] as $box){
$id = $box;
//THEN DO SOMETHING TO EACH ID
}
If you also want to see which boxes were unchecked, then things get a little more complicated because POST and GET will only pass the values of checked check-boxes. and there are several ways I can think of to do this. One way would be to pass an array of the all ids displayed via a $_SESSION variable to the next script:
session_start();
$ids = new Array();
echo "<form action='receiver.php' method='post'>";
while ($row = mysql_fetch_assoc($result)) {
echo " <input type='checkbox' value='".$row['id']."' name='checkedBoxes[]'/> ".$row['Name'];
array_push($ids, $row['id'];
}
$_SESSION['ids'] = $ids;
echo "<input type='submit' value='process'>";
echo "</form>";
And then on receiver.php you can reference that array with $_SESSION['ids'] and compare it to the values that were checked. Just make sure you place session_start(); in your code to be able to see the variable!
Good Luck!
I'm designing this code and it doesn't work. Can anyone help me?
The jQuery:
$('.cuttingCheckbox').change(function() {
if (this.checked) {
$.post(
'process_class.php',
{
headmark : $($row[HEAD_MARK]).val(),
headmark_id : $($row[ID]).val()
},
function(response){
this.setAttribute("disabled", true), alert(headmark, headmark_id);
}
);
}
});
and the code,
$sql = "SELECT * FROM FABRICATION WHERE FABRICATION.HEAD_MARK = '{$_POST["hm"]}'";
$query = oci_parse($conn, $sql);
$query_exec = oci_execute($query);
while($row = oci_fetch_assoc($query)) {
echo "<table border='1'>";
echo '<table cellspacing = "0"';
echo '<thead>';
echo '<tr><th>Head Mark/ID</th>
<th>Cutting</th>
</tr></thead>';
echo "<tbody>";
echo "<tr><td><b>$row[HEAD_MARK]/$row[ID]</b></td>";
if ($row['CUTTING'] == 'Y') {
//echo "<td><input type='checkbox' id='cuttingCheckbox' name='cuttingCheckbox' checked='checked' disabled='disabled'/></td>";
echo "<td><img src='../images/fabDone.png' width='30' height='30'></td>";
} else {
echo "<td><input type='checkbox' class='cuttingCheckbox' name='cuttingCheckbox'/></td>";
}
echo "</tr>";
echo "</tbody>";
echo "<table cellspacing = '0'";
}
echo "</table>";
And the process_class.php just processing $row[HEAD_MARK] and $row[ID] passed to update the database. I don't know how to pass the $row[HEAD_MARK] and $row[ID] into the jQuery. Please help me
Your problem might be in this jquery statement
{ headmark : $($row[HEAD_MARK]).val(),
headmark_id : $($row[ID]).val()
}
can you please explain which value you are trying to get from HTML dom tree using jquery.
since you have to either use # if field from which you want get value using jquery has id attribute with same name.
so try like below:
{ headmark : $('#<?php echo $row[HEAD_MARK]?>').val(),
headmark_id : $('#<?php echo $row[ID]?>').val()
}
if field is identified by id.
Edit:
change your PHP code line to look like this:
echo "<td><input type='checkbox' data-headmark=".$row['HEAD_MARK']." data-id=".$row['ID']." class='cuttingCheckbox' name='cuttingCheckbox'/></td>";
And:
change your jQuery code line to look like this:
{ headmark : $(this).data('headmark'),
headmark_id : $(this).data('id')
}
Also:
make sure that in process_class.php script update Query should have quote around head_mark if it is varchar type like below:
"UPDATE FABRICATION_QC SET CUTTING = 'Y'
WHERE HEAD_MARK = '".$_POST["headmark"]."' AND ID = ".$_POST["headmark_id"].";"
Now apply this three changes and try again.
SCROLL TO FIND WORKING CODE
I am working on a AJAX editing platform, and I am having trouble with setting up the text field for editing.
My code so far:
The Javascript below handles the initial submission:
<head>
<script type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();
function edit()
{
var doc_id = document.getElementById("doc_id").value;
ajax.open('GET', 'ajax.php?doc_id='+doc_id, true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
document.getElementById('content').innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
</script>
</head>
The SQL below handles the initial select query and display of that information:
$query = 'SELECT pp.`physician_id`, pp.`physician_first_name`, pp.`physician_last_name`, pp.`featured`, ';
$query.= 'FROM `primary_physicians` AS pp ';
$query.= 'ORDER BY pp.`physician_id` ';
<body>
<div id="container">
<?php
$result = mysql_unbuffered_query( $query );
echo "<table border='1'>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
$physician_id = $row['physician_id'];
echo "<td>" . $row['physician_id'] . "</td>";
echo "<td><div id='content'><input id='doc_id' type='hidden' value='$physician_id' />" . $row['physician_first_name'] . "<br /><input type='button' value='Edit' onclick='edit();'></div></td>";
echo "<td>" . $row['physician_last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</div>
</body>
</html>
And the 'ajax.php' file handles the request when the user clicks the 'Edit' button within the 'content' div.
$client_id = $_GET['doc_id'];
$client_query = 'SELECT pp.`physician_id`, pp.`physician_first_name`, pp.`physician_last_name`, pp.`featured` ';
$client_query.= 'FROM `primary_physicians` AS pp WHERE pp.`physician_id`=' . $client_id . '';
$client_result = mysql_unbuffered_query( $client_query );
while ($client_row = mysql_fetch_assoc($client_result))
{
echo "<input type='text' value='$client_row[physician_first_name]' />";
}
What shows is below:
Initial page load:
Pressing the 'edit' button (any of the available buttons, not just the one associated with the client/ID):
Pressing any edit button shows client ID #2 within client ID #1's table row (not in the row with client ID #2):
I'm guessing I have to set up something within the content div and somehow associate it with the 'edit()' function, however I can't figure out how to do that without setting the script within the while loop (which I really don't want to do).
WORKING CODE BELOW
Javascript (initial submission and display):
<head>
<script type="text/javascript">
if(window.ActiveXObject) var ajax = new ActiveXObject('Microsoft.XMLHTTP');
else var ajax = new XMLHttpRequest();
function hello(e)
{
/* this was once document.getElementById("doc_id").value;*/
var doc_id = e.currentTarget.id;
ajax.open('GET', 'ajax.php?doc_id='+doc_id, true);
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
/*this was without the '+doc_id' document.getElementById('content').innerHTML = ajax.responseText; */
document.getElementById('content'+doc_id).innerHTML = ajax.responseText;
}
}
ajax.send(null);
}
</script>
</head>
PHP/MySQL:
<body>
<div id="container">
<?php
$result = mysql_unbuffered_query( $query );
echo "<table border='1'>";
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>";
$physician_id = $row['physician_id'];
echo "<td>" . $row['physician_id'] . "</td>";
//note change to the 'content' div (addition of $physician_id to make it truly unique; this ties into the javascript above.
echo "<td><div id='content$physician_id'>";
//note changes to input id and button id, as well as the 'onclick' function.
echo "<input id='doc_id_$physician_id' type='hidden' value='$physician_id' />" . $row['physician_first_name'] . "<br /><input type='button' id='$physician_id' value='Edit' onclick='hello(event);'></div></td>";
echo "<td>" . $row['physician_last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
</div>
</body>
No changes to or initial MySQL query or to ajax.php
There is a problem with the elements' ids. Remeber that the id attribute should be unique inside a document. You are using the same id for numerous elements:
td><div id='content'><input id='doc_id' type='hidden' ...
inside a loop.
Then you use the Javascript document.getElementById('doc_id'). JS supposes there is only one element with this id on the page so it will always return the first element it finds.
EDIT:
You will have to also change your JS function to retrieve the proper value:
for the edit buttons use: onclick="edit(event)"
And then in the JS:
function edit(e) {
buttonId = e.currentTarget.id;
//use the button id to find the proper value
}
Of course you will have to set the id on the "edit" buttons and have it correspond with id of you inputs. E.g. use $i for the button id and doc_id_$i for the input id.
I also recommend having a look at jQuery, as it will help facilitate many of the things you're trying to achieve here.