Using ajax on select change for multiple selects - php

I have a table row where I added the ability to add/remove using .clone and .remove
I also have an ajax call to my controller in code igniter to grab the data and populate the other inputs based on data.
It currently works one the first one, I am able to select an option from the dropdown and it fills the values of the neighboring inputs. My problem is when I click add and it successfully clones the row, when I change that dropdown its like the .change and .ajax events no longer work.
Here is my jQuery which is here I think I am having the problem:
$('.invoice_line_item').each(function(){
$(this).change(function(){
var table = $(this).closest('.tr_clone');
var select_value = $(this).val();
//alert(item_id + ' ' + select_value);
console.log(item_id + select_value);
$.ajax({
url: '<?php echo site_url("Invoice_item/get_item"); ?>',
type: 'POST',
dataType: "JSON",
data: ({'id' : select_value}),
success: function (data, status)
{
//alert('Success ' + data);
console.log(data);
$(table).find('.description').val(data['work_description']);
$(table).find('.amount').val(data['amount']);
$(table).find('.quantity').val(data['quantity']);
$(table).find('.price').val(data['amount']);
},
error: function (data, xhr, desc, err)
{
alert('An Error Occurred: ' + xhr + ' ' + desc + ' ' + err);
console.log(data);
}
});
});
});
Here is the HTML:
<tbody>
<tr class="tr_clone" id="inv_line_1">
<td>
<select id="line_item_1" name="invoice_line_item" class="invoice_line_item">
<option></option>
<?php
foreach($prefix_line_items as $line_item)
{
?>
<option value="<?php echo $line_item['id']; ?>"><?php echo $line_item['item']; ?></option>
<?php
}
?>
</select>
</td>
<td><input type="text" id="description_1" name="description" class="description" value="" /></td>
<td><input type="currency" id="amount_1" name="amount" class="amount" value="" /></td>
<td><input type="number" id="quantity_1" name="quantity" class="quantity" value="" /></td>
<td><input type="currency" id="price_1" name="price" class="price" value="" readonly/></td>
<td><i class="fa fa-plus"></i> <i class="fa fa-minus"></i></td>
</tr>
</tbody>
No errors in console, works the first time for the first row but when I click the Add button and it duplicates the row, I change the (cloned) select element and its like the jQuery no longer fires so it isnt grabbing the data via ajax or printing to the console.

While cloning the element, by default, it does not copy the event handlers to new elements. For that you have to pass true to tell clone method to do so.
Good practice is to clone the element and then copy only required events manually to the new element.
Check below example given on jquery's website,
/ Original element with attached data
var $elem = $( "#elem" ).data( "arr": [ 1 ] ),
$clone = $elem.clone( true )
Hope it helps..

Related

Change specific dynamically created table row html and text from ajax response

From the database, I have a dynamic table like this:
<table>
<?php
$query = ....;
foreach ($query as $row) {
echo '<tr>';
echo '<td>' . ' <span class="bName">' . $row['brand_name'] . '</span>'.
'<input name="product_id" type="number" value="' . $row['product_id'] . '">'.
'<input name="company_id[]" type="number" value="' . $row['company_id'] . '">'.
'<button name="exchange" type="button">Click Me!</button></td>';
echo '</td>';
echo '</tr>';
}
?>
</table>
It returns say 4 rows with brand_name inside the <span> and product_id inside an <input>. The exchange button on click calls an ajax request that query another random brand_name and returns the query as JSON like this:
{product_id: '2206', brand_name: 'New name', company_id: '234' }
The script for ajax is
<script>
$(document).ready(function() {
$('button[name="exchange"]').click(function() {
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$('.bName').html(data.brand_name); // Problem is here
$('.company_id').html(data.company_id); // and here
console.log(data);
},
});
});
});
</script>
My target is to change the brand_name inside class bName and company_id value with the new values from ajax response for that specific row. But my problem is it changes all the spans with bName class and all the inputs with class company_id. What should be the best approach to change the specific row of that table from the ajax data?
Store a reference to the cell that the button that was actually clicked exists in so you can find within that cell the specific elements.
Also note that the company_id value is in an input thaat you ned to use val() on and you need to give it a class name
$('button[name="exchange"]').click(function() {
// cell this button instance is in
const $cell = $(this).closest('td');
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
$cell.find('.bName').html(data.brand_name); // Problem is here
$cell.find('.company_id').val(data.company_id); // and here
console.log(data);
},
});
});
Unable to test using AJAX but perhaps this might help. Use the event of the click function to find the parentNode and from that use querySelector to target the particular elements in the table row.
$(document).ready(function() {
$('button[name="exchange"]').click(function(e) {
let tr=e.target.parentNode;
let span=tr.querySelector('span.bName');
let pid=tr.querySelector('input[name="product_id"]');
let cid=tr.querySelector('input[name="company_id[]"]');
console.info( span.textContent, cid.value, pid.value)
$.ajax({
url: 'ajaxChangeBrand.php',
type: 'POST',
data: 'keyword=' + $(this).parent().find('input[name="product_id"]').val(),
success: function(response) {
var data = JSON.parse(response);
span.textContent=data.brand_name;
cid.value=data.company_id;
pid.value=data.product_id;
},
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>
<span class="bName">Womble</span>
<input name="product_id" type="number" value="23">
<input name="company_id[]" type="number" value="88">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Bagpuss</span>
<input name="product_id" type="number" value="39">
<input name="company_id[]" type="number" value="12">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
<tr>
<td>
<span class="bName">Clanger</span>
<input name="product_id" type="number" value="47">
<input name="company_id[]" type="number" value="91">
<button name="exchange" type="button">Click Me!</button>
</td>
</tr>
</table>

Working with checkbox which is creating by Ajax

I am working with ajax project.
I have a form of user in with name, address , postcode .
on entering the name, address or postcode the matching rows is shown by ajax file in .
so on select the checkbox i want to do some further activity.
my html code is
Address : <input type="text" name="user_name" id="from_location" value="" class="in_form" />
<div id="user"></div>
and jQuery code is
$.ajax({
url: "ajax_user.php",
data: {
address: address,
},
dataType: "html",
type: "POST",
success: function(result){
$("#user").append(result);
}
})
}
and ajax user php is
$sql= "SELECT * FROM instructor_mst WHERE sex='$sex' AND car_type='$car_type' AND address Like '%$address%' ";
if (!$sqli=mysql_query($sql)){
echo mysql_error();
}
$num_rows= mysql_num_rows($sqli);
if($num_rows != 0)
{?>
<table border="0" class="form_ins" >
<?
while ($row = mysql_fetch_array($sqli))
{
?>
<tr>
<td>
</td>
<td>
Name
</td>
<td>
Address
</td>
</tr>
<tr>
<td>
<input type="checkbox" name="select" value"<?php echo $row['id'];?>">
</td>
<td>
<?php echo $row['name'];?>
</td>
<td>
<?php echo $row['address'];?>
</td>
</tr>
</table
<?}
in result i got like
checkbox | user name | address
now on selecting the checkbox i want to submit for other activity....
I am not getting how can i do this...All answer will be appreicieted
As your checkbox being dynamically added -
$(document).on('change','input[type=checkbox]',function(){
if($(this).is(':checked')){
// do something
}
});
Or if you have an ID of your checkbox -
$(document).on('change','#checkBoxID',function(){
if($(this).is(':checked')){
// do something
}
});
you need to delegate the click event using on for dynamically added element which is checkbox in your case
$(document).on('click','input[name="select"]',function(){
//this is called when you select the checkbox
//do your stuff
})
or delegating it to the closest static element
$('#user').on('click','input[name="select"]',function(){
//dou your stuff
});
updated
checkbox might have multiple values so to get all the values that is checked you need to loop through the values or use map()
try this
$('#user').on('click','input[name="select"]',function(){
var selectedValue = $("input[name='select']:checked").map(function(n){
return this.value;
});
console.log(selectedValue ); //this will print array in console.
alert(seletedValue.join(',')); //this will alert all values ,comma seperated
});

Doing an ajax call to a php page

I have this star rating, I implemented from jQuery and I need to save the comments, the user id and the value of the star clicked. What I do not know is how to pass that through the ajax call and what the PHP should have at the least to process the call? Here is my code
stars code - as you can see it has a comments box , the stars with star value and the user id is stored in a variable called
$user_id
Here is the code
<tr>
<td style="padding:10px;">
<span style="font-size: 20px; vertical-align:top;">Comments</span>
</td>
<td style="padding:10px;">
<textarea name="comments1" cols="60" rows="2"></textarea>
</td>
<td>
<div>
<input name="star1" value "1" type="radio" class="star"/>
<input name="star1" value="2" type="radio" class="star"/>
<input name="star1" value="3" type="radio" class="star"/>
<input name="star1" value="4" type="radio" class="star"/>
<input name="star1" value="5" type="radio" class="star"/>
</div>
</td>
<tr>
The ajax call - This is the attempted call to the page where I am sending the request, but how can I include the comments and user id on this call?
$('.star').rating({
callback: function(value, link) {
var name = $(this).attr('name');
$.ajax({
url: "ajax.php",
data: "name=" + name + "&value=" + value,
cache: false,
success: function(response) {
try {
console.log(response);
} catch (err) {
alert(response);
}
}
});
}
});
Now, ajax.php has variables $passed_user_id, $passed_comments, $passed_ratingval. How am I retrieving these values when the call is triggered in php? something like
$passed_comments = //get the value being passed from ajax call
$passed_ratingval = //get the value being passed for the rating value
$passed_user_id = //get the value being passed for the user_id`
I do have all set up, the insert query, connection everything works. I'm just not sure how to make this work with the ajax call.
Kinda hacky, but this will work for you. It also will allow for multiple ratings on one page (which I assume you might be doing considering the TR).
HTML:
<tr>
<td style="padding:10px;">
<input type="hidden" name="userID" value="<?php echo $user_id ?>">
<span style="font-size: 20px; vertical-align:top;">Comments</span>
</td>
<td style="padding:10px;">
<textarea name="comments" cols="60" rows="2"></textarea>
</td>
<td>
<div>
<input name="star1" value "1" type="radio" class="star"/>
<input name="star1" value="2" type="radio" class="star"/>
<input name="star1" value="3" type="radio" class="star"/>
<input name="star1" value="4" type="radio" class="star"/>
<input name="star1" value="5" type="radio" class="star"/>
</div>
</td>
<tr>
JS:
$('.star').rating({
callback: function(value, link) {
var name = $(this).attr('name');
var userID = $(this).closest('tr').find('input[name="userID"]').val();
var comments = $(this).closest('tr').find('textarea[name="comments"]').val();
$.ajax({
url: "ajax.php",
data: "name=" + name + "&value=" + value + "&userID=" + userID + "&comments=" + comments,
cache: false,
success: function(response) {
try {
console.log(response);
} catch (err) {
alert(response);
}
}
});
}
});
Also, if you use POST instead of GET, you can format your ajax call a bit nicer like below. Remember to use $_POST[] in your ajax.php file.
$('.star').rating({
callback: function(value, link) {
var name = $(this).attr('name');
var userID = $(this).closest('tr').find('input[name="userID"]').val();
var comments = $(this).closest('tr').find('textarea[name="comments"]').val();
$.ajax({
url: "ajax.php",
type: "POST",
data: {
name: name,
value: value,
userID: userID,
comments: comments
},
cache: false,
success: function(response) {
try {
console.log(response);
} catch (err) {
alert(response);
}
}
});
}
});
Here is example code of mine, which I use on one project:
jQuery.post("load.php", {
op_type : opType,
xor : xor.toString(),
or : or.toString(),
and : and.toString(),
from : seeds.toString(),
last_id : jQuery("input[type=hidden]:last").val(),
last_update : last_update_time
}, function(data) {
var json = jQuery.parseJSON(data);
if (json.list.length > 0) {
last_update_time = Math.floor(new Date().getTime() / 1000);
jQuery("div#list_content ul.no-list").append(json.list);
}
});
And in PHP to receive data I use:
$_POST['op_type']
and in this manner I get other variables too.
To return something I do like this:
echo json_encode(array("list"=>$html));
So afyer jQuery parses JSON it can get access to $html variable via list property.
So what you need is to specify request type in jQuery and get that request type in PHP. Sending data in JSON is one of the options. jQuery and PHP also support XML, but I didn't worked with it.

jquery post - update db - multiple rows

I'm not sure if what I'm trying to do is simple or not but here it is:
I have rows of data in a table. The last 3 fields are text fields that take user input. Each row has it's own UPDATE button.
I'm using the following code to try and do a jQuery .ajax post but I'm seeing my issue - I'm assigning IDs to my input fields and you can only have one ID declared per page so I'm sure that's one issue.
I'm trying to make it so that when you click the UPDATE button, it passes the variables from that row in the INPUT boxes and the hidden INPUT field for the rowID, and calls a .php file that updates the DB.
$(function() {
$(".submit").click(function() {
var status = $("#status").val();
var ly = $("#ly").val();
var rt = $("#rt").val();
var offerout = $("#offerout").val();
var lineid = $("#lineid").val();
var dataString = 'status='+ status + '&ly=' + ly + '&rt=' + rt + '&offerout=' + offerout + '&lineid=' + lineid;
$.ajax({
type: "POST",
url: "post/updatedata.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
});
and on line of my form (each line is the same but with a different hidden ID variable):
<form method="POST" name="form">
<td>This one</td><td>Los Angeles</td>
<td>CA</td><td>94591</td>
<td>220000</td>
<td>20000</td><td>24500</td>
<td>-5500</td><td>12</td>
<td>0</td><td>0.167</td><td>4</td>
<td>1</td><td>1898</td>
<td></td><td>1</td><td>211335190</td>
<td><input size="6" type="text" id="status" name="status"></td>
<td><input size="6" type="text" id="ly" name="ly"></td>
<td><input size="6" type="text" id="rt" name="rt"></td>
<td><select id="offerout" name="offerout"><option value="No">No</option><option value="Yes">Yes</option></select></td>
<input type="hidden" name="lineid" id="lineid" value="97">
<td><input type="submit" class="submit" value="Update"></td>
</form>
Thanks in advance, been working for days on this!
Duplicating id attributes will cause problems. When you say $("#ly"), you'll probably get the first one on the page and that's usually not the one you want. That's easy to solve:
Drop the id attributes in favor of class attributes. You could also use attribute selectors.
Adjust your jQuery selectors to go up to an ancestor and come back down to the thing you want.
First the HTML:
<td><input size="6" type="text" class="status" name="status"></td>
<td><input size="6" type="text" class="ly" name="ly"></td>
<td><input size="6" type="text" class="rt" name="rt"></td>
<td><select class="offerout" name="offerout"><option value="No">No</option><option value="Yes">Yes</option></select></td>
<input type="hidden" name="lineid" class="lineid" value="97">
Then your jQuery:
var $form = $(this).closest('form');
var status = $form.find(".status").val();
var ly = $form.find(".ly").val();
var rt = $form.find(".rt").val();
var offerout = $form.find(".offerout").val();
var lineid = $form.find(".lineid").val();
Also, since you are doing a POST request, you should just hand jQuery an object and let it worry about serializing it:
var data = {
status: status,
ly: ly,
rt: rt,
offerout: offerout,
lineid: lineid
};
$.ajax({
type: "POST",
url: "post/updatedata.php",
data: data,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
That should take care of your client-side issues.
You could store a row number data variable in each submit and use that to determine which row was clicked and thus which inputs you need to pull values from.
$(function() {
$(".submit").each(function () {
var rowNum = $(this).attr('data-rownum');
$(this).click(function () {
var status = $("#status" + rowNum).val();
var ly = $("#ly" + rowNum).val();
var rt = $("#rt" + rowNum).val();
....
});
});
});
<form method="POST" name="form">
....
<td><input size="6" type="text" id="status1" name="status"></td>
<td><input size="6" type="text" id="ly1" name="ly"></td>
<td><input size="6" type="text" id="rt1" name="rt"></td>
<input type="hidden" name="lineid" id="lineid1" value="97">
<td><input type="submit" class="submit" value="Update" data-rownum="1"></td>
</form>
I remove hidden field and assign database id to update button as button will click get that id and corespondent data.
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<form method="POST" name="form">
<td>CA</td><td>94591</td>
<td>220000</td>
<td>20000</td><td>24500</td>
<td>-5500</td><td>12</td>
<td>0</td><td>0.167</td><td>4</td>
<td>1</td><td>1898</td>
<td></td><td>1</td><td>211335190</td>
<td><input size="6" type="text" id="status_97" name="status"></td>
<td><input size="6" type="text" id="ly_97" name="ly"></td>
<td><input size="6" type="text" id="rt_97" name="rt"></td>
<td><select name="offerout" id="offerout_97"><option value="No">No</option><option value="Yes">Yes</option></select></td>
<td><input type="submit" class="submit" value="Update" name="97"></td>
</form>
</tr>
<tr>
<form method="POST" name="form">
<td>CA</td><td>94591</td>
<td>220000</td>
<td>20000</td><td>24500</td>
<td>-5500</td><td>12</td>
<td>0</td><td>0.167</td><td>4</td>
<td>1</td><td>1898</td>
<td></td><td>1</td><td>211335190</td>
<td><input size="6" type="text" id="status_96" name="status"></td>
<td><input size="6" type="text" id="ly_96" name="ly"></td>
<td><input size="6" type="text" id="rt_96" name="rt"></td>
<td><select name="offerout" id="offerout_96"><option value="No">No</option><option value="Yes">Yes</option></select></td>
<input type="hidden" name="lineid" id="lineid_96" value="96">
<td><input type="submit" class="submit" value="Update" name="96"></td>
</form>
</tr>
</table>
java script code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
$(function() {
$(".submit").click(function() {
var rowToUpdate = $(this).attr('name');
var status = $("#status_"+rowToUpdate).val();
var ly = $("#ly_"+rowToUpdate).val();
var rt = $("#rt_"+rowToUpdate).val();
var offerout = $("#offerout_"+rowToUpdate).val();
var dataString = 'status='+ status + '&ly=' + ly + '&rt=' + rt + '&offerout=' + offerout + '&rowToUpdate='+ rowToUpdate;
$.ajax({
type: "POST",
url: "post/updatedata.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
});
</script>
I hope this will help you..

JQuery .load() removing .sortable() function from sortable list

I will try to explain my problem with as little code as possible.
Basically I have several sortable lists connected in the usual way. Each item in the list has some hidden elements that are toggled with a button on the respective items. There is also a second button that causes the list item to slideUp and be removed from the list - then being sent to a new list. This works in conjunction with an ajax call which when successful uses the .load() function to refresh the receiving sortable list.
The problem: When I use .load() to refresh the receiving sortable list, the new list item is present but the list loses its sort-ability and all the hidden items on each list item are displayed. Any idea why the .load() function removes the interactivity of refreshed page elements?
This is the code to remove an item and refresh a new list:
$(document).ready(function click(){
$(".finished").click(function() {
if (confirm('Are you sure is complete?')) {
$(this).closest(".card").slideUp();
var id = $(this).closest(".card").find(".hiddenid").val();
var machinequantity = $(this).closest(".card").find(".machinequantity").val();
$.ajax({
url: "update_item_machine_complete.php",
type: "POST",
data: "&id="+id+"&machinequantity="+machinequantity,
success: function() {
$('#complete').load('index.php #sortable4')
}
});
}
});
});
Here's an example of the receiving list:
<div id="complete" class="box">
<ul id="sortable4" class="sortable">
<li class="notsortable"><h1>Complete</h1></li>
<?php
include("php/database_connect.php");
$result = mysql_query("SELECT * FROM orders WHERE misc='complete' ORDER BY columnpos ASC ");
while($row = mysql_fetch_array($result))
{
echo'
<li id="id_' . $row['id'] . '">
<div class="card">
<table>
<tr>
<td class="left">' . $row['customer'] . '</td>
<td></td>
<td class="right">' . $row['ponumber'] . '</td>
</tr>
<tr>
<td class="left">' . $row['partnumber'] . '</td>
<td><div class="show"></div></td>
<td class="right">' . $row['quantity'] . ' x Black</td>
</tr>
</table>
<div class="hide">
<p>Quantity Done: <span><input class="machinequantity" type="text" value="' . $row['quantity'] . '" /><input type="submit" value="update" /></span></p>
<p><input class="finished" type="submit" value="Finished" /></p>
<input class="hiddenid" type="hidden" value="' . $row['id'] . '" />
</div>
</div>
</li>
';
}
?>
</ul>
</div>
EDIT: This is the .sortable() code I'm using to record column and position:
$(document).ready(function {
$("#sortable01, #sortable0, #sortable1, #sortable2, #sortable3, #sortable4").sortable({
connectWith : ".sortable",
items : "li:not(.notsortable)",
receive : function(event, ui){
var column = $(this).parent().attr('id');
var index = ui.item.index() + 1;
var id = $("#"+column+" li:nth-child("+index+") .hiddenid").val();
$("#"+column+" li:nth-child("+index+") ").addClass('notsortable');
$.ajax({
url: "update_column.php",
type:"POST",
data: "column="+column+
"&id="+id,
success: function(){
$("#"+column+" li:nth-child("+index+") ").removeClass('notsortable');
}
});
},
beforeStop : function (event, ui) {
$.ajax({
url: "update_column_order.php",
type:"POST",
data: {
sort0:$('#sortable0').sortable('serialize'),
sort1:$('#sortable1').sortable('serialize'),
sort2:$('#sortable2').sortable('serialize'),
sort3:$('#sortable3').sortable('serialize')
}
});
},
})
.disableSelection();
$(".hide").hide();
});
Reinitialize the sortable functionality on the ajax-replaced elements within load's callback:
$('#complete').load('index.php #sortable4', function() {
$('#sortable4').sortable(options);
});
This happens because those elements are completely replaced, you'll need to call .sortable() on the list again...since you're replaced it, for example:
$('#complete').load('index.php #sortable4', function() {
$("#sortable4").sortable();
});

Categories