Form echoed with PHP not submitting using ajax - php

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

Related

Updating textarea and datetime

Well, I have these input fields of date_submitted and remarks. My date_submitted is in a input type of datetime-local and my remarks is in a textarea tag. I have a function where in I can update the data I entered in it.
So here are my problems with examples:
ex. I input 03/03/2018 12:31 AM then click add for it to be added in the database, now when I am going to update it, it just shows this mm/dd/yyyy --:-- -- instead of 03/03/2018 12:31 AM
ex. For the remarks, when I input
Hello
World
then add it then update it, it shows in the textarea field this
Hello //insert br tag
World //insert br tag
so my questions are how am I gonna remove the br tags whenever I update my data? I have used nl2br in this one. and how will my inputted date still show up whenever I hit my update button? TYVM.
Below are excerpts from my code
index
<div class="col-sm-2">
<input type="datetime-local" name="date_submitted" id="date_submitted" class="form-control" placeholder="Date Submitted" style="width: 120%;"/>
</div>
<div class="col-sm-3">
<textarea name="remarks" id="remarks" class="form-control" placeholder="Remarks" rows="2" style="margin-left:13%;"></textarea>
</div>
<div class="col-sm-2">
<input type="hidden" name="id" id="docu_id" />
<button class="button add" name="action" id="action" style="margin-left: 16%;">Add</button>
</div>
<br><br>
script
<script>
$(document).ready(function(){
fetchDocu();
function fetchDocu()
{
var action = "select";
$.ajax({
url: "select.php",
method: "POST",
data: {action:action},
success: function(data){
$('#code').val('');
$('#doc_kind').val('');
$('#date_submitted').val('');
$('#remarks').val('');
$('#action').text("Add");
$('#result').html(data);
}
});
}
$('#action').click(function(){
var docCode = $('#code').val();
var docKind = $('#doc_kind').val();
var dateSubmitted = $('#date_submitted').val();
var docRemarks = $('#remarks').val();
var id = $('#docu_id').val();
var action = $('#action').text();
if(docCode != '' && docKind != '' && dateSubmitted != '')
{
$.ajax({
url : "action.php",
method:"POST",
data:{docCode:docCode, docKind:docKind, dateSubmitted:dateSubmitted, docRemarks:docRemarks, id:id, action:action},
success:function(data){
alert(data);
fetchDocu();
}
});
}
else {
alert("All Fields are Required");
}
});
$(document).on('click','.update', function(){
var id = $(this).attr("id");
$.ajax({
url: "fetch.php",
method: "POST",
data: {id:id},
dataType: "json",
success:function(data){
$('#action').text("Save");
$('#docu_id').val(id);
$('#code').val(data.code);
$('#doc_kind').val(data.doc_kind);
$('#date_submitted').val(data.date_submitted);
$('#remarks').val(data.docRemarks);
}
})
});
action.php
if($_POST["action"] == "Save")
{
$code = mysqli_real_escape_string($connect, $_POST["docCode"]);
$doc_kind = mysqli_real_escape_string($connect, $_POST["docKind"]);
$date_submitted = mysqli_real_escape_string($connect, $_POST["dateSubmitted"]);
$remarks = mysqli_real_escape_string($connect, $_POST["docRemarks"]);
$procedure = "
CREATE PROCEDURE updateDocu(IN docu_id int(11), docCode varchar(20), docKind varchar(150), dateSubmitted varchar(150), docRemarks varchar(150))
BEGIN
UPDATE officeSecTB SET code=docCode, doc_kind=docKind, date_submitted=dateSubmitted, remarks=docRemarks
WHERE id = docu_id;
END;
";
if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS updateDocu"))
{
if(mysqli_query($connect, $procedure))
{
$query = "CALL updateDocu('".$_POST["id"]."', '".$code."', '".$doc_kind."','".$date_submitted."', '".$remarks."')";
mysqli_query($connect, $query);
echo 'Data Updated';
}
}
}
and this is how I display the output
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '
<tbody>
<tr>
<td>'.$row["code"].'</td>
<td>'.$row["doc_kind"].'</td>
<td>'.date('d M Y - H:i A', strtotime($row['date_submitted'])).'</td>
<td>'.nl2br($row["remarks"]).'</td>
<div class="row">
<td>
<div class="col-sm-6">
<button name="update" id="'.$row["id"].'" class="button update btn-xs">Update</button>
</div>
<div class="col-sm-6">
<button name="delete" id="'.$row["id"].'" class="button delete btn-xs">Delete</button>
</div>
</td>
</div>
</tr>
</tbody>
';
}
}
Sorry for the long post. Thank you in advance.
fetch.php
<?php
$connect = mysqli_connect("localhost","root", "", "ustjhsdts");
if(isset($_POST["id"]))
{
$output = array();
$procedure = "
CREATE PROCEDURE whereDocu(IN docu_id int(11))
BEGIN
SELECT * FROM officesectb WHERE id = docu_id;
END;
";
if(mysqli_query($connect, "DROP PROCEDURE IF EXISTS whereDocu"))
{
if(mysqli_query($connect, $procedure))
{
$query = "CALL whereDocu(".$_POST["id"].")";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result))
{
$output['code'] = $row["code"];
$output['doc_kind'] = $row["doc_kind"];
$output['date_submitted'] = $row['date_submitted'];
$output['remarks'] = nl2br($row["remarks"]);
}
echo json_encode($output);
}
}
}
?>

not able to carry the form values through post method

There is a form where the user enters a number and according to the condition applied on the number, a list of addresses are displayed. I would like to store the data that is returned through AJAX. The code on the page that has a form:
index.php
<script>
$(document).ready(function() {
$("#phone").keyup(function() {
var number = $("#phone").val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: 'number='+number,
cache: false,
}).done(function(html) {
$('#results').html(html);
});
});
});
<script>
<form action="insert_temp.php" method="POST">
<input type="text" name="phoneno" id="phone" value="" />
<div id="results"></div>
<button class="button btn btn-primary btn-large" type="submit" name="submit" value="submit">Submit</button>
</form>
code on t_fetchaddr.php page
$val = $_REQUEST['number'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0)
{ ?>
<div class="span6" >
<div class="span3">
<? while($row2 = mysqli_fetch_assoc($result2))
{ ?>
<input type="radio" name="old_address" value="<? echo $row2['address']; ?>" ><? echo $row2['address']; ?><br>
<? } ?>
</div>
</div>
<? } ?>
code on insert_temp.php page
$old_address = mysqli_real_escape_string($con, $_POST['old_address']);
echo $old_address;
Everything is working fine until displaying of the address through number, but when I submit the form it is not going to the back end. I tried to echo $old_address but got nothing.
other input values in index page inside the form are going to backend but value that is being fetched from t_fetchaddr.php page is not getting carried, Can anyone please tell where I went wrong
Try this and watch your console :
$(document).ready(function() {
$("#phone").keyup(function() {
var number = $(this).val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: {number:number},
cache: false,
success : function(html) {
$('#results').html(html);
},
error : function(err){
console.log(err);
}
});
});
});
<script>
$(document).ready(function()
{
$("#phone").keyup(function()
{
var number = $("#phone").val();
$.ajax({
url: "t_fetchaddr.php",
type: 'POST',
data: {number :number}, //modified
cache: false,
success:function(html)
{
$('#results').html(html);
}
});
});
});
</script>//Missing closing
<form action="insert_temp.php" method="POST">
<input type="text" name="phoneno" id="phone" value="" />
<div id="results"></div>
<button class="button btn btn-primary btn-large" type="submit" name="submit" value="submit" >Submit</button>
</form>
and in php
$val = $_POST['phoneno'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0)
{ ?>
<div class="span6" >
<div class="span3">
<? while($row2 = mysqli_fetch_assoc($result2))
{ ?>
<input type="radio" name="old_address" value="<? echo $row2['address']; ?>" ><? echo $row2['address']; ?><br>
<? } ?>
</div>
</div>
<? } ?>
Note:
Missing closing tag </script>
And this line changed data: 'number='+number,
just try this code on fetchaddr.php
i have just removed the in between php tags.
<?
$val = $_REQUEST['number'];
$sql2 = "SELECT * FROM user_address where number='".$val."' ";
$result2 = mysqli_query($con, $sql2);
if (mysqli_num_rows($result2) > 0) {
echo '<div class="span6" >
<div class="span3">';
while($row2 = mysqli_fetch_assoc($result2))
{
echo '<input type="radio" name="old_address" value="'.$row2['address'].'" >'.$row2['address'].'<br>';
}
echo '</div>
</div>';
} ?>
hopefully this will solve your problem.

Set checkbox state after ajax query

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

Php Ajax form submit in colorbox

I have a form with some php to validate and insert in the database on submit and the form opens in colorbox.
So far so good. What I'm trying to do is to close colorbox and refresh a div on success.
I guess I need to pass a response to ajax from php if everything OK, close the colorbox with something like setTimeout($.fn.colorbox.close,1000); and refresh the div, but I'm stuck because I'm new in ajax.
I'll appreciate any help here.
Here is my ajax:
jQuery(function(){
jQuery('.cbox-form').colorbox({maxWidth: '75%', onComplete: function(){
cbox_submit();
}});
});
function cbox_submit()
{
jQuery("#pre-process").submit(function(){
jQuery.post(
jQuery(this).attr('action'),
jQuery(this).serialize(),
function(data){
jQuery().colorbox({html: data, onComplete: function(){
cbox_submit();
}});
}
);
return false;
});
}
form php code:
<?php
error_reporting(-1);
include "conf/config.php";
if(isset($_REQUEST['rid'])){$rid=safe($_REQUEST['rid']);}
if(isset($_REQUEST['pid'])){$pid=safe($_REQUEST['pid']);}
$msg = '';
if (!$_SESSION['rest_id']) $_SESSION['rest_id']=$rid; //change to redirect
$session_id=session_id();
if(isset($_REQUEST['submit'])){
if(isset($_POST['opta'])){
$opta=safe($_POST['opta']);
$extraso = implode(',',array_values( array_filter($_POST['opta']) ));
}
if (array_search("", $_POST['opt']) !== false)
{
$msg = "Please select all accessories!";
}else{
$extrasm = implode(',',array_values( array_filter($_POST['opt']) ));
if ($_POST['opt'] && isset($_POST['opta'])) {$extras= $extrasm .",". $extraso;}
if ($_POST['opt'] && !isset($_POST['opta'])) {$extras= $extrasm;}
if (!$_POST['opt'] && isset($_POST['opta'])) {$extras= $extraso;}
$sql['session_id'] = $session_id;
$sql['rest_id'] = $_POST['rid'];
$sql['prod_id'] = $_POST['pid'];
$sql['extras'] = $extras;
$sql['added_date'] = Date("Y-m-d H:i:s");
$newId=insert_sql("cart",$sql);
}
}
?>
<form id="pre-process" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<div style="background-color:#FFF; padding:20px;">
<?=$msg;?>
<?php
$name = getSqlField("SELECT name FROM products WHERE resid=".$_SESSION['rest_id']." and id=".$pid."","name");
echo "<div style='color:#fff; background-color:#F00;padding:10px;' align='center'><h2>".$name."</h2></div><div style='background-color:#FFF; padding: 20px 70px 30px 70px; '>Please select accessories.<br><br>";
$getRss = mysql_query("SELECT * FROM optional_groups_product where prodid=".$pid." order by id asc");
while ($rsrw = #mysql_fetch_array($getRss)) {
$goptionals = getSqlField("SELECT goptionals FROM optionals_groups WHERE resid=".$_SESSION['rest_id']." and id=".$rsrw['goptid']."","goptionals");
$goptionals=explode(', ',($goptionals));
echo "<select name='opt[]' id='opt[]' style='width:220px;'>";
echo "<option value='' >Select Options</option>";
foreach($goptionals as $v)
{
$vname = mysql_query("SELECT * FROM optionals where id=".$v." LIMIT 0,1");
while ($rsgb = #mysql_fetch_array($vname)) {
$aa=$rsgb['optional'];
}
echo "<option value=".$v." >".$aa."</option>";
}
echo "</select>(required)<br>";
//}
}
$getRss = mysql_query("SELECT * FROM optional_product where prodid=".$pid."");
?>
<br><br>
<table border="0" cellpadding="0" cellspacing="0" >
<tr>
<td bgcolor="#EAFFEC">
<div style="width:440px; ">
<?php
while ($rssp = #mysql_fetch_array($getRss)) {
$optional=getSqlField("SELECT optional FROM optionals WHERE id=".$rssp['optid']."","optional");
$price=getSqlField("SELECT price FROM optionals WHERE id=".$rssp['optid']."","price");
?>
<div style="width:180px;background-color:#EAFFEC; float:left;padding:10px;""><input type="checkbox" name="opta[]" id="opta[]" value="<?=$rssp['optid']?>" /> <i><?=$optional?> [<?=CURRENCY?><?=$price?> ]</i> </div>
<?php } ?>
</div>
</td>
</tr></table>
<input type="hidden" name="rid" value="<?=$rid?>" />
<input type="hidden" name="pid" value="<?=$pid?>"/>
</div><input type="hidden" name="submit" /><input id='submit' class="CSSButton" style="width:120px; float:right;" name='submit' type='submit' value=' Continue ' /><br />
<br /><br />
</div>
</form>
I don't know colobox, but if I understand well what you are trying to do,
I would say your javascript should more look like this
function cbox_submit()
{
jQuery("#pre-process").submit(function(e) {
e.preventDefault(); // prevents the form to reload the page
jQuery.post(
jQuery(this).attr('action')
, jQuery(this).serialize()
, function(data) {
if (data['ok']) { // ok variable received in json
jQuery('#my_colorbox').colorbox.close(); // close the box
}
}
);
return false;
});
}
jQuery(function() {
jQuery('#my_colorbox').colorbox({
maxWidth: '75%'
, onComplete: cbox_submit // Bind the submit event when colorbox is loaded
});
});
You should separate at least your php script that does the post part.
And this php (called with jQuery(this).attr('action')) should return a json ok variable if successfull. Example:
<?php
# ... post part ...
# if success
ob_clean();
header('Content-type: application/json');
echo json_encode(array('ok' => true));
?>

Problem with Mootools Ajax request and submitting a form

I have a table with content comming from a database. Now i tryed to realize a way to (a) delete rows from the table (b) edit the content of the row "on the fly". (a) is working perfectly (b) makes my head smoking!
Here is the complete Mootools Code:
<script type="text/javascript">
window.addEvent('domready', function() {
var eDit = $('edit_hide');
eDit.slide('hide');
var del = new Request.HTML(
{
url: 'fuss_response.php',
encoding: 'utf-8',
update: eDit,
onComplete: function(response)
{
eDit.slide('in');
}
});
$$('input.delete').addEvent( 'click', function(e){
e.stop();
var aID = 'delete_', bID = '';
var deleteID = this.getProperty('id').replace(aID,bID);
new MooDialog.Confirm('Soll der Termin gelöscht werden?', function(){
del.send({data : "id=" + deleteID});
}, function(){
new MooDialog.Alert('Schon Konfuzius hat gesagt: Erst denken dann handeln!');
});
});
var edit = new Request.HTML(
{
url: 'fuss_response_edit.php',
update: eDit,
encoding: 'utf-8',
onComplete: function(response)
{
$('sst').addEvent( 'click', function(e){
e.stop();
safe.send();
});
}
});
var safe = new Request.HTML(
{
url: 'termin_safe.php',
encoding: 'utf-8',
update: eDit,
onComplete: function(response)
{
}
});
$$('input.edit').addEvent( 'click', function(e){
e.stop();
var aID = 'edit_', bID = '';
var editID = this.getProperty('id').replace(aID,bID);
edit.send({data : "id=" + editID});
$('edit_hide').slide('toggle');
});
});
</script>
Here the PHP Part that makes the Edit Form:
<?php
$cKey = mysql_real_escape_string($_POST['id']);
$request = mysql_query("SELECT * FROM fusspflege WHERE ID = '".$cKey."'");
while ($row = mysql_fetch_object($request))
{
$id = $row->ID;
$name = $row->name;
$vor = $row->vorname;
$ort = $row->ort;
$tel = $row->telefon;
$mail = $row->email;
}
echo '<form id="termin_edit" method="post" action="">';
echo '<div><label>Name:</label><input type="text" id="nns" name="name" value="'.$name.'"></div>';
echo '<div><label>Vorname:</label><input type="text" id="nvs" name="vorname" value="'.$vor.'"></div>';
echo '<div><label>Ort:</label><input type="text" id="nos" name="ort" value="'.$ort.'"></div>';
echo '<div><label>Telefon:</label><input type="text" id="nts" name="telefon" value="'.$tel.'"></div>';
echo '<div><label>eMail:</label><input type="text" id="nms" name="email" value="'.$mail.'"></div>';
echo '<input name="id" type="hidden" id="ids" value="'.$id.'"/>';
echo '<input type="button" id="sst" value="Speichern">';
echo '</form>';
?>
And last the Code of the termin_safe.php
$id = mysql_real_escape_string($_POST['id']);
$na = mysql_real_escape_string($_POST['name']);
$vn = mysql_real_escape_string($_POST['vorname']);
$ort = mysql_real_escape_string($_POST['ort']);
$tel = mysql_real_escape_string($_POST['telefon']);
$em = mysql_real_escape_string($_POST['email']);
$score = mysql_query("UPDATE fuspflege SET name = '".$na."', vorname = '".$vn."', ort = '".$ort."', telefon = '".$tel."', email = '".$em."' WHERE ID = '".$id."'");
As far as i can see the request does work but the data is not updated! i guess somethings wrong with the things posted
For any suggestions i will be gladly happy!
PS after some comments: I see the problem in this part:
var edit = new Request.HTML(
{
url: 'fuss_response_edit.php',
update: eDit,
encoding: 'utf-8',
onComplete: function(response)
{
$('sst').addEvent( 'click', function(e){
e.stop();
safe.send();
});
}
});
The "Edit" request opens the form with the prefilled input fields and then attaches a click event to the submit button which should call a new request when clicked.
This third request i fail to pass the data of the input fields. i tried to get the value of each field like this:
var name = $('nns').getProperty('value');
and pass it this way
.send({data : "name=" + name});
did not work so far
PPS:
as requested the code that makes the html from main site
<?php $request = mysql_query("SELECT * FROM fusspflege");
echo '<form id="fusspflege" method="post" action="">';
echo '<table class="fuss_admin">';
echo '<tr><th>Name</th><th>Vorname</th><th>Ort</th><th>Telefon</th><th>eMail</th><th>Uhrzeit</th><th>Datum</th><th></th><th></th></tr>';
echo '<tr><td colspan=8 id="upd"></td></tr>';
while ($row = mysql_fetch_object($request))
{
$id = $row->ID;
$name = $row->name;
$vor = $row->vorname;
$ort = $row->ort;
$tel = $row->telefon;
$mail = $row->email;
$dat = $row->datum;
$uhr = $row->uhrzeit;
echo '<tr><td>'.$name.'</td><td>'.$vor.'</td><td>'.$ort.'</td><td>'.$tel.'</td><td>'.$mail.'</td><td>'.$uhr.'</td><td>'.$dat.'</td>';
echo '<td><input id="delete_'.$id.'" class="delete" type="button" value="X"></td>';
echo '<td><input id="edit_'.$id.'" class="edit" type="button" value="?"></td>';
echo '</tr>';
}
echo '</table>';
echo '</form>';
echo '<div id="edit_hide"></div>';
?>
UPDATE:
<form action="" method="post" id="termin_edit">
<div>
<label>
Name:
</label>
<input type="text" value="NAME" name="name" id="nns">
</div>
<div>
<label>
Vorname:
</label>
<input type="text" value="Marianne" name="vorname" id="nvs">
</div>
<div>
<label>
Ort:
</label>
<input type="text" value="MArkt Wald" name="ort" id="nos">
</div>
<div>
<label>
Telefon:
</label>
<input type="text" value="" name="telefon" id="nts">
</div>
<div>
<label>
eMail:
</label>
<input type="text" value="info#rudolfapotheke.de" name="email" id="nms">
</div>
<input type="hidden" value="115" id="ids" name="id">
<input type="button" value="Speichern" id="sst">
</form>
Update:
This is the mootools script based on the form you gave me that should work with your html:
$('sst').addEvent('click', function(event) {
var data;
event.stop();
var myInputEl = $$('#termin_edit input');
for(var i=0; i<myInputEl.length; i++){
if(i == 0)
data = myInputEl[i].name + "=" + myInputEl[i].value;
else
data += "&" + myInputEl[i].name + "=" + myInputEl[i].value;
}
myRequest.send(data);
});
Also add alert to your Request call back for the edit just to test if the ajax worked:
onSuccess: function(responseText) {
alert("done! " + responseText);
},
onFailure: function() {
alert("failed");
}
On the php side create a new PHP file and put the following in it and have ajax target it:
<?php
print_r($_POST);
?>
The Ajax should return the $_POST array in the alert box.

Categories