Delete multiple rows using Jquery - php

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.

Related

How do I force a refresh on click on php?

I have two buttons in html which are back and next.
If i click those buttons a variable gets incremented or decremented.
This variable is getting sent to a function.php where there is an sql statement.
The statement is:
select * from x where dimension is = value
How do I refresh the page to show my new table out of my query?
That is my php right here:
function tbl_showPage($page){
global $mysqlhost, $mysqluser, $mysqlpwd, $mysqldb;
$connection=mysqli_connect($mysqlhost, $mysqluser, $mysqlpwd) or die ("Verbindungsversuch fehlgeschlagen");
mysqli_select_db($connection, $mysqldb) or die("Konnte die Datenbank nicht waehlen.");
if($page<1)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='1'";
}
elseif($page>9)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='9'";
}
else
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension=$page";
}
$quest_query = mysqli_query($connection, $sql_tbl_questions) or die("Anfrage nicht erfolgreich");
$i = 0;
while ($question = mysqli_fetch_array($quest_query)) {
$i++;
echo '<tr>';
echo '<th>'.$i.'</th>';
echo '<th>'.$question['question'].'</th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="0" required></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="2.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="7.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="10"></th>';
echo '</tr>';
$dimensions = $question['dimension'];
}
echo '<tr>';
echo '<th></th>';
echo '<th>Kommentar/Ihre Anmerkung</th>';
echo '<th class="text-center" colspan=5><textarea rows=3 cols=50 name="Kommentar"></textarea></th>';
echo '</tr>';
echo '<input type="hidden" name="gesamt" value="'.$i.'">';
echo '<input type="hidden" name="dimensions" value="'.$dimensions.'">';
echo '<input type="hidden" name="size" value="'.$_POST['size'].'">';
echo '<input type="hidden" name="branche" value="'.$_POST['branche'].'">';
}
maybe my var is not beeing passed probably?
The javascript function is looking like that:
<script type="text/javascript">
var ki = kd = 1;
function increase()
{
ki++;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: ({page:ki}),
success: function(data){
console.log(data);
}
});
window.location.reload();
}
function decrease()
{
kd--;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: ({page:kd}),
success: function(data){
console.log(data);
}
});
window.location.reload();
}
</script>
I can't really figure out my problem, is my variable which I am generating in the function not passed properly, or is there another problem?
Seems as if you are mixing PHP and javascript here.
Do you have a onClick-function on your button? If you do, and a javascript function is called you can just add window.location.reload(); at the bottom of your javascript function to reload the page.
Tips: Use the edit function on your post and add code related to your problem, then it is easier to get help.
It is easy to make in JavaScript,
function myFunction() {
window.location.reload();
}
And then you just add the function to your button,
<button class="myButton" onclick=myFunction()">Click to reload</button>

Form echoed with PHP not submitting using ajax

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();
});

Cant pass value of checkbox through ajax

I have table received from database:
<p id="result"></p>
<?php
//$id = $_SESSION['staff_id'];
$teamResult = getQuarter($leader_id);
$count1 = 0;
if (mysqli_num_rows($teamResult) > 0)
{
?>
<table id="confirm">
<tr>
<th>1st Quarter</th>
</tr>
<?php
while($row = mysqli_fetch_array($teamResult))
{
$staff_id = $row['staff_id'];
$username = $row['username'];
$date1 = $row['date1']; $fdate1 = $row['fdate1']; $q1 = $row['q1']; $cfm1 = $row['cfm1'];
?>
<tr>
<td>
<?php if($date1 != NULL){
echo "Ev.date: ".$date1."<br/> Fb.date: ".$fdate1.""
."<input type='text' id='stid' name='confirm' class='confirm' value='". $q1. "| " . $staff_id ."'>";
}else {echo "";}
?>
</td>
</tr>
<?php
$count1++;
}
} else {
echo "<h2>No Data to Display</h2>";
}
?>
</table>
This field is checkbox but I changed it to text to see its value:
<input type='text' id='stid' name='confirm' class='confirm' value='". $q1. "| " . $staff_id ."'>
Here is what I got in table:
Then I have AJAX function:
<script>
$(function () {
$(document).on('click', '.confirm', function(){
var stid = $("#stid").val();
$.ajax({
url: "comAssessment/change.php",
method: "POST",
data: {stid: stid},
dataType:"text",
success: function (data) {
$('#confirm').hide();
$('#result').html(data);
}
});
});
});
</script>
And change.php:
$info = $_POST["stid"];
list($value1,$value2) = explode('|', $info);
echo $value1;
echo "<br/>";
echo $value2;
But the problem is I dont get correct value. For first and second row i get 1| 1000302. Even for second row where is should be 1| 1000305. What it the problem and how can I solve it?
IDs have to be unique. $("#stid") will always select the first element with that ID.
You can simply use $(this) to get the value of the element you clicked on.
$(document).on('click', '.confirm', function(){
var stid = $(this).val();
$.ajax({
url: "comAssessment/change.php",
method: "POST",
data: {stid: stid},
dataType:"text",
success: function (data) {
$('#confirm').hide();
$('#result').html(data);
}
});
});

ajax / php form and variable assignment

My goal is to submit a set of variables to my AJAX function from with in a while loop in php. This is my first shot at using AJAX, so please excuse if it is messy, and not close to correct. I appreciate any assistance.
PHP FORM:
x=0;
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$id = $row['col1'];
$ad = $row['col2'];
cho '<form id="msu_form">';
echo "<tr><td>{$ad}</td>";
echo "<td>";
$query2 = "SELECT col1,col2 FROM table WHERE notes = 'x'";
$result2 = mysql_query($query2);
$count2 = mysql_num_rows($result2);
if($count2 > 0)
{
echo '<select class="Primary" name="primary" onchange=doAjaxPost()>';
while($row2 = mysql_fetch_array($result2))
{
echo "<option value=".$row2['col1'].">".$row2['col2']."</option>";
}
echo "</select>";
}else
{
echo "Blah";
}
echo "</td>";
echo "<td>";
$query3 = "SELECT col1,col2 FROM table2 WHERE notes = 'y'";
$result3 = mysql_query($query3);
$count3 = mysql_num_rows($result3);
if($count3 > 0)
{
echo '<select class="Secondary" name="secondary">';
while($row3 = mysql_fetch_array($result3))
{
echo "<option value=".$row3['col1'].">".$row3['col2']."</option>";
}
echo "</select>";
}else
{
echo "Bah";
}
echo "</td>";
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
//echo '<td>'."<input type='submit' name='btnupdate' value='UPDATE' /></td>";
echo '</form>';
$x = $x+1;
}
So what happens is every time I change any of the "primary" select boxes on the screen, I get the value of the variables on the first line only. I want to receive the values of the form from the select box. I have tested it via a button, that submits the form it is commented out, but that button submits all the correct information to the page, but I don't want to submit the data every time. Is there a way to accomplish my goal?
Thanks - below the ajax if it helps with an answer.
<script>
function doAjaxPost() {
// get the form values
var primary = $(this).val();
var secondary = $(this).parent().next().child('.Secondary').val();
var hidden = $(this).parent().nextAll('.ID').val();
//var desc = $(this).parent().nextAll('#desc').val();
$.ajax({
type: "POST",
url: "functions/database_write.php",
data: $('#msu_form').serialize(),
//data: "Primary="+primary+"&Hidden="+hidden+"&Secondary="+secondary,
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
First, in your php code change the following 4 lines (using id)
echo "<select id=Primary name=primary onchange=doAjaxPost()>";
echo "<select id=Secondary name=secondary>";
echo '<input type="hidden" id="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" id="desc" name="desc" value="'.$ad.'"/>';
to (using class) edited
echo '<select class="Primary" name="primary" onchange="doAjaxPost(this)">'; //added (this)
echo '<select class="Secondary" name="secondary">';
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
Then, in your javascript code, change
function doAjaxPost() {
var primary = $('#Primary').val();
var secondary = $('#Secondary').val();
var hidden = $('#ID').val();
var desc = $('#desc').val();
to edited
function doAjaxPost(sel) { // added (sel)
var primary = $(sel).val(); //changed to $(sel)
var secondary = $(sel).parent().next().children('.Secondary').val(); //changed to $(sel) and changed to children()
var hidden = $(sel).parent().nextAll('.ID').val(); //changed to $(sel) and changed to nextAll()
var desc = $(sel).parent().nextAll('#desc').val(); //changed to $(sel) and changed to nextAll()
If everything works fine when submitting normally, then probably you are generating the ajax data wrong, instead give your form an id:
echo '<form id="myform">';
Then serialize the form to get the correct data:
function doAjaxPost() {
$.ajax({
type: "POST",
url: "functions/data.php",
data: $('#myform').serialize(),
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
EDIT Ok you edit has cleared things up a bit, I didn't notice you have multiple forms.
Using the same doAjaxPost function as above, change the data property to:
data: $(this).parents('form').serialize();

How to make this J Query/Ajax script work with more than one row record?

I have a table with records from a database which is dynamically filled.
<table>
<tr>
<td>name
</td>
<td>surname
</td>
...
</tr>
<?php do { ?>
<tr>
<td><?php echo $row_Recordset1['Name'];?>
</td>
<td><?php echo $row_Recordset1['Surname'];?>
</td>
...
<td align="center">
<form name="form" action="novi.php">
<input name="check" type="radio" value="da">Да
<input name="check" type="radio" value="ne">Не
<input type="hidden" id="id" value="<?php echo $row_Recordset1['id_korisnici'];?>">
<input class="button1"type="button" id="klik" value="Испрати"/>
</form>
</td>
</tr>
<?php } while($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</table>
And than I'm using J Query to create an AJAX call to another page which will run the query.
<script>
$('#klik').click(function() {
var check = $("input[name='check']:checked").val();
var id = $('#id').val();
if (check == "da")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik').prop('value', (data));
document.location.reload();
});
}
else if (check == "ne")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik').prop('value', (data));
document.location.reload();
});
}
else
{
$('#klik').prop('value', 'Грешка');
setTimeout("$('#klik').prop('value', '.')",500);
setTimeout("$('#klik').prop('value', '..')",1000);
setTimeout("$('#klik').prop('value', '...')",1500);
setTimeout("$('#klik').prop('value', 'Испрати')",2000);
}
});
This is working OK if there is only one row in the table.
What I don't know how to do is, to make the script store all the generated CHECKED radio buttons in an array or something, plus all the ID's of the records from the database and send them to another page where according to their ID's a query will update the database..
<?php
if ($_POST['id'] != NULL) {
if ($_POST['check'] == "da") {
$id = mysql_real_escape_string($_POST['id']);
$update = mysql_query("update korisnici set validacija = 1 where id_korisnici= '$id'");
if ($update === true) {
echo 'OK';
}else if ($update === false){
echo 'Error!!!';
}
}
elseif ($_POST['check'] == "ne")
{
$id = mysql_real_escape_string($_POST['id']);
$update = mysql_query("update korisnici set validacija = 2 where id_korisnici= '$id'");
if ($update === true) {
echo 'OK';
}
else if ($update === false){
echo 'Error!!!';
}
}
} else {
echo 'Error!!!';
}
?>
Thanks!
P.S. I'm a noob in JQuery and a beginner in PHP...
UPDATE:
I did change some things. And now the values are shown as I want, when I click the button without a selection I'm getting the error message in the ELSE part of the JQuery code in the proper button. But no matter which button I click (if the table is populated with 3 records from the database, there are 3 buttons) only the first row from the table is updated in the database.
<form name="form" action="novi.php">
<input name="check<?php echo $row_Recordset1['id_korisnici'];?>" type="radio" value="da">Да
<input name="check<?php echo $row_Recordset1['id_korisnici'];?>" type="radio" value="ne">Не
<input type="hidden" id="id" value="<?php echo $row_Recordset1['id_korisnici'];?>">
<input class="button1"type="button" id="klik<?php echo $row_Recordset1['id_korisnici'];?>" value="Испрати"/>
</form>
The JQuery:
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').click(function() {
var check = $("input[name='check<?php echo $row_Recordset1['id_korisnici'];?>']:checked").val();
var id = $('#id').val();
if (check == "da")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', (data));
document.location.reload();
});
}
else if (check == "ne")
{
$.post('sluzbaIncludes/n.php', {check:check, id:id}, function(data) {
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', (data));
document.location.reload();
});
}
else
{
$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', 'Error');
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '.')",500);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '..')",1000);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', '...')",1500);
setTimeout("$('#klik<?php echo $row_Recordset1['id_korisnici'];?>').prop('value', 'Send')",2000);
}
});
Make each group of radio buttons have a unique name but the same class. Then you can iterate through them using jQuery:
var radioVals = new Array();
var i = 0;
$(".radioButtonClass:checked").each(function() {
radioVals[i] = $(this).val();
});
Then just pass the array in your ajax call.

Categories