I made this following function :
function populatetable(){
$.ajax({
type: 'GET',
url: 'backend/conn.php?action=populatetable'
}).done(function(data){
var response = data.data;
$.each(response, function(key, element){
row += '<tr> <<td>' + element.phone + '</td> <td> <button class="trigger"> Edit Data </button> </td> </tr>';
});
$('table.loadeddata > tbody').html(row);
})
}
and stored it to a file called script.js. Then in another file named index.php I included that file within the tag <script src='script.js'></script>
and below the above script tag, I made once again a <script> and put this following code into the second <script> tag :
$('document').ready(function(){
populatetable();
$('button.trigger').click(function(){
window.alert('button works');
});
});
why did the button not showing the alert when clicked?
The button appeared perfectly, it seems that the closure caused the problem but I'm not sure.
the button is dynamically created, so it is not in the DOM at load time. try:
$('body').on('click', '.trigger', function(){
window.alert('button works');
});
fiddle https://jsfiddle.net/sn36oyfo/
Read more about event delegation
Related
I've got a div which is updated via AJAX(result is passed in other php page), and the content is a table with buttons, which should call a js function with value passed on:
<?php echo '
<table>
<tr>
<td>115</td>
<td><input type="button" value="down" onclick="jsFunction(115)"/></td>
</tr>
</table>'; ?>
The div gets updated with function filter() as follows(also i pass to filter() different values, but when loaded, it starts with value 1):
$(document).ready(function() {
filter(1);
});
function filter(pageval) {
var user = document.getElementById("user");
userval = user.value;
var pid= '#page-'+pageval;
$.ajax({
type: 'post',
url: 'filtercase.php',
data: {
user:userval,
page: pageval,
},
success: function (response) {
$( '#ajax-response' ).html(response);
}
});
}
Question: where do I put jsFunction(int) so it will be called only when button is table is clicked?
Function itself:
<script type="text/javascript">
function downloadReport(case){
console.log(case);}
</script>
I've put it in $(document).ready(function()), as independent script on the bottom of the page, inside my ajax response - none worked:
Uncaught SyntaxError: Unexpected token case
Uncaught ReferenceError:downloadReport is not defined
case being a reserved keyword, the javascript engine does not read your code function at all.
You have the error in the console...
You need to use a handler. The simple way is to add to your button element:
onclick="downloadReport()"
I am binding the click function foo to the anchor tag in jquery.ajax. The problem I am facing is that I have to request twice or click the anchor tag twice to make the request. Also I have noticed in the browser under the network bar that ajax request is not triggered, first time when I hit the anchor tag. But when I hit it twice then I see two ajax request in the network tab. I have no idea what is going on?
<script type="text/javascript">
function show(thelink)
{
var cat = thelink.innerHTML;
var productContainer = document.getElementById("productContainer");
$.ajax({
type:"POST",
url:"fetchdata1",
data:"cat="+cat,
success:function(data){
productContainer.innerHTML ="";
var $productContainer = $('#productContainer');
$.each(data,function(key,value){
if(value['newVar'] === 1)
{
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
<a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
<span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span>\n\
<br/><br/><a href='#' class='remove' onclick='foo(this)' pid='"+value['id']+"'>REMOVE</a></div>");
}
else{
$productContainer.append("<div id='productBox' class='grid_3'>\n\
<a href='product.jsp?id="+value['id']+"'><img src='"+value["image"]+"'/></a><br/>\n\
<a href='product.jsp?id="+value['id']+"'><span class='black'>"+value['name']+"</span></a><br/>\n\
<span class='black'>By "+value['company']+"</span><br/><span class='red'>RS."+value['price']+"</span></div>");
}
}) ;
}
});
return false;
}
function foo(obj){
var pid = $(obj).attr("pid");
$(obj).bind("click", function(){
$.ajax({
type:"POST",
url:"removeFromWishlist",
data:"pid="+pid,
success:function(response){
console.log("sent ajax request");
}
});
});
}
You were binding an extra onclick handler to .remove.
When working with callbacks on dynamically added elements, its better to bind all required events on document context using $(document).on("click", 'selector', function(){ ... });.
So instead of a href='#' class='remove' onclick='foo(this)' pid='"+ do this (see below snippet)
$(document).on("click", '#productBox .remove', function(){
// your ajax call
$.ajax({
type:"POST",
url:"removeFromWishlist",
data:"pid="+pid,
success:function(response){
console.log("sent ajax request");
}
});
});
This will separate your HTML layout and its behaviour.
Below things must be avoided (Thanks to #charlietfl):
Binding 'click' listeners twice on same element.
Using javascript inline with your html code.
Directly binding a javascript function using onclick attribute.
Not using javascript unobtrusively.
Hope it helps.
I am trying to read a table when I click on total button,the button is created on ajax call with table I tried with both id attribute and input type submit selectors but I am not able to read the button,but when I tried to call javascript function on button click the javascript function is called,can anyone explain this and how should I read using jquery selectors
$.ajax({
type:'POST',
url:'/pos/addproduct',
dataType: "json",
data:JSON.stringify(order),
contentType: "application/json; charset=utf-8",
success:
function(data){
i++;
console.log(i);
$.each(data,function(index,value){
var temp = "qty" + data[index].barcodeid.trim();
var qtyitm=$("#"+temp);
if(qtyitm.length != 0){
qtyitm.html(data[index].qty);
//("#price"+(data[index].barcodeid.trim())).html(data[index].price);
temp = "price" + data[index].barcodeid.trim();
qtyitm = $("#"+temp);
qtyitm.html(data[index].price);
}
else{
var row=$("<tr><td>"+data[index].oid+"</td>"+"<td>"+data[index].pname.trim()+
"</td>"+
"<td id=\"qty"+data[index].barcodeid.trim()+"\">"+data[index].qty+"</td>"+
"<td id=\"price"+data[index].barcodeid.trim()+"\">"+data[index].price+"</td>"+
"<td>"
+data[index].barcodeid.trim()+"</td></tr>"
);
$("#firstrow").after(row).removeClass("hidden");
}
})
if(i==1){
var row1=$("<tr><td>"+'<input type="submit" id="calculateTotal" value="Total">'+"</td></tr>");
$("#order tbody").append(row1);
}
}
})
});
$('input[id="calculateTotal"]').click(function(event){
alert("hello");
})
Since the submit button #calculateTotal was added dynamically via js code in :
$("<tr><td>"+'<input type="submit" id="calculateTotal" value="Total">'+"</td></tr>");
You should use event delegation on() to attach click event to it, like :
$('body').on('click', 'input[id="calculateTotal"]', function(event){
alert("hello");
})
Hope this helps.
Browser parses your javascript code when your page is loaded and attaches event listeners to DOM elements in your initial loading (in that case your button does not exits as you simply attach it to existing DOM tree [hence no event bound] )
Solution is use $('document').on('event','selector','callback') so with you code :
var row1=$("<tr><td>"+'<input type="submit" id="calculateTotal" value="Total">'+"</td></tr>");
$("#order tbody").append(row1);
and in Js:
$('document').on('click','#calculateTotal',function(){
//do your stuff here
});
Hope it helps...:D
When I click all the button output will be same (i.e 1).I want to display specific value of specified button for EXAMPLE:- When I click button 1 then It must display output as 1 and when I click 2 it must display output as 2.please help me.
<?php
for ($i=0; $i < 10 ; $i++) {
echo '<br><button value="'.$i.'" class="my_remark_btn">'.$i.'</button>';
}
?>
<script type="text/javascript">
$('.my_remark_btn').click(function(){
remark_aftr_click();
});
function remark_aftr_click(){
var k = $(".my_remark_btn").val();
$.ajax({url: "my_remark_act.php",
cache: true,
type: "POST",
data: {go:k},
success: function(data_remark_mi){
alert(data_remark_mi);
}
});
}
</script>
my_remark_act.php:-
<?php echo $_POST['go']; ?>
$('body').append("<button data-value='val' class='my_remark_btn'>val</button>")
$(document).on('click', '.my_remark_btn', function() {
alert($(this).attr('data-value'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Button has no value.
Use data attribute like data-value.
Get it like $(this).attr('data-value') using this context for clicked button.
Use event delegation for dynamically added elements.
Try This Example.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$("button").click(function() {
alert(this.id); // or alert($(this).attr('id'));
});
});
</script>
</head>
<body>
<button id="some_id1"></button>
<button id="id2"></button>
<button id="id3"></button>
<button id="id4"></button>
<button id="id5"></button>
</body>
</html>
You can use JQuery. try the below code.
// this will fire for all button having class '.my_remark_btn'
$('.my_remark_btn').click(function(){
// using $(this) you will get the current element
var value = $(this).val();
console.log(value);
});
In you code you are accessing value by var k = $(".my_remark_btn").val(); , This will only return value of the first button with class my_remark_btn.
Have a try of this
jQuery
$('.my_remark_btn').click(function(){ // when a button is clicked
var value = $(this).value; // get the value of that specific button
alert(value); // alert the value to the page (to make sure it is correct)
remark_aftr_click(value); // run function, with value as a parameter
});
function remark_aftr_click(val){
$.ajax({
url: "my_remark_act.php",
cache: true,
type: "POST",
data: {go: val}, // post data to Ajax with CORRECT value
success: function(data){
alert(data); // alert returned data
}
});
}
Why your code was not working:
When you were retrieving the value of .my_remark_btn before, you were only ever getting the value of the first element with that specific class.
How you can get it to work:
Instead, you need to pass the value as a parameter within your function (while using this as a selector to get the value of that specific button).
Hope this helps :-)
You need $(this).attr("value") like below:-
<script type="text/javascript">
$('.my_remark_btn').click(function(){
var k = $(this).attr("value");
$.ajax({url: "my_remark_act.php",
cache: true,
type: "POST",
data: {go:k},
success: function(data_remark_mi){
alert(data_remark_mi);
}
});
});
</script>
Example:-
$('.my_remark_btn').click(function(){
var k = $(this).attr("value");
alert(k);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button value ="1" class="my_remark_btn">1</button><br>
<button value ="2" class="my_remark_btn">2</button>
Background: I am working on a small web application. AJAX will successfully POST the data to the action(create.php) and create.php will execute the necessary mysql query. Once AJAX is done, I append a message to the div id="container"></div> informing the user of a successful execution then clear the content "container" for future use; however, here in lies the problem.
Problem: After AJAX executes, I can not click on any HTML links already loaded onto the page(page.php). I have to refresh the page in order to click on any links and follow them to their destination. What is causing this to happen and how can I fix it?
AJAX does not need to return a result. It only needs to execute the specified jQuery code once the request is done. On a hunch, I altered create.php to echo the $_POST array and have AJAX return that as a result. Once AJAX loads the result into the "container" I still can not click on any links loaded on page.php
Answer: The DOM was not being reloaded after AJAX calls causing bootstrap dropdown menus to not function properly. The bootstrap dropdown class had to be manually reinitialized after each call. This has already been answered in detail here
create.php
<?php
if($_POST){
//run mysql query
}else{
//do nothing
}
?>
form.php
<form id="new-items">
<input type="text" name="item" />
<input type="button" onclick="create_item()" name="Submit" value="Submit" />
</form>
page.php
<html>
<head>
<script>
$(document).ready(function(){
$("#add_items").click(function(){
event.preventDefault();
$("#content").load("form.php");
});
});
function create_item(){
var form_data = $("#new-items").serialize();
var request = $.ajax({
url: "create.php",
type: "POST",
data: form_data,
});
request.done(function(){
$("#content").append('<div>User was added successfully</div>');
setTimeout(function(){
$("#content").fadeOut("slow");
}, 5000);
setTimeout(function(){
$("#content").empty();
}, 8000);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<nav>
Link1
Link2
Add New Items
</nav>
<div id="content"></div>
</body>
</html>
After you fadeOut the #content element, it remains hidden. The next time you call your AJAX function, it's loading create.php into an invisible element.
Try:
setTimeout(function(){
$("#content").fadeOut("slow", function() {
$(this).empty().show();
});
}, 5000);
Other issues: <div class="content"> should be <div id="content">; you didn't include jquery.js at the top of your script; you didn't pass the event object e to your click handler.
page.php should now look like:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$("#add_items").click(function(e){
e.preventDefault();
$("#content").load("form.php");
});
});
function create_item(){
var form_data = $("#new-items").serialize();
var request = $.ajax({
url: "create.php",
type: "POST",
data: form_data,
});
request.done(function(){
$("#content").append('<div>User was added successfully</div>');
setTimeout(function(){
$("#content").fadeOut("slow", function() {
$(this).empty().show();
});
}, 5000);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
</head>
<body>
<nav>Add New Items</nav>
<div id="content"></div>
</body>
</html>
The anchor links in the <nav> will natually 'refresh' the page with the new content.
If you want to load the content via an ajax request then you should try the following:
Add a common class to the links
<nav>
Link1
Link2
Add New Items
</nav>
Then attach a click event to each link which intercepts the default page refresh with e.preventDefault(). The you can perform the ajax request using the href attribute of that link.
$(function(){
$(".anchor").on('click', function(e){
e.preventDefault();
var $this=$(this);
$("#content").load($this.attr('href'));
});
});
The DOM was not being reloaded after AJAX call. Boostrap dropdown module has to be manually reinitialized after each call. Detailed answered here: answer