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.
Related
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);
});
I am working in codeigniter. I have created one table and its html is like this:
<table>
<tr>
<td>
<center><label style="font-weight:normal" class="t_date"><?php echo date('Y-m-d'); ?></label></center>
</td>
<td>
<center><label style="font-weight:normal" class="b_id"><?php echo $result[0]->branch_id; ?></label></center>
</td>
</tr>
<tr>
<td></td>
<td><input type="button" onClick="window.print();" value="Print" name="print" id="print"/></td>
</tr>
</table>
Now I want to get the value of td so I have written jQuery like this:
<script>
jQuery(document).ready(function(){
jQuery("#print").click(function(){
//alert(123);
var to_date = jQuery(".t_date").text();
var to_date = jQuery(".b_id").text();
});
});
</script>
And I got value of it. Now i want to insert these all value into database so what code should i have to write?
jQuery(document).ready(function () {
jQuery("#print").click(function () {
alert(123);
var to_date = jQuery(".t_date").text();
var to_id = jQuery(".b_id").text();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/controller/function",
data: {to_date: to_date, to_id: to_id},
success: function (html) //we're calling the response json array 'permissions'
{
// action
}
});
});
});
this ajax will call your function in controller.. in your function call a model function to insert the values to db.
you can do so using AJAX.
Create a webpage to accept inputs as parameters and save them into database.
And study this link: http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
code to do so:
$.get("web page address with parameters ", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
For example: if you created a webpage named "savedata.php" that takes inputs as parameters and saves into database.
Then
$.get("[root_path]/savedata.php?[paramaters]", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
[root_path] is the root path of you webpage and [parameters] is "&" separated parameters.
Refer - AJAX
<script>
jQuery(document).ready(function () {
jQuery("#print").click(function () {
$.ajax({
url: '/path/to/file',
type: 'default GET (Other values: POST)',
dataType: 'default: Intelligent Guess (Other values: xml, json, script, or html)',
data: {
t_date: jQuery(".t_date").text(),
b_id: jQuery(".b_id").text(),
},
success: function (response) {
alert(response);
}
});
});
});
</script>
this will do the work
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;
});
Im trying to send the values of multiple select box to a mail/check script with ajax
But when the variable reaches the php script the array lost its first record and i cant find how
jQuery(function() {
var paraTag = jQuery('input#submit').parent('div');
jQuery(paraTag).children('input').remove();
jQuery(paraTag).append('<input type="button" name="submit" id="submit" class="btn btn-default btn-lg" value="Verstuur" />');
jQuery('#contact-form input#submit').click(function() {
jQuery('#contact-form').append('<img src="images/loading.gif" class="loaderIcon" style="width:100px; margin:-20px;" alt="Loading..." />');
var name = jQuery('input#name').val();
var adres = jQuery('input#adres').val();
var woonplaats = jQuery('input#woonplaats').val();
var email = jQuery('input#email').val();
var postcode = jQuery('input#postcode').val();
var bedrijf = jQuery('input#bedrijf').val();
var comments = jQuery('textarea#comments').val();
var tel = jQuery('input#tel2').val();
var hidden = jQuery('input#hidden2').val();
var over_select = jQuery('#over').serialize();
console.log(over_select);
jQuery.ajax({
type: 'post',
url: 'sendEmail.php',
data: 'hidden=' + hidden + '&over=' + over_select + '&post=' + postcode + '&plaats=' + woonplaats + '&adres=' + adres +'&name=' + name + '&email=' + email + '&tel=' + tel + '&bedrijf=' + bedrijf + '&comments=' + comments,
success: function(results) {
jQuery('#contact-form img.loaderIcon').fadeOut(1000);
jQuery('#response').html(results);
}
}); // end ajax
});
In the mail script i put "over" in a php variable and when i print_r() it, it lost its first selection.
Can you please help me out?
Try sending your data like this
jQuery.ajax({
type: 'post',
url: 'sendEmail.php',
data : {'hidden': hidden, 'over': over_select, 'post': postcode, 'plaats': woonplaats, 'adres': adres,'name':name,'email': email, 'tel': tel, 'bedrijf':bedrijf, 'comments': comments},
success: function(results) {
jQuery('#contact-form img.loaderIcon').fadeOut(1000);
jQuery('#response').html(results);
}
}); // end ajax
Then in the php part use
url_decode($_POST['over_select']);
If you run .serialize() on your multiple select it will return something like this:
over[]=Val1&over[]=Val2
Your data string then becomes:
over=over[]=Val1&over[]=Val2
Which is probably your problem. Try removing the "over=" in your data string.
What I'm trying to do is to edit mysql records using php. I've used Ajax/Json to edit a single record, but the problem is my codes isn't working. I tried to alert the value of input element after I clicked the save button and the alert output is verified. And also I don't get any message in console.
Here's what I got right now. Any help will appreciate.
Index.php
<div class="entry-form1">
<form action="" method="post">
<input type="text" name="id_edit" id="id_edit" class="inputs_edit">
<input type="text" name="approved_edit" id="approved_edit" class="inputs_edit">
<input type="submit" name="save_edit" id="save_edit" value="Save"/>
</form>
</div>
Search.php
$query1 = $mysqli->query(""); // not to include
while($r = $query1->fetch_assoc()){
<td><a href='#' name='".$r['id']."' id='".$r['pr_id']."' class='edits'>Edit</a></td>
}
<script>
$(document).ready(function(){
$(".edits").click(function(){
$(".entry-form1").fadeIn("fast");
//not to include some parts of codes
$.ajax({
type: "POST",
url: "auto-complete.php",
data :edit_post_value,
dataType:'json',
success:function(data){
var requested=data.requested;
var id=data.id;
//send to element ID
$('#id_edit').val(id);
$('#requested_edit').val(requested);
}
});
$("#save_edit").click(function () {
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data))
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});
</script>
Item_edit.php
<?php
$mysqli = new mysqli("localhost", "root", "", "app");
if(isset($_POST['id_edit'])) {
$id_edit= $_POST['id_edit'];
$requested_edit= $_POST['requested_edit'];
$sql = $mysqli->query("UPDATE pr_list SET requested='$requested_edit' WHERE id='$id_edit'");
if($sql){
echo json_encode(array( "success" => "1"));
}else{
echo json_encode(array("success" => "0"));
}
}
?>
1) First, you're not capturing the click event, because $("# save_edit") is within a function that is not being called. So, you're not even sending the form to the server.
2) Second, the way a form works by default send the data and then reload the page, you must call the preventDefault() function from the event object captured to prevent it, before making the ajax call.
try this:
$(document).ready(function(){
$("#save_edit").click(function (e) {
e.preventDefault(); //prevent a page reload
var two = $('#id_edit').val();
var five = $('#requested_edit').val();
alert(five);
$.ajax({
type: "POST",
url: "/item_edit.php",
data: "id_edit="+two+"&requested_edit="+five,
dataType:'json',
success: function(data){
console.log(JSON.stringify(data));
if(data.success == "1"){
$(".entry-form1").fadeOut("fast");
//setTimeout(function(){ window.location.reload(); }, 1000);
}
}
});
});
});