Make Checkbox that checked after submit to be visible using ajax - php

I have a form that takes the attendance of staffs. After submit I need the checkbox to be checked for the selected staffs. The form is submitted through ajax. Below is the code that inserts the attendence of the whole staffs.
var _data = new FormData($('#formaction')[0]);
$.ajax({
type: 'POST',
dataType:"json",
processData: false,
contentType: false,
url: '<?php echo base_url();?>SchoolAdmin/insertAttendance',
data: _data,
success: function (result) {
console.log(result);
staffattendance();
}
});
function staffattendance()
{
var fullDate = new Date();
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);
//var currentDate = fullDate.getDate() + "/" + twoDigitMonth + "/" + fullDate.getFullYear();
var currentDate = fullDate.getFullYear()+"-"+ twoDigitMonth +"-"+fullDate.getDate();
$.ajax({
type: 'POST',
dataType:"json",
url: '<?php echo base_url();?>SchoolAdmin/staffattendance',
data: {currentDate:currentDate},
success: function (result) {
$.each(result, function (i, item) {
console.log(result[i].staff_id);
$('.teachers').prop('checked', true);
});
}
});
}
Here I called a function staffattendance(), to get the staff id of staffs who is present on the current day. So i need to match the staff id I received through this function with the checkbox field and should be in checked mode. Below is the code that dynamically generates checkboxes with staff name.
<?php foreach($teacher as $row)
{?>
<tr><td>
<?php echo $row->name;?>
</td>
<td>
<input type="checkbox" name="teachers[]" class="teachers" value="<?php echo $row->staff_id;?>" >
<input type="hidden" name="teachers1[]" class="teachers1" value="<?php echo $row->staff_id;?>">
</td>
</tr>
<?php }?>
So I need to retain the checkbox of the staff_id that i got from staffattendance() fuction .
How this can be achieved.

Rose, the question is bit unclear as you do not specify when your table with names and checkboxes are generated and will this table be affected by ajax success..
you could try:
$.each(result, function (i, item) {
console.log(result[i].staff_id);
$('.teachers[value="'+result[i].staff_id+'"]').prop('checked', true);
});

Related

How to update quantity in session array on the go?

I want to capture value keyed in textbox for quantity in the shopping cart while they type. I used jquery's key up for this.Then I want to save the new value in the session for quantity. I'm getting the value but unable to save it. It returns null after refreshing the page.
Html
<input type="text" size="4" class="qty" value="<?php echo $v['quantity'];?>" id="<?php echo $k;?>"/>
Ajax
$("input[class=qty]").keyup(function()
{
var data;
var newVal = $(this).val();
var id = this.id;
console.log(id+" "+newVal);
$.ajax({
type: "GET",
dataType: "text",
url: "updateCart.php?id="+id+"&&value"+newVal, //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
newVal=data;
}
});
});
updateCart.php
<?php
session_start();
$id = $_GET['id'];//say 2
$new_value =$_GET['value'];//say 16
foreach($_SESSION['cart'] as $k=>$v)
{
$k;
$v["id"];
$v["quantity"];
if($id == $k)
{
//assign new value to the quantity
$_SESSION['cart'][$id]['quantity']=$new_value;
//print_r($_SESSION['cart'][1]['quantity']);
}
}
//echo json_encode($new_value);
//var_dump($_SESSION['cart']);
this can display session['cart'] with updated value if I test in
this page ..but when passed to originated page via ajax, returns null.
echo $_SESSION['cart'][$id]['quantity'];
?>
You left out the = between &value and + newVal. But I recommend you let jQuery do this automatically by using the data: option.
data = { id: id, value: newVal };
$.ajax({
type: "GET",
dataType: "text",
url: "updateCart.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
console.log(data);
newVal=data;
}
});

jQuery Ajax is not Working what is the Issue

jQuery for Updating Database table entry using PHP. after ajax code is not working for me please help.
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var allottedValue = $(this).parent().find('input').val();
alert('Row id = ' + rowID + ' Enrollment no = ' + allottedValue);
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
// After this line it is not working
$.ajax({
type: "POST",
url: "request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
$(this).parents(".success1").replaceWith(html);
}
});
//$(this).parents(".success1").animate({backgroundColor: "#003"}, "slow").animate({opacity: "hide"}, "slow");
});
// HTML to Show Multiple Inputbox for multiple upload with link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dynamic-table">
<div class="success1">
<input name="enrollNo" type="text" value="" class="postEnroll"/>
<br/>
Allot Enrollment No
</div>
</div>
You are trying to replace with parent, it must be child. Use below code
success: function (html) {
$("#dynamic-table .success1").replaceWith(html);
}
OR
success: function (html) {
$("#dynamic-table").find(".success1").replaceWith(html);
}
This code works great i have used similar.... try this one..
function FormSubmit() {
$.ajax(
type: "POST",
url: 'success1.php',
data: $("#attend_data").serialize(),
async: false
}).done(function( data ) {
$("#attend_response").html(data);
});
}
I have updated your code snippet below... tested offline and the code is working:
A few pointers:
Instead of this: request/allot_enrollmentNo_gov.php
Try this: /request/allot_enrollmentNo_gov.php
Notice the forward slash ( / ) This indicate that the Ajax path must start from the root directory depending on your server settings.
Use this: $(".success1").html(html); instead of $(this).parents(".success1").replaceWith(html);
Working code below:
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var allottedValue = $(this).parent().find('input').val();
alert('Row id = ' + rowID + ' Enrollment no = ' + allottedValue);
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
// After this line it is not working
$.ajax({
type: "POST",
url: "/request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
$(".success1").html(html);
alert('Response from the POST page = ' + html + ');
}
});
//$(this).parents(".success1").animate({backgroundColor: "#003"}, "slow").animate({opacity: "hide"}, "slow");
});
// HTML to Show Multiple Inputbox for multiple upload with link
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="dynamic-table">
<div class="success1">
<input name="enrollNo" type="text" value="" class="postEnroll"/>
<br/>
Allot Enrollment No
</div>
</div>
Now it is working Perfectly by setting parent:
$("#dynamic-table").on("click", ".submit", function () {
var rowID = $(this).attr("id");
var rowParent = $(this).parent('.success1');
var allottedValue = rowParent.find('input').val();
var dataString = 'allottedEnroll=' + allottedValue + '&rowid=' + rowID;
$.ajax({
type: "POST",
url: "request/allot_enrollmentNo_gov.php",
data: dataString,
success: function (html) {
rowParent.replaceWith(html);
}
});
return false;
});

Typeahead input field and query passed to PHP with AJAX

I am using Twitter Bootstrap Typeahead for an autocomplete field.
End state goal: The user first enters details into field 1. When they enter details in field 2, ajax passes the query as it is written to a PHP file which queries a database based on what was also entered into field 1.
How do I pass both the query from field 2 and the contents of field 1 to the PHP file and access them.
Here is what I have so far:
HTML FILE:
<div class="field1">
<input type="text" id="field1" data-provide="typeahead" name="field1">
</div>
<div class="field2">
<input type="text" id="field2" data-provide="typeahead">
</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/bootstrap.js"></script>
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
PHP FILE:
if (isset($_POST['query'])) {
$db_server = mysql_connect("localhost", "root", "root");
mysql_select_db("db_test");
$query = $_POST['query'];
$other = '**This needs to be field 1**';
$sql = mysql_query("SELECT * FROM table WHERE row1 LIKE '%{$query}%' AND row2 = '$other'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['row1'];
}
echo json_encode($array);}
At the moment, the query part works perfectly and the results are returned (the console also displays the value from 'Field1'. Just need to get that value into the php file at the same time!
Any help would be great
If I understood this correctly, you want to parse both the values of field 1 and 2 to the same AJAX call. This is how you do it.
<script>
$(function() {
$("#field2").typeahead({
source: function(query, process) {
var textVal=$("#field1").val();
$.ajax({
url: 'field2.php',
type: 'POST',
data: 'query=' + query + '&field1=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
Now you just make another $_POST['field1'] in your PHP file.
var userQuery = $('#ID of query input element').val();
var field1 = $('#ID of input 1 element').val();
$.ajax({
type: "POST",
url: '',
data: {query: QueryVariable, input1: input1variable},
success: function(data) {
// code within this block
},
error: function() {
alert('System Error! Please try again.');
},
complete: function() {
console.log('completed')
}
}); // ***END $.ajax call

How do I get jQuery/AJAX result into table cell

I have this script here that outputs a result from a sql db query but I can not figure out how to get it to put the result in the table cell specified.
Here is query:
<script type="text/javascript">
$(document).ready(function(){
$('.typeval').change(function(){
var movement = $(this).val();
var client_id = $(this).parent().siblings().find('.clientval').val();
var class_id = <? echo $class_id; ?>;
$.ajax({
type: "POST",
url: "movement_count.php",
data: {movement:movement, client_id:client_id, class_id:class_id},
dataType: "json",
success:(function(output) {
$.each(output, function(index, value){
alert(value);
$(".count").append(output[value]);
}) // each
}) // success
}); // ajax
}); // .typeval
}); // document
</script>
I want to put the result of this (value):
alert(value);
into here:
<td><label class="count"></label></td>
The <td> I am targeting on the same row as the <select> menu that is triggering the result. There will also be multiple table rows with this exact same cell <td>. So I need to target the <td> on this row only somehow. Can someone help me with this? Im not sure if I need the $.each but my php query is a mysql_fetch_row array even though the value returned will always be just one number.
Here is the HTML markup for the table cell I need the value in:
<td><label class="count"></label></td>
JS source code for class=count:
$(".count").append(output[index]);
ITS WORKING!!!! here is the code below
$(document).ready(function(){
$('.typeval').change(function(){
var movement = $(this).val();
var client_id = $(this).parent().siblings().find('.clientval').val();
var class_id = <? echo $class_id; ?>;
$count = $(this).parents('tr').find('label.count');
$.ajax({
type: "POST",
url: "movement_count.php",
data: {movement:movement, client_id:client_id, class_id:class_id},
dataType: "json",
success:(function(output) {
$.each(output, function(index, value){
//alert(value);
$count.append(output[index]);
}) // each
}) // success
}); // ajax
}); // .typeval
}); // document
Replace this
$("label.count<?php echo $client_id; ?>").append(output[value]);
With
$("label.count<?php echo $client_id; ?>").append(value);
Or alternately with this
$("label.count<?php echo $client_id; ?>").append(output[index]);
Hope this will help !!
Working code:
$(document).ready(function(){
$('.typeval').change(function(){
var movement = $(this).val();
var client_id = $(this).parent().siblings().find('.clientval').val();
var class_id = <? echo $class_id; ?>;
$count = $(this).parents('tr').find('label.count');
$.ajax({
type: "POST",
url: "movement_count.php",
data: {movement:movement, client_id:client_id, class_id:class_id},
dataType: "json",
success:(function(output) {
$.each(output, function(index, value){
//alert(value);
$count.append(output[index]);
}) // each
}) // success
}); // ajax
}); // .typeval
}); // document

passing ajax varabiles

i have been looking around to try and work out how to pass 2 variables arcoss the page thru ajax i have at this moment a page where a check box dynamailcy saves its value to the database on the click of it but i need it to be able to only edit rows with a certian id at thi moment i have gotten this far but i am stuck. any help would be greatly appricated
$(function()
{
$("input[type='checkbox']").on('click', function(){
var chkName = $(this).attr('checked');
if($(this).is(":checked")) {
var checkVal = $(':checkbox[checked='+chkName+']').attr('value');
}
else{
var checkVal =$("#frm input:checkbox").attr("id");
}
var userid = $(':checkbox[checked='+chkName+']').attr('name');
$.ajax({
type: "GET",
url: 'request.php?uname=' + checkVal '&id'= + userid ,// this is where i cant send the &id varible across but i can send the checkVal
success: function(data) {
if(data == 1){//Succues
alert('Data was saved in db!');
}
if(data == 0){//Faliure
alert('Data was NOT saved in db!');
}
}
});
});
});
</script>
</head><body>
<div class="content">
<table border="0.02px" class="mytable">
<thead>
<th><strong>Paid</strong></th>
<th><strong>Repaired</strong></th>
<th><strong>Returned</strong></th>
</thead>
<tr>
<form id="frm" name="frm">
<td><input type="checkbox" value="Paid" id="Waiting on Payment" name="29" /></td>
<td><input type="checkbox" value="Repaired" id="Waiting on Repairs" name="uname" /></td>
<td><input type="checkbox" value="With Student" id="Awaiting Pickup" name="uname" /></td>
</form>
</tr>
</table>
</div>
Below line in your code is incorrect:
url: 'request.php?uname=' + checkVal '&id'= + userid ,
Should be:
url: 'request.php?uname=' + checkVal +'&id=' + userid,
Also consider using var isChecked = $(this).prop('checked'); to get the checked status of checkbox.
In line var chkName = $(this).attr('checked');, value of chkName would be 'undefined', while the checkbox is unchecked and so as the line
var userid = $(':checkbox[checked='+chkName+']').attr('name');.
If I understand your code correctly, then you may try this:
$("input[type='checkbox']").on('click', function() {
var $this = $(this);
var isChecked = $this.prop('checked');
var checkVal = isChecked ? $this.attr('value') : $this.attr("id");
var userid = $this.attr('name');
$.ajax({
type: "GET",
//url: 'request.php?uname=' + checkVal '&id' = +userid,
url: 'request.php?uname=' + checkVal +'&id=' + userid,
// this is where i cant send the &id varible across but i can send the checkVal
success: function(data) {
if (data == 1) { //Succues
alert('Data was saved in db!');
}
if (data == 0) { //Faliure
alert('Data was NOT saved in db!');
}
}
});
});
Currently there is an error with the url variable you are trying to send
Current:
url: 'request.php?uname=' + checkVal '&id'= + userid,
Corrected:
url: 'request.php?uname=' + checkVal + '&id=' + userid,
I think you are looking for .serialize from jquery.
You can check the api here. It has the example as well. Please go through the example how to pass serialized data.
Later in server end, you can have $_POST['<your input name here>'] to get the value.
In addition, I see you try to get back the value from server. You can always echo json_encode(<your data object here>) to send to server end.

Categories