Working with checkbox which is creating by Ajax - php

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

Related

Set input value upon select option in php

I have a form where I am selecting a product. On the basis of the selected product, I want to update the rest of the fields in the form.
The Form display with select option
On selecting the product name, I want rest of the details of the form to fill up from the database using php.
Here is the code for the table created.
<table id="productTable" class="table-c">
<tr>
<th class="text-center" style="width: 5%;">SR No.</th>
<th class="text-center" style="width: 45%">DESCRIPTION</th>
<th class="text-center" style="width: 10%">HSN/SAC</th>
<th class="text-center" style="width: 10%">QTY IN-HAND</th>
<th class="text-center" style="width: 10%">ENTER OUTWARD QTY</th>
<th class="text-center" style="width: 5%">Delete</th>
</tr>
<tr style="text-align: center;" id="products">
<?php $j=0; $j++; ?>
<td><?php echo $j; ?></td>
<td><select class="form-control" name="code" id="productID" style="width: 429px;">
<?php
$sql = "SELECT * FROM `product`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option id='".$row['code']."' value='".$row['pname']."'>".$row['pname']."</option>";
}
} else {
echo "0 results";
}
?>
</select>
</td>
<td><input type="number" name="hsnNo" id="hsnNo" readonly></td>
<td><input type="number" name="qty" id="qty" readonly></td>
<td class="coljoin"><input type="number" format="2" name="amount"></td>
<td>
<span class="fa fa-trash"></span>
</td>
</tr>
</table>
How should I do this?
This is PHP Code:-
<form>
<select name="customer" id="customer_id">
<option value="">-- Select customer Name -- </option>
<option value="1">John</option>
<option value="2">Smith</option>
</select>
Address: <input name="add" type="text" value="">
Mobile: <input name="mobile" type="text" value="">
EMail-Id:<input name="email" type="text" value="">
</form>
This is JS Code:-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#customer_id").change(function() {
var id = $(this).val();
var dataString = 'cid='+id;
//alert(dataString);
$.ajax({
url: 'dataAjax.php',
type: 'post',
data: dataString,
success: function(response) {
// Parse the jSON that is returned
var Vals = JSON.stringify(response);
// These are the inputs that will populate
$("input[name='add']").val(Vals.add);
$("input[name='mobile']").val(Vals.mobile);
$("input[name='email']").val(Vals.email);
}
});
});
});
</script>
This is other PHP File Code:-
<?php
// This is where you would do any database call
if(!empty($_POST)) {
// Send back a jSON array via echo
echo json_encode(array("add"=>'India',"mobile"=>'1234567890','email'=>'demo#demo.com'));
}
?>
using product id use ajax & call the get_product_details(id) & in get product convert response array in json & echo it .in ajax, response data you have to parse in json... then set you required field.. (add require js)
**Ajax Call :**
$(document).on('change','your_dropdown_filed_id',function()
{
var product_id = $(this).val();
//Ajax call
$.ajax({
method: "POST",
url: "/get_product_details", //your php file function path
data: { product_id: product_id}
}).done(function( response ) {
alert( "Data Saved: " + response );
var obj = JSON.parse(response);
//obj hold all values
alert(obj.qty);
alert(obj.hsn);
$('#hsn_id').val(obj.hsn);
$('#qty_id').val(obj.qty);
});
});
**product.php**
function get_product_details(product_id)
{
//Get product details in associative array format
echo json_encode($product_details);
}
Once the product is selected execute ajax request and get data from the database with respective of the selected product.
JAVASCRIPT CODE :
$('#products').change(function(){
$.ajax({
url: 'your php code page name which returns product details.php?product_id'+$('#products').val(),
type: 'post',
success: function(response) {
var obj = JSON.parse(response);
$("#hsn_sac").val(obj.hsn_sac); // hsn or sac values
$("#qty_in_hand").val(obj.qty_in_hand); // qty_in_hand values
}
}});
});
PHP CODE :
<?php
// first connect database and then fire the query to get product details
$connection = mysql_connect("your database host name","database username","database password","database name");
$result = mysql_query("your query");
while ($row = mysql_fetch_array($result)) {
// get data and store in array
}
mysql_close($connection); // close connection
echo json_encode(database result); // encode database result so that it will available to ajax request and assign back to view
exit;
?>

query Fetch data from multiple tables MySQL

i have a page on which there is a form, in which there are two radio buttons, on selected the on of the related buttons, it's related content will be shown on the form.
<tr class="text">
<td colspan="4" valign="top" bgcolor="f2f2f2">
<?php
$srl=mysql_query("select * from module ORDER BY module_id ASC");
while($rows=mysql_fetch_array($srl))
{ ?>
<input type="radio" name="module" value=<?php echo $rows[module_id] ?>><?php echo $rows[module_name] ?>
<?php
}
?>
</td>
</tr>
</tbody>
</table>
<tr class="text">
<td colspan="6">
<div id="items_list"></div>
</tr>
and i have write this jquery for api calls.
<script type="text/javascript">
$(function() {
$("module").change(function() {
var module_id = $(this);
var dataString = 'module_id='+ module_id.val();
alert(dataString);
$("#items_list").html("");
if(module_id.val()=='')
{
alert("select stock type");
}
else {
$.ajax({
type: "POST",
url: "ajax/request_fetch_items.php",
data: dataString,
cache: false,
success: function(){
$("#items_list").html( html );
},
error:function (xhr, ajaxOptions, thrownError){
//On error, we alert user
alert(thrownError);
}
});
}
return false;
});
});
</script>
but nothing happens when i select any radio button, neither it shows the alert in jquery.
what i want is whenever a radio button is selected, its value is passed via ajax call, the the remaining html content will be load into the next row.
On inepcting the radio buttons it shows following code,
<input type="radio" name="module" value="1">Stationary
<input type="radio" name="module" value="2">Inventory
Your jQuery selector $("module") is targeting <module> html tags, just change it to $("input[name=module]:radio") so it targets <input> elements of type radio named module.
https://jsfiddle.net/eh6c5wjb/

Get data from php-foreach-loop to ajax

I have searched very long for a solution to this problem but could not find any.
I get data from the database to show some projects on my website. For each project i can click on a pen-symbol to edit the name of the project. I´d like to send the date per ajax request, but always get the data of the first project. If i try for example to edit the name of the second project "test", i get the data of the first project "blubb"
What i have tried:
- Used classes not Id´s
Call Ajax function from PHP foreach with form
- Used $this
Get Ajax variable from the PHP foreach loops
My code lookes like this (simplified):
< script type = "text/javascript" >
$(document).ready(function() {
$(".submit").click(function() {
//here are the problems, i only get the value of the first project
var new_project_name = $('.new_project_name').val();
var old_project_name = $('.old_project_name').val();
$.ajax({
type: "POST",
url: "php/edit/edit.php",
data: {
old_project_name: old_project_name,
new_project_name: new_project_name,
name: name
},
}).
done(function(response) {
blabla
});
});
}); < /script>
<?php foreach($db->query('SELECT * FROM portfolio ORDER BY position, id desc') as $row) { $name = $row['name']; ?>
<div class="rename">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td>Projektname:</td>
</tr>
<tr>
<td>
<input type="text" class="new_project_name" value="<?php echo $name;?>">
</td>
<input type="text" class="old_project_name" value="<?php echo $name;?>" hidden>
</tr>
<tr>
<td>
<input class="submit" type="submit" value="Umbenennen">
</td>
</tr>
</table>
</div>
<?php } ?>
Thank you for any help.
you could pass the id of the project to ajax and update the new value. For that you just need to pass the id of the element.
HTML
<input type="text" class="new_project_name" value="<?php echo $name;?>" rel="<?php echo $id; ?>">
jQuery
$(document).ready(function() {
$(".submit").click(function() {
var parentObj = $(this).closest('.rename');
var id = parentObj.find(' .new_project_name').attr('rel');
var project_name = parentObj.find(' .new_project_name').val();
$.ajax({
type: "POST",
url: "php/edit/edit.php",
data: {
project_name : project_name ,
id:id
},
}).
done(function(response) {
blabla
});
});
});
See the Fiddle and check console
http://jsfiddle.net/hoja/2caukhvo/11/

data received through JQuery, php, mysql is not working

On entering the customer name in textbox it searches for customer info. I have generated successfully using JQuery by passing the entire table through Json variable, as I dont want any page refresh. Now I want to select the customer id generated from mysql db (php) through radio button, but the radio button event is not working. For testing purpose I have put a static table having the same radio button properties in that particular div(place for dynamic record generation using JQuery) and working fine. Hence I found that the data received through JQuery got some problem. Hope I am clear. Please find a way. Thanks in advance.
below is the code
abc.php
<input type="text" placeholder="full name" id="fullName" name="fullName" class="txt" style="width: 250px" /> 
<input type="button" id="btSelect" value="Select" class="button-crystal" />
<div id="disp"></div>
script.js
$('#btSelect').click(function () {
var form_data = {
genCustDetails: $('#fullName').val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: "xyz.php",
data: form_data,
dataType: "json",
success: function (response)
{
$('#disp').html(response);
}
});
return false;
});
xyz.php
if (isset($_POST['genCustDetails'])) {
$out="";
$result = mysql_query("select * from dbcustdetails where name like '$_POST[genCustDetails]%'");
while ($row = mysql_fetch_assoc($result)) {
$out.='
<table style="background-color:#eee; margin-bottom:5px;">
<tr>
<th class="td3">Customer ID</th>
<td class="td4">
'.$row["custID"].' <input type="radio" id="cust_ID" name="cust_ID" value="'.$row["custID"].'" />
</td>
</tr>
<tr>
<th class="td3">Name</th>
<td class="td4">'.$row["name"].'</td>
</tr>
<tr>
<th class="td3">Phone No.</th>
<td class="td4">'.$row["phno"].'</td>
</tr>
<tr>
<th class="td3">Email</th>
<td class="td4">'.$row["email"].'</td>
</tr>
<tr>
<td colspan="2" style="padding:0;">
<b>Address</b><br/>'.$row["addr"].'
</td>
</tr>
</table>';
}
echo json_encode($out);
}
Maybe You should'nt bind the event properly for the dynamic elements in the DOM.
Try Like this
$('body').on('change','.radiobuttonClassorID',function(){
//actions
});
that is because your newly generated radio button is not having any event handler assigned to it.
you have to assign an event handler after the ajax call (on ajax success).
something like
$('input[type="radio"]').unbind('click').click(function(){
//Your handler code
})

jquery dynamic added row display price form db on each row select option

Hi i need some help in jquery task, i created table with dynamic row add. i want when i select option value this price display in this row next column, ever select option value will be different in each row
my code is here
<script type="text/JavaScript">
$(".name").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "test.php",
data: dataString,
cache: false,
dataType:"json",
success: function(data)
{
$(".price").val(data.price);
return false;
}
});
});
</script>
HTML:
<table>
<tr>
<th>
select item
</th>
<th>
price
</th>
</tr>
<tbody>
<td>
<select name="item[]">
<option value="1">
item name
</option>
</select>
</td>
<input type"text" name="price[]">
<td>
</td>
</tbody>
</table>
From the picture it looks like you would several dropdowns with textbox next to it and you want to load the price of each item separately, for that you need to do things:
Change
$(".name").change(function()
to
$("select[name^='item']").change(function()
This means to target a select tag which has name starting with item.
Change
$(".price").val(data.price);
to
$(this).closest('tr').find("input[name^='price']").val(data.price);
This means we find the closest tr tag of the select and then find an input with name starting from price within the tr tag, so your select dropdown value always get stored in the next textbox.
DEMO (This link is just to give you an idea of how it works and AJAX is commented because JSFiddle will not run it).
With, dynamic rows, you should use .on method. Adding some classes to the elemens for esealy find them.
This code should work:
<table id="unit-price">
<tr>
<th>
select item
</th>
<th>
price
</th>
</tr>
<tbody>
<tr>
<td>
<select class="name" name="item[]">
<option value="1">item name</option>
</select>
</td>
<td>
<input type="text" class="price" name="price[]">
</td>
</tr>
</tbody>
</table>
<script type="text/JavaScript">
$("#unit-price").on('change', '.name', function () {
var $this = $(this);
$.ajax({
type : "POST",
url : "test.php",
data : {
id : $this.val()
},
cache : false,
dataType : "json",
success : function (data) {
$this.parent()
// Get parent tr
.closest('tr')
// Then, find price textbox with class 'price'
.find('.price').val(data.price);
}
});
});
</script>
I think you could solve your problem using jQuery's nextUntil() function.
In your case, you could call $(this).nextUntil(".price").val(data.price);
I'm not too sure on this one so let us know if this works.

Categories