Depending on the value in the mysql database I would like a checkbox to be either checked or unchecked. Although the ajax query is getting the correct value the checkbox always remains checked
The Jquery
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "ajax/get_db_settings.php",
dataType: "json",
data: 'user='+1,
success:function(response){
var taken_by_on = response.taken_by;
alert(taken_by_on);
if(taken_by_on = 0){
$('.taken_by_input').attr('disabled',true).css('color','#F0F0F0');
$('#taken_by_enable').prop('checked', false);
}else if(taken_by_on = 1){
$('.taken_by_input').attr('disabled',false).css('color','#000');
$('#taken_by_enable').prop('checked', true);
}
},error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
</script>
get_db_settings.php
$user_id = $_POST['user'];
$sql = "SELECT * FROM user WHERE userID = $user_id";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
if($result){
$row = mysqli_fetch_array($result);
$taken_by_on = $row['takenByOn'];
$output_array = array(
'taken_by' => $taken_by_on
);
}
echo json_encode($output_array);
The html
<form name="add_positioning" class="postable" id="add_positioning">
<table border="0" class="autoTable_pos">
<tr>
<td colspan="2" style="text-align:left">Enable <input style="width:10px"
type="checkbox" name="taken_by" id="taken_by_enable">
</td>
</tr>
<?
$sql= "SELECT * FROM gradeReason WHERE reason_userID = $id AND category = 'positioning' AND current = 1 ORDER BY reasonID";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($result)){?>
<tr>
<td>
<input type="text" class="taken_by_input outline ie7_td"
name="reason[][<? echo $row['reasonID']; ?>]" value="<? echo $row['reason_name']; ?>"/>
</td>
<td><input type="button" name="delete_pos" value=""
class="taken_by_input delRow_pos del_reason_btn del_taken_in"
onClick="UpdateRecord(<? echo $row['reasonID']; ?>);"/>
</td>
</tr>
<?
}
?>
</table>
</form>
The plan is that if the value in the database is 1 the checkbox is checked and the inputs in the table are enabled whereas they would be disabled and the checkbox would remain unchecked if the value was 0.
I am using an array to pass back the values from the Ajax because I intend to add more to it once I have this working
In the if condition, you need to use == not =, = is the assignment operator, you need the equals operator which is ==
if (taken_by_on == 0) {
$('.taken_by_input').attr('disabled', true).css('color', '#F0F0F0');
$('#taken_by_enable').prop('checked', false);
} else if (taken_by_on == 1) {
$('.taken_by_input').attr('disabled', false).css('color', '#000');
$('#taken_by_enable').prop('checked', true);
}
Related
I have a html table that is created using AJAX and within that table I would like to submit some input values into a MySQL database, also using AJAX. The catch is that I need only the input from one row to be submitted.
The script below is what was used to generate the html table from the php server side php:
if (isset($_GET['query'])) {
$id = $_GET['query'];
$query = "SELECT * FROM samples_database WHERE sample_id=$id;";
$result = mysqli_query($connect, $query);
$input = mysqli_fetch_array($result);
$input1 = $input['micro_analysis'];
$order_id = $input['order_id'];
$rows = explode(',', $input1);
if (count($rows) > 0 ) {
$output .= '<thead>
<tr>
<th>result_id</th>
<th>m_analysis_id</th>
<th>order_id</th>
<th>sample_id</th>
<th>Tests</th>
<th>Detected</th>
<th>Result</th>
<th>Comments</th>
<th colspan="1"></th>
</tr>
</thead>
<tbody>';
foreach ($rows as $row){
$query2 = "SELECT * FROM microbiology_analysis_database WHERE id=$row";
$result2 = mysqli_query($connect, $query2);
$input2 = mysqli_fetch_array($result2);
$analysis = $input2['m_analysis'];
$query3 = "SELECT * FROM results_database WHERE m_analysis_id=$row AND order_id=$order_id AND sample_id=$id";
$result3 = mysqli_query($connect, $query3);
$input3 = mysqli_fetch_array($result3);
$result_id = $input3['id'];
$result = $input3['result'];
$output .=
'<tr>
<td><input name="result_id" id="result_id" value="'.$result_id.'" readonly></td>
<td><input name="m_analysis_id" id="m_analysis_id" value="'.$row.'" readonly></td>
<td><input name="order_id" id="order_id" value="'.$order_id.'" readonly></td>
<td><input name="sample_id" id="sample_id" value="'.$id.'" readonly></td>
<td>'.$analysis.'</td>
<td><input name="detected" class="result_input" type="text" id="detected"></td>
<td><input name="result" class="result_input" type="text" id="result" value="'.$result.'"></td>
<td><input name="comment" class="result_input" type="text" id="comment"></td>
<td><input type="submit" id="submit" value="Submit"></td>
</tr>';
}
$output .= '</tbody>';
}
echo $output;
And here is the AJAX script to allow for the creation of the table:
$(document).ready(function(){
$('.get_result').click(function (event)
{
event.preventDefault();
var url = $(this).attr('href');
$.get(url, function(data) {
$('#tests').html(data);
});
});
});
Up until this point the script works perfectly, but it is with the submission of inputs from this table that I get some wonky results. I would only submit the last row of inputs and would generate a whole lot of empty entries into the MySQL database. Also, instead of staying on the page, it redirects to a empty white page.
Here is the script for the form submission:
function formSubmit(){
$.ajax({
type: 'POST',
url: '../server/insert_tests.php',
data: $('#frmBox').sterialize(),
success: function(response){
$('#success').html(response);
}
});
var form = document.getElementById('frmBox').reset();
return false;
}
As well as the php script for database entries:
$result_id =test_input($_POST['result_id']);
$order_id = test_input($_POST['order_id']);
$sample_id = test_input($_POST['sample_id']);
$detected = test_input($_POST['detected']);
$result = test_input($_POST['result']);
$m_analysis_id = test_input($_POST['m_analysis_id']);
if ($result_id == '') {
$sql = "INSERT INTO results_database (order_id, sample_id, detected, result, m_analysis_id) VALUES ('$order_id', '$sample_id', '$detected', '$result', '$m_analysis_id');";
mysqli_query($connect, $sql);
} else {
$sql = "UPDATE results_database SET order_id='$order_id', sample_id='$sample_id', detected='$detected', result='$result', m_analysis_id='$m_analysis_id' WHERE id='$result_id';";
mysqli_query($connect, $sql);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
This is where the html table will be created within the html script:
<h3 id="success"></h3>
<div class="result_input">
<form action="../server/insert_tests.php" id="frmBox" method="post" onsubmit="return formSubmit();">
<table id="tests">
</table>
</form>
</div>
Anyone's expertise will be much appreciated, I think I need a this call somewhere in the AJAX script, but not sure how to implement this.
firstly you have to change sterialize to serialize.
function formSubmit(){
$.ajax({
type: 'POST',
url: '../server/insert_tests.php',
data: $('#frmBox').sterialize(),
success: function(response){
$('#success').html(response);
}
});
var form = document.getElementById('frmBox').reset();
return false;
}
to
function formSubmit(){
$.ajax({
type: 'POST',
url: '../server/insert_tests.php',
data: $('#frmBox').serialize(),
success: function(response){
$('#success').html(response);
}
});
var form = document.getElementById('frmBox').reset();
return false;
}
I have a form that is echoed out from the database, but the issue is that when I try to submit, only the first echoed form submits and the rest doesn't. Below is my code.
editquestion.phh
<thead>
<tr>
<th style="width: 5%;">S/N</th>
<th style="width: 20%;">QUESTION</th>
<th style="width: 40%;">ANSWER</th>
<th style="width: 30%;">KEYWORDS</th>
<th style="width: 5%;">SAVE/UPDATE</th>
</tr>
</thead>
<tbody>
<?php
$sql = $db->prepare("SELECT * FROM questions");
$result = $sql->execute();
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$quiz_id = $row['quiz_id'];
$question = $row['question'];
$answer = $row['answer'];
$keywords = $row['keywords'];
echo '<form action="updatequestion.php" method="post" enctype="multipart/form-data">
<tr>
<td><input style="width: 50%" type="text" name="cid" id="cid" value="'.$quiz_id.'"></td>
<td><input type="text" name="question" id="question" value="'.$question.'"></td>
<td><input type="text" name="answer" id="answer" value="'.$answer.'"></td>
<td><input type="text" name="keywords" id="keywords" value="'.$keywords.'"></td>
<td><input type="submit" name="qupdate" class="qupdate" value="Update"></td>
</tr>
</form>';
}
?>
</tbody>
</table>
qupdate.js
$(document).ready(function() {
$('.qupdate').click(function() {
question = $('#question').val();
answer = $('#answer').val();
keywords = $('#keywords').val();
id = $('#cid').val();
$.ajax({
type: "POST",
url: "updatequestion.php",
data: "cid="+id+"&question="+question+"&answer="+answer+"&keywords="+keywords,
success: function(html){
if(html = "true")
{
$('.qupdate').css("opacity", "1");
}
else
{
alert("not successful");
}
},
beforeSend: function(){
$('.qupdate').css("opacity", "0.5");
}
});
return false;
});
});
Just added the code for updatequestion.php.
<?php
session_start();
require_once("db.php");
$db = new MyDB();
if (isset($_POST['question']) || isset($_POST['answer']) || isset($_POST['cid']))
{
$id = strip_tags(#$_POST['cid']);
$cname = strip_tags(#$_POST['question']);
$cunit = strip_tags(#$_POST['answer']);
$keywords = strip_tags(#$_POST['keywords']);
if (empty($cname) || empty($cunit))
{
echo "fill";
}
else
{
$sql = $db->prepare("UPDATE questions SET question = ?, answer = ?, keywords = ? WHERE quiz_id = ?");
$sql->bindParam(1, $cname, SQLITE3_TEXT);
$sql->bindParam(2, $cunit, SQLITE3_TEXT);
$sql->bindParam(3, $keywords, SQLITE3_TEXT);
$sql->bindParam(4, $id, SQLITE3_INTEGER);
$result = $sql->execute();
if ($result)
{
echo "true";
}
else
{
echo "false";
}
}
}
?>
But the ajax seems to only work for the first echoed data and doesn't seem to submit the rest. How do I solve this?
Thanks in advance.
Add class dynamic-form to form tag and remove id from all fields:
echo '<form class="dynamic-form" action="updatequestion.php" method="post" enctype="multipart/form-data">
<tr>
<td><input style="width: 50%" type="text" name="cid" value="'.$quiz_id.'"></td>
<td><input type="text" name="question" value="'.$question.'"></td>
<td><input type="text" name="answer" value="'.$answer.'"></td>
<td><input type="text" name="keywords" value="'.$keywords.'"></td>
<td><input type="submit" name="qupdate" class="qupdate" value="Update"></td>
</tr>
</form>';
Update in JS
$(document).ready(function () {
$('.dynamic-form').on('submit', function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "updatequestion.php",
data: formdata,
success: function (html) {
//success
}
});
return false;
});
});
Here is solution of your problem :-
$('.qupdate').click(function() {
var question = $(this).closest("form").find('input[name=question]').val();
var answer = $(this).closest("form").find('input[name=answer]').val();
var keywords = $(this).closest("form").find('input[name=keywords]').val();
var id = $(this).closest("form").find('input[name=cid]').val();
});
It seems everyone here gave you almost the same answer, but it does not entirely satisfy your problem.
To give you the simplest answers:
What you are doing is bad practice by principle, because you should
not echo "forms"
Each form on the page has the same information
besides the inputs, which is wrong.
The correct solution:
Start using ajax post only for this purpose
Don't use FORM, instead just create a div for each question and have
the inputs there with the question id
Use a modal to edit the questions, that way when you close the
modal you reset the inputs in the modal, giving you the ability to
edit again a question and save it.
The solution you want right now:
editquestion.php
<thead>
<tr>
<th style="width: 5%;">S/N</th>
<th style="width: 20%;">QUESTION</th>
<th style="width: 40%;">ANSWER</th>
<th style="width: 30%;">KEYWORDS</th>
<th style="width: 5%;">SAVE/UPDATE</th>
</tr>
</thead>
<tbody>
<?php
$sql = $db->prepare("SELECT * FROM questions");
$result = $sql->execute();
while ($row = $result->fetchArray(SQLITE3_ASSOC))
{
$quiz_id = $row['quiz_id'];
$question = $row['question'];
$answer = $row['answer'];
$keywords = $row['keywords'];
echo '<tr>';
echo '<td><input style="width: 50%" type="text" name="cid" id="cid" value="'.$quiz_id.'"></td>';
echo '<td><input type="text" name="question" id="question" value="'.$question.'"></td>';
echo '<td><input type="text" name="answer" id="answer" value="'.$answer.'"></td>';
echo '<td><input type="text" name="keywords" id="keywords" value="'.$keywords.'"></td>';
echo '<td><input type="button" name="qupdate" class="qupdate" value="Update" onclick="doEdit('.$quiz_id.');"></td>';
echo '</tr>';
}
?>
</tbody>
</table>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Edit Question</h4>
</div>
<div class="modal-body">
<p>Edit your question:</p>
<p><input type="hidden" id="question_id" id="question_id" value=""></p>
<p><input type="text" id="question_text" value=""></p>
<p><input type="text" id="question_answer" value=""></p>
<p><input type="text" id="question_keywords" value=""></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="doupdate" class="btn btn-default">Update Question</button>
</div>
</div>
</div>
</div>
qupdate.js:
<script>
$(document).ready(function() {
function doEdit(question_id) {
/** POPULATE THE MODAL WITH THE QUESTION DATA **/
$.ajax({
type: "POST",
url: "getquestiondata.php", /** create this file, and return the question data from the database based on the "cid" **/
data: "cid="+question_id+",
success: function(response){
$('#question_id').val(response.cid);
$('#question_text').val(response.text);
$('#question_answer').val(response.answer);
$('#question_keywords').val(response.keywords);
}
});
}
/** DO THE ACTUAL UPDATE **/
$('#doupdate').click(function() {
var question_id = $('#question_id').val();
var question_text = $('#question_text').val();
var question_answer = $('#question_answer').val(),
var question_keywords = $('#question_keywords').val(),
$.ajax({
type: "POST",
url: "updatequestion.php",
data: "cid="+question_id+"&question="+question_text+"&answer="+question_answer+"&keywords="+question_keywords,
success: function(html){
if(html = "true")
{
$('.qupdate').css("opacity", "1");
$('#myModal').modal('toggle');
// Reset the modal inputs
$('#question_id').val("");
$('#question_text').val("");
$('#question_answer').val("");
$('#question_keywords').val("");
}
else
{
alert("not successful");
}
},
beforeSend: function(){
$('.qupdate').css("opacity", "0.5");
}
});
return false;
});
});
</script>
This code is untested, as I do not have your database or any information about the questions you store, however I am 90% positive that if you use this method it will work for you better than any other answer.
If I made some small typo or mistake, the code is very easy to edit and fix it.
FINAL NOTE: "updatequestion.php" is not the problem here, was never the problem.
Good luck!
As was mentioned by other people ID should be unique on the page.
In your case you can get whole form and serialize it's data:
$(document).ready(function() {
$('.qupdate').click(function() {
// Clicked $('.qupdate') is now $(this)
// But we should define $this variable if we want to be able to use it in callbacks.
// This is more efficient way instead of searching for $('.qupdate') in DOM again and again.
// Unless you want to set CSS for ALL .qupdate buttons in ALL forms.
var $this = $(this);
$.ajax({
type: "POST",
url: "updatequestion.php",
// find closest to .qupdate form and serialize it's data
data: $this.closest('form').serialize(),
success: function(html) {
// use double (or even tripple) equals operator if you want to compare, otherwise you'll just set html as "true"
// and it'll be always successful
if(html == "true") {
// We use $this variable here which we've defined earlier, and which, as we remember,
// stands for clicked $('.qupdate') button
$this.css("opacity", "1");
} else {
alert("not successful");
}
},
beforeSend: function() {
// We use $this variable here which we've defined earlier, and which, as we remember,
// stands for clicked $('.qupdate') button
$this.css("opacity", "0.5");
}
});
return false;
});
});
Update
Perhaps you send in response not exactly "true" or "false"?
In order to be sure that you don't send back any extra characters you should call exit after echo:
if ($result)
{
echo "true";
exit;
}
else
{
echo "false";
exit;
}
If you aren't sure you can simply remove this html check from JS since it never worked actually in your example:
// remove this if-else block
if(html = "true")
{
$('.qupdate').css("opacity", "1");
}
else
{
alert("not successful");
}
You can also check what you send and what you get using browser developer tools. For example in chrome press F12 and in the opened panel select Network tab. Now click button in any form and you'll see that new request was sent. Wait for it to complete - Status column should receive some number (200 if everything was ok). Now you can click on this request and see details. There is even video example =) https://www.youtube.com/watch?v=WOQDrGrd9H8
I try to help using Sanjay Kumar answer since you want to save per row
editquestion.php
<thead>
<tr>
<th style="width: 5%;">S/N</th>
<th style="width: 20%;">QUESTION</th>
<th style="width: 40%;">ANSWER</th>
<th style="width: 30%;">KEYWORDS</th>
<th style="width: 5%;">SAVE/UPDATE</th>
</tr>
</thead>
<tbody>
<?php
// assuming your database already connected here
$sql = $db->prepare("SELECT * FROM questions");
$result = $sql->execute();
while($row = $result->fetchArray(SQLITE3_ASSOC))
{
$quiz_id = $row['quiz_id'];
$question = $row['question'];
$answer = $row['answer'];
$keywords = $row['keywords'];
// enctype="multipart/form-data" is used if the form contains a file upload, and echo per line for clarity
echo '<form action="updatequestion.php" method="post">';
echo '<tr>';
echo '<td><input style="width: 50%" type="text" name="cid" value="'.$quiz_id.'"></td>';
echo '<td><input type="text" name="question" value="'.$question.'"></td>';
echo '<td><input type="text" name="answer" value="'.$answer.'"></td>';
echo '<td><input type="text" name="keywords" value="'.$keywords.'"></td>';
echo '<td><input type="submit" name="qupdate" class="qupdate" value="Update"></td>';
echo '</tr>';
echo '</form>';
}
?>
</tbody>
</table>
qupdate.js
// assuming you already loaded jquery library
$(document).ready(function()
{
$('.qupdate').click(function()
{
var id = $(this).closest("form").find('input[name=cid]').val();
var question = $(this).closest("form").find('input[name=question]').val();
var answer = $(this).closest("form").find('input[name=answer]').val();
var keywords = $(this).closest("form").find('input[name=keywords]').val();
var postData = {'cid' : id, 'question' : question, 'answer' : answer, 'keywords' : keywords};
$.ajax(
{
type: "POST",
url: "updatequestion.php",
data: postData,
success: function(response)
{
// note the '==' operator
if(response == "true")
{
$('.qupdate').css("opacity", "1");
}
else
{
console.log(response);
alert("not successful");
}
},
error: function(e)
{
console.log(e);
},
beforeSend: function()
{
$('.qupdate').css("opacity", "0.5");
}
});
return false;
});
});
updatequestion.php
<?php
session_start();
require_once("db.php");
$db = new MyDB();
if(isset($_POST['cid']) && isset($_POST['question']) && isset($_POST['answer']) && isset($_POST['keywords']))
{
$id = filter_input(INPUT_POST, 'cid', FILTER_SANITIZE_STRING);
$cname = filter_input(INPUT_POST, 'question', FILTER_SANITIZE_STRING)
$cunit = filter_input(INPUT_POST, 'answer', FILTER_SANITIZE_STRING)
$keywords = filter_input(INPUT_POST, 'keywords', FILTER_SANITIZE_STRING)
if($id == '' || $cname == '' || $cunit == '' || $keywords == '')
{
echo "one or more parameter is empty";
}
else
{
$sql = $db->prepare("UPDATE questions SET question = ?, answer = ?, keywords = ? WHERE quiz_id = ?");
$sql->bindParam(1, $cname, SQLITE3_TEXT);
$sql->bindParam(2, $cunit, SQLITE3_TEXT);
$sql->bindParam(3, $keywords, SQLITE3_TEXT);
$sql->bindParam(4, $id, SQLITE3_INTEGER);
$result = $sql->execute();
if ($result)
{
echo "true";
}
else
{
echo "false";
}
}
}
else
{
echo "wrong parameter";
}
?>
I add some comment in the code.
You can inspect element and check in console tab for additional message if something not working, and i add filter input function for some security and change the comparison for empty variable.
I hope this give you some idea.
You can use in some other way may be it works
$(document).on('click','.qupdate',function() {
var question = $(this).closest("form").find('input[name=question]').val();
var answer = $(this).closest("form").find('input[name=answer]').val();
var keywords = $(this).closest("form").find('input[name=keywords]').val();
var id = $(this).closest("form").find('input[name=cid]').val();
});
//or
jQuery('body').on('click', '.qupdate', function (){
var form = $(this).closest("form");
var forminput = form.serialize();
});
I am trying to delete rows from my sql database using checkbox. This is working fine as long as there is only one checkbox marked. But I also want it to be possible to delete multiple rows. I have seen many example, but I cant get it to work. Hope anyone here can help me.
So first the result.php file (here is all the rows / table created):
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH)) {
echo "<tr>";
echo "<td><input type='checkbox' name='id[]' class='toedit' value='" . $row[0] . "'></td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
echo "</table>";
This file is included in my main html (main.html) file, here is the Jquery as well.
Jquery sending chechbox variables to delete.php file:
<script type="text/javascript">
$(".deletelogg").on('click', function(){
$.ajax({
type: 'POST',
url: "php/delete.php",
data: {id:$('.toedit:checked:first').val()},
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
</script>
Last in my delete.php file:
include 'connect-database.php';
for ($i = 0; $i < count($_POST['id']); $i++) {
if ($_POST['id'][$i] != "") {
echo $_POST['id'] ;
$sql = "DELETE FROM Logg Where LoggID LIKE '".$_POST['id']."'";
$stmt = sqlsrv_query( $conn, $sql);
if ($stmt == false) {
die( print_r(sqlsrv_errors(), true) );
}
}
}
I was trying to make an array containing all id from the checkbox, but it didn't work.. any help pleas?
A working example: http://jsfiddle.net/Twisty/1y4zy5mn/
You should iterate over your checkboxes and collect the values. Given the following HTML:
<table>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="1" />
</td>
<td>One</td>
<td>Fish</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="2" />
</td>
<td>Two</td>
<td>Fish</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="3" />
</td>
<td>Red</td>
<td>Fish</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="4" />
</td>
<td>Blue</td>
<td>Fish</td>
</tr>
</table>
<button class="deletelogg">Delete</button>
<p></p>
Your JQuery will need to do a little more work. This should work for 1 or many:
$(".deletelogg").on('click', function () {
var ids = [];
$(".toedit").each(function () {
if ($(this).is(":checked")) {
ids.push($(this).val());
}
});
if (ids.length) {
$.ajax({
type: 'POST',
url: "php/delete.php",
data: {
id: ids
},
success: function (data) {
alert(data);
$("p").text(data);
}
});
} else {
alert("Please select items.");
}
});
With this, you can switch to a foreach() loop too:
include 'connect-database.php';
foreach ($_POST['id'] as $id) {
echo $id;
$sql = "DELETE FROM Logg Where LoggID = $id";
$stmt = sqlsrv_query( $conn, $sql);
if ($stmt == false) {
die( print_r(sqlsrv_errors(), true) );
}
}
I'd do it like this way: first make a "checkAll" checkbox, and when is checked, check all your check-boxes. Then at the end of your form, put the "delete" button. When this one is pressed, all the checked check-boxes are deleted. I think this works even for some of the check-boxes (if you only check some of them, not all of them).
<div id="content"></div>
<input type="checkbox" id="checkAll">
//get all the rows from db here, or make them manually
<input type="checkbox" class="check" name="checkbox" value="<?php echo $row->id;?>">
//...
Then, with this piece of js code, you can check them all, or some of them, and "send" them to a server-side script which will grab them, and delete them from the db.
var checkBoxes = document.getElementsByTagName('input');
var param = "";
var params = [];
for (var counter=0; counter < checkBoxes.length; counter++) {
if (checkBoxes[counter].type.toUpperCase()=='CHECKBOX' && checkBoxes[counter].checked == true) {
param += checkBoxes[counter].value+' ';
params = param;
}
}
$.ajax({
type: "POST",
url: "path/to/server/side/script",
data: { params:params },
success: function(resp){
$('#content').html(resp);
}
});
And for checking them all:
$("#checkAll").click(function(){
$(".check").prop('checked', $(this).prop('checked'));
});
I don't know if this is the best way, but is a point to start. Also, don't forget to secure your app.
I'm trying to implement live-table edit, but I'm having some trouble with my select options. The input type="text" is fully functional though.
Ever since I tried to add select, it seemed to brake my entire lay-out. First there were multiple rows and columns displayed on the page. But now there's only one and the columns show up empty after the one that contains select.
And the second problem is that ajax doesn't post the table edit since I added select to the mark-up. I'm thinking that this is because the mark-up breaks, but I'm not sure.
If anybody knows what to do, I'd appreciate it.
Markup
<?php
$query = ("select * from projectlist");
$resultaat = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($resultaat, MYSQL_ASSOC)){
$id = $row['projectid'];
?>
<tr class="predit">
<form action="" method="post">
//Working input
<td>
<span id="klant_<?php echo $id; ?>" class="text"><?php echo $row["Klant"]; ?></span>
<input type="text" class="ip" id="klant_ip_<?php echo $id; ?>" value="<?php echo $row["Klant"]; ?>">
</td>
//Same approach, but with select instead of input
<td>
<span id="project_<?php echo $id; ?>" class="text"><?php echo $row["Project"]; ?></span>
<select id="project_ip_<?php echo $id; ?>" class="ip">
<?php
//Fetch select options from another table
$query = ("select * from projecten");
$resultaat = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($resultaat, MYSQL_ASSOC)){
$listid = $row["projectcode"];
$projectnaam = $row["projectnaam"];
?>
<option value="<?php echo $projectnaam; ?>" id="<?php echo $listid; ?>"><?php echo $projectnaam; ?></option>
<?php
}
?>
</select>
</td>
</tr>
</form>
<?php
}
?>
JQuery Ajax
$(document).ready(function(){
//Projeclist
$(".predit").click(function(){
var ID=$(this).attr('id');
$("#klant_"+ID).hide();
$("#project_"+ID).hide();
$("#klant_ip_"+ID).show();
$("#project_ip_"+ID).show();
}).change(function(){
var ID=$(this).attr('id');
var klant=$("#klant_ip_"+ID).val();
var project=$("#project_ip_"+ID).val();
var dataString = 'id='+ ID
+'&Klant='+klant
+'&Project='+project;
//alert(dataString);
var project_txt = $("#project_ip_"+ID+" option:selected").text();
$.ajax({
type: "POST",
url: "post_table.php",
data: dataString,
cache: false,
success: function(html){
$("#project_"+ID).html(project_txt);
$("#klant_"+ID).html(klant);
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
},
});
});
$(".ip").mouseup(function() {
return false
});
$(document).mouseup(function(){
$(".ip").hide();
$(".text").show();
});
});
post_table.php
<?php
include('config.php');
$klant = $_POST['Klant'];
$project = $_POST['Project'];
$id = $_POST['id'];
$query = "update projectlist
set Klant='$klant',
Project='$project'
where projectid='$id'";
mysql_query($query, $con);
?>
I am new in php. When user select one of the option in dropdown menu, the list of selected item will shows in textarea form. I want to make each of every item on that list, link to another page. How do I write php/html statement in javascrip/jquery? Here is my javascript :
<script type="text/javascript">
function check(){
var select = document.getElementById('category');
var textarea = document.getElementById('model');
$.ajax({
type: 'POST',
url: 'http://localhost/system/ajax.php',
data: {txt:$('#category').val()},
dataType: 'json',
success: function(resp){
result = resp.success;
textarea.value = "";
for(i=0; i<result.length; i++){
textarea.value = result[i] += "\n" + textarea.value;
}
}
});
}
This is my html code :
<form action="" method="post">
<tr>
<td width="116">Category</td>
<td width="221">
<center>
:
<select name="category" id="category" onChange="check()">
<option>--- Choose Category ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("inventory");
$sql = mysql_query("SELECT * FROM equipment GROUP BY equip_category ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_array($sql)){
echo '<option value="'.$row['equip_category'].'">'.$row['equip_category'].'</option>';
}
}
?>
</select >
</center>
</td></td></tr>
<tr>
<td><p>Model/Brand</p>
<td>
<p align="center">:<textarea name="model" id="model" rows="5" cols="25"><?php echo (''); ?></textarea>
</p>
</td></td>
</tr></form>
To insert PHP into jQuery/JS, use the following syntax:
var phpVar = <?php echo $some_php_var;?>;
console.log(phpVar); //logs $some_php_var
However, oftentimes it is best to just echo jQuery/JS in PHP:
<?php
echo 'var phpVar = '.$some_php_var.';',
'console.log(phpVar);';
?> <!--logs $some_php_var-->
In PHP use $_POST['txt'] to access the value of category that you are passing from Javascript.
Check out this tutorial for connecting PHP-Javascript-MySQL.
this is my ajax.php :-
<?php
if(!empty($_POST)) {
include "connect.php";
$txt = $_POST['txt'];
$query = "SELECT equip_name_desc FROM equipment WHERE equip_category = '$txt'";
$number = 0;
$result = mysql_query($query)
or die(mysql_error());
while($row = mysql_fetch_array($result))
{
$time = $row['equip_name_desc'];
$testarray[$number] = $time;
$number = $number+1;
}
echo json_encode(array('success'=>$testarray));
}
?>
Below is the example of output. I want to make 'Lenovo GGG' or 'HP' is a link to another page. Question is, how to write the href link in javascript?