I am using the jQuery DataTables plugin, it has one event, that on click of button we can add new row in table.
The jQuery code is as below:
$(document).ready(function() {
var t = $('#example').DataTable();
var counter = 1;
$('#addRow').on( 'click', function () {
t.row.add( [
counter,
'<select id="k'+counter+'" name="itemname'+counter+'" ><option>-------</option></select>' ,
'<input id="itemrate" name="itemqty'+counter+'" placeholder="Quantity" type="text">',
'<input id="itemrate" name="itemrate'+counter+'" placeholder="Rate" type="text">',
'<input id="totalamt" name="totalamt'+counter+'" placeholder="Total Amount" type="text">'
] ).draw();
counter++;
});
});
I want to fill data fetched from a MySQL database using jQuery .ajax(), and my code is as follows:
jQuery(document).ready(function(){
jQuery('#k'+counter).click(function(){
jQuery.ajax({
url: 'getData.php',
type:'POST',
data:'form_data='+val,
success:function(results){
jQuery('#k'+counter).html(results);
}
});
});
});
The code for getdata.php is as follows:
<?php
mysql_connect('localhost','root','');
mysql_select_db('eroyalsum');
$sql = "SELECT ITEMCODE,ITEMNAME FROM itemmaster1";
$result = mysql_query($sql);
while($row = mysql_fetch_row($result))
{
echo '<option value="'.$row[0].'" >'.$row[1].'</option>';
}
?>
Finally, my problem is when I write it as separate function, it just works only once. When I add other row it does not work, and when i write jQuery's .ajax() in one function it does not work...
try changing you selector from:
jQuery('#k'+counter).click(function(){
…
to
jQuery(document).on("change", "select[id^='k']", function(){
...
The issue is the event binding.
When you bind the event to the #k elements, the new item doesn't automatically get the event bound to it.
You can use stuff like :
$('body').on('click','.new_elements',function(){ //dostuff});
you can read more about it here
Event binding on dynamically created elements?
Related
I'm loading data from mysql to php with ajax. I want to create edit function for my website. This edit will be on modal.
Select input with options (subcategories) is loading by ajax after radio input categories is loaded with previous ajax.
I've tried several jquery events to change select option, but no one worked.
This is script code in my modal file.
<script>
$(document).ajaxComplete(function() {
$("#editexp'.$poz.'").on("shown.bs.modal", function(){
$("input[name=payment'.$poz.'][value='.$method.']").prop("checked", true);
$("input[name=kategoria'.$poz.'][value='.$catid.']").prop("checked", true);
var category = '.$catid.';
var poz = '.$poz.';
$.ajax({
url:"expense_subcategory_change.php",
method:"POST",
data:{category:category,
poz:poz
},
success:function(data){
$("#subcategory'.$poz.'").html(data);
}
});
$("input[type=radio][name=kategoria'.$poz.']").change(function(){
var category = $(this).val();
var poz = '.$poz.';
$.ajax({
url:"expense_subcategory_change.php",
method:"POST",
data:{category:category,
poz:poz
},
success:function(data){
$("#subcategory'.$poz.'").html(data);
}
});
});
});
});
$("#subcategory'.$poz.'").ajaxComplete(function() {
$("#subcategory'.$poz.' ").find("option").each( function() {
var $this = $(this);
if ($this.val() == '.$subcatid.') {
$this.prop("selected","selected");
return false;
}
});
});
</script>
I've also tried this:
$("#subcategory'.$poz.'").ajaxComplete(function() {
$("#subcategory'.$poz.' option[value='.$subcatid.']").prop("selected","selected");
});
also these two functions without ajaxComplete for #subcategory or with second ajaxComplete for document
Input with options is loading but first option is always selected.
This is main part of my expense_subcategory_change code:
$result = mysqli_query($connection,"$sql_query");
$output .= '<select class="mb-3 w-50-100 " name="subcategory'.$poz.'">';
while($row = mysqli_fetch_array($result))
{
$output .= '<option value="'.$row['id'].'" >'.$row['sub'].'</option>';
}
$output .= '</select>';
echo $output;
The issue is in your selector. You are using 'name' in the select element but using '#' (id) to search the dom for the element. Change your PHP code to:
$output .= '<select class="mb-3 w-50-100 " id="subcategory'.$poz.'">';
And I tested with the second method you provided as it seemed cleaner
$("#subcategory'.$poz.' option[value='.$subcatid.']").prop("selected","selected");
See the solution (simplified code) working here https://jsfiddle.net/79kugn60/
If you are using any event. Try Bind that event in your function. So that everytime event gets binded. After firing.
I have a drop-down that's populated with database records along with a button for displaying each record's information via an AJAX call to a processing page. If the record's 'approval' database field is true, the check box is displayed as checked, if not, it's unchecked. Up to this point, everything works fine.
My problem is not being able to use a jQuery selector on the dynamically generated check box. When the checkbox is changed, nothing happens--no console logs or anything.
I haven't re-factored my code to avoid repetition/etc, so please excuse the sloppiness:
PHP (returned code through AJAX call):
if($approved) {
echo '<p><strong>Approved: </strong>';
echo '<input type="checkbox" id="checkbox_unapprove" checked>';
echo '</p>';
} else {
echo '<p><strong>Approved: </strong>';
echo '<input type="checkbox" id="checkbox_approve">';
echo '</p>';
}
Portion of my jQuery:
$('#checkbox_approve').change(function(){
console.log('clicked');
var dropdown_id = $('#exchanges0 option:selected').attr('id');
alert(dropdown_id);
});
$('#checkbox_unapprove').change(function(){
console.log('clicked');
var dropdown_id = $('#exchanges1 option:selected').attr('id');
alert(dropdown_id);
});
I'm thinking that jQuery can't access #checkbox_approve or #checkbox_unapprove because they're not loaded into the DOM upon page load. Is this correct?
Use .on()
As elements are added dynamically you can not bind events directly to them .So you have to use Event Delegation.
$(document).on('change','#checkbox_approve',function(){
console.log('clicked');
var dropdown_id = $('#exchanges0 option:selected').attr('id');
alert(dropdown_id);
});
Syntax
$( elements ).on( events, selector, data, handler );
instead of binding your event in a $(document).ready() put it all on a standard function
function onDocumentLoad() {
$('#checkbox_approve').change(function(){
console.log('clicked');
var dropdown_id = $('#exchanges0 option:selected').attr('id');
alert(dropdown_id);
});
$('#checkbox_unapprove').change(function(){
console.log('clicked');
var dropdown_id = $('#exchanges1 option:selected').attr('id');
alert(dropdown_id);
});
}
SO you can call this function in the $(document).ready(); and also after your AJAX script has added content to the page. therefor you events will be properly binded to your new added elements
I am dynamically adding list items to a list in jQuery through an ajax call that is called every second.
Below is the code for the ajax call.
$.ajax({
url: 'php/update_group_list.php',
data: '',
dataType: 'json',
success: function(data) {
var id = data.instructor_id;
group_cnt = data.group_cnt,
group_name = data.group_name,
group_code = data.group_code;
for (i = current_row; i < group_cnt; i++)
{
//setInterval(function() { $('#group-list-div').load('php/group_list.php'); }, 5000);
$('#group-list').append("<li><a href='#' data-role='button' class='view-group-btns' id='"+group_code[i]+"' value='"+id+"' text='"+group_name[i]+"'>"+group_name[i]+"</a></li>");
$('#delete-group-list').append("<fieldset data-role='controlgroup data-iconpos='right'>" +
"<input id='"+group_code[i]+i+"' value='"+group_code[i]+"' type='checkbox' name='groups[]'>" +
"<label for='"+group_code[i]+i+"'>"+group_name[i]+"</label>" +
"</fieldset>");
}
current_row = i;
$('#group-list').listview('refresh');
$('#delete-group-list').trigger('create');
}
});
Now I am having two problems
FIRST PROBLEM:
When I try to run the code below (it should show an alert box if any of the list items created in this line $('#group-list').blah...blah in the code above), nothing happens.
$(".view-group-btns").click(function()
{
alert("check");
});
SECOND PROBLEM:
Also when I try to send the form data for the checkboxes (referencing line $('#delete-group-list').blah...blah in the ajax call code above) the post returns the error unexpected token <
What am I doing wrong? I think the two problems are related as I am creating the list items that are used dynamically.
Here is extra code relating to the SECOND problem
HTML:
<form id='delete-group-form' action='php/delete_groups.php' method='post'>
<h3 style='text-align: center;'>Check the Box Beside the Groups you Would Like to Delete </h3>
<div style='margin-top: 20px;'></div>
<div id='delete-group-list'>
</div>
<div style='margin-top: 20px;'></div>
<input type='submit' id='delete-groups-btn' data-theme='b' value='Delete Groups(s)'>
</form>
JS Code
$('#delete-group-form').submit(function(e)
{
e.preventDefault();
alert($('#delete-group-form').serialize());
if ($('#delete-group-form').serialize() == "")
{
alert('No groups selected to be deleted.')
return false;
}
else
if ($('#delete-groups-form').serialize() == null)
{
alert('No groups selected to be deleted.')
return false;
}
else
{
$.post('php/delete_groups.php',$('#delete-groups-form').serialize()).done(function(data)
{
obj = jQuery.parseJSON(data);
var group_codes = obj.group_list;
alert(group_codes);
alert("The selected groups have been deleted");
window.setTimeout(2000);
return false;
});
}
return false;
});
delete_groups.php
<?php
$group_codes = $_POST['groups'];
$items = array('group_list'=>$group_codes); //creating an array of data to be sent back to js file
echo json_encode($items); //sending data back through json encoding
?>
I think the root of the SECOND problem is the line $group_codes = $_POST['groups']; specfically the $_POST['groups'] because when I replace it with $group_codes = 'test'; (just for debugging purposes) , the code works as expected.
You need to use event delegation to make your newly-created elements function properly:
$("#group-list").on("click", ".view-group-btns", function() {
alert("check");
});
I noticed you have 3 single quotes on this line... missed one after controlgroup
$('#delete-group-list')."<fieldset data-role='controlgroup data-iconpos='right'>"
That would explain the unexpected token <
You have to use the jquery on event.
$(".view-group-btns").on("click", function(event)
{
alert("check");
});
Why?
Because you can only use the regular "click" on elements that are created BEFORE the DOM is updated.
When you are dynamically creating new elements into the dom tree, then you can't use .click anymore.
on (and in the past, .live(), which is deprecated now) can listen to modifications in the DOM tree and can use the later-on created elements.
You have to bind the click function after you get the element from ajax call. Binding on pageLoad event will only bind with those elements that are already in the dom. So do something like this.
$.ajax({
success : function(res){
//bind your click function after you update your html dom.
}
})
I have a requirement to get a variable from PHP to Javascript when clicked by the user. I have an array of data returned by a query and I need to pass an ID value for the element clicked so that I can populate an additional data set via the .load using another PHP page. I am unsure how todo this?
Javascript Code in Page:
<script type="text/javascript">
$(function () {
$("#pass_userid_div").click(function () {
$("#another_div").load('remote_pages/get_info.php?userid=' + $GET_THE_USERID_AND_PASS_HERE);
});
});
</script>
PHP Code in Page:
$query_str = "SELECT id, username, dateregistered FROM users";
$query = mysql_query($query_string) or die(mysql_error());
while ($results = mysql_fetch_array($query)) {
print "<div id='pass_userid_div'>{$results['username']}</div>";
print "<div>{$results['dateregistered']}</div>";
}
Why must it be a div? Use an interactive element:
PHP:
while ($results = mysql_fetch_array($query)) {
print "<button type='button' name='pass_userid_div' value='{$results['id']}'>{$results['username']}</button>";
print "<div>{$results['dateregistered']}</div>";
}
JavaScript:
<script type="text/javascript">
$(function () {
$("button[name='pass_userid_div']").click(function () {
$("#another_div").load('remote_pages/get_info.php?userid=' + $(this).val());
});
});
</script>
Update: If it really must be a div, use a data- attribute:
<div class="pass_userid_div" data-userid='{$results['id']}'…
…$(this).data("userid")
$("#another_div").load('remote_pages/get_info.php?userid=' + $GET_THE_USERID_AND_PASS_HERE, function(){
$("#another_div #pass_userid_div").each(function(){
var yourvar =$(this).text();
// use your var
})
});
Please not you should not use more then one div whith the same id. Use class instread
I build a table up of cameras using php. So upon entry I have a query that pulls all the data I need (this is Joomla, hence the weird functions):
$query_camera_name = "SELECT camera_name, camera_status, camera_quality, email_notice, camera_hash, camera_type, camera_sensitivity, camera_user, camera_pass, camera_ip, camera_port FROM #__cameras WHERE user_id=".$user->id." AND camera_status!='DELETED'";
$db->setQuery($query_camera_name);
//get number of cameras so we can build the table accordingly
$db->query();
$num_rows = $db->getNumRows();
// We can use array names with loadAssocList.
$result_cameras = $db->loadAssocList();
I then look through to create a table with the data I need (this is abbreviated):
<?php
for($i=0;$i<$num_rows;$i++)
{
?>
...
<tbody>
<tr data-hash="<?php echo $result_cameras[$i]["camera_hash"]; ?>">
<td>
<?php echo $result_cameras[$i]["camera_type"]; ?>
</td>
<td>
<?php echo $result_cameras[$i]["camera_name"]; ?>
</td>
...
<td>
<button id="axis-details" onclick="apikey('<?php echo $result_cameras[$i]["camera_hash"]; ?>');">API Key</button>
</td>
...
<?php
}
?>
I'd like to create a jquery ui dialog with a textarea and a url filled in. The dialog is easy:
$(document).ready(function() {
var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ')
.append('<p><textarea id=\"textbox\">'+ENTER URL HERE+'</textarea></p>')
.append('<p>For more information see: setup</p>');
$dialog.dialog({
autoOpen: false,
title: 'API Key'
});
$('#axis-details').click(function(e) {
e.preventDefault();
$dialog.dialog('open');
});
});
The url is this:
"http://myhost.com/notify.php/" +'<?php echo $result_cameras[$i]["camera_hash"]; ?>';
The problem is how can I put that url in the jquery code (where it says "ENTER URL HERE")? I obviously can't use:
<?php echo $result_cameras[$i]["camera_hash"]; ?>
because that is only resolved in the PHP code where I loop to build an html table. Any suggestions are appreciated.
Foolowing will create dialog "on the fly"
First you have to use class instead of ID for your "axis_details" button. ID's must be unique in a page.
You aready have url in your data-has attribute in TR
$('.axis-details').click(function(e) {
e.preventDefault();
var url = $(this).closest('tr').data('hash');
var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ').append('<p><textarea id=\"textbox\">' + url + '</textarea></p>').append('<p>For more information see: setup</p>');
$dialog.dialog({
title: 'API Key',
close: function() {
$(this).remove();
}
});
})
....
<button class="axis-details" data-url="<?php echo $result_cameras[$i]["camera_hash"] ?>">API Key</button>
....
....
var $dialog = $('<div id="dialog-container"></div>');
$dialog.append('Please copy this key for camera setup: ')
.append('<p><textarea class="url-container"></textarea></p>')
.append('<p>For more information see: setup</p>');
....
....
$(".axis-details").on("click", function()
{
var url = $(this).data("url");
$("#dialog-container").find(".url-container").val(url);
$dialog.dialog('open');
});
if you didn't, you have to append the dialog div to the document (i'm not sure)
First in your PHP file:
echo '<input type="hidden" value="'.$result_cameras[$i]["camera_hash"].'" class="cameraHash" />';
Then you need to modify your jQuery code so the appends happen the way you intend.
$(document).ready(function() {
var $dialog = $('<div></div>');
$dialog.append('Please copy this key for camera setup: ');
//new code to count each instance found
var eachLink = $(".cameraHash").val();
$.each(eachLink, function(index,value){
$dialog.append('<p><textarea id=\"textbox-'+index+'\">http://myhost.com/notify.php/'+value+'</textarea></p>')
});
//end new code, but change the next .append to $dialog.append
$dialog.append('<p>For more information see: setup</p>');
$dialog.dialog({
autoOpen: false,
title: 'API Key'
});
The above function grabs each value of .cameraHash. It appends the same textarea (which I modified because the ID isn't unique in your post, so I used the 'index' of the links to represent the textbox. so that it's cohesive with the values) and inside of it uses the value of the cameraHash found at that specific index.