jQuery.ajax, I always have to request twice - javascript

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.

Related

Id selector not working for input type submit

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

Jquery-generated button not working, closure

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

Add javascript function to wordpress page

I have a page that locates a link inside it and when that link is clicked it should save some data in database.
Besides, I have a file named "add.php" that communicates with the DB and operates well.
In my wordpress page I have added below codes for accessing the add.php file and send some parameters to it.
<a href="javascript:add(true);" >Click Me</a>
<script type="text/javascript">
function add(b){
$(document).ready(function(){
var result = $.ajax({
type: "POST",
url: "add.php",
data: { add: b }
});
result.done(function(msg) {
alert(msg);
});
result.fail(function(jqXHR, textStatus) {
alert( "No such data exists: " + textStatus );
});
});
}
</script>
I had this exact code in an html file and it worked smoothly. but it doesn't work on wordpress page like that.
Plus, the problem is that when I click the link -Click Me- it doesn't do anything.
please tell me where the problem is and how to solve it ?
I would recommend you to use this:
<a href="#" data-add="true" class='hitClick'>Click Me</a>
<!--use data* attributes to pass specific data -->
now in your function:
function add() {
event.preventDefault(); //<------make sure to add it.
var result = jQuery.ajax({
type: "POST",
url: "add.php",
data: {
add: jQuery(this).data('add')
}
});
result.done(function(msg) {
alert(msg);
});
result.fail(function(jqXHR, textStatus) {
alert("No such data exists: " + textStatus);
});
}
jQuery(document).ready(function(){
jQuery('.hitClick').on('click', add); // bind the click and use as callback
});

Why my find('a') doesn't work in jquery?

I have a function in jquery:
function handleUpcomingUserTexts () {
$.ajax({
url: 'getjson.php',
type: "POST",
data: {
mail: '<?php echo htmlentities($_SESSION["email"]); ?>'
},
dataType:'text',
success: function(ans)
{
var data = JSON.parse(ans);
$.each(data, function(i, v) {
var upcomingText = $('<i class="fa fa-comment fa-fw"></i> '+v.Content+'<span class="pull-right text-muted small"><em>'+v.Date+'</em></span>');
$('#upcomingTexts').append(upcomingText);
var a = upcomingText.find('a').on('click',function(e){
e.preventDefault();
alert("here");
});
});
}});
};
and it fills the html nicely, but when I click the link - nothing happens and I don't see the alert message. What is wrong in here?
Because upcomingText is already a a. And you are trying to find a a in your a.
You can just write this :
var a = upcomingText.on('click',function(e){
When you write var variable = $('<a ...>...</a>');, the result is the root tag of the given html. So in your case, the <a>.
Because upcomingText is <a> and in this tag there are not any <a> tags, so you need use upcomingText like this
upcomingText.on('click',function(e) {});
but event delegation in this case better solution
// add this code before $.ajax
$('#upcomingTexts').on('click', 'a.list-group-item', function(e) {});
Try to use delegate function, on #upcomingTexts block
$('#upcomingTexts').delegate('a', 'click', function(e){
//your code here
});

jquery ajax not submitting

I have this code:
<script>
$(document).ready(function() {
$("#edit-my-username").click(function() {
$("#my-username").html('<input type="text" id="new-username" value="<?php echo $my_username; ?>"> <button class="my-button small-btn" id="submit-my-username">Submit</button>');
});
$("#submit-my-username").click(function() {
var user = "<?php echo $userid; ?>";
var edit_field = "username";
var edit_content = $("#new-username").val();
if(edit_content !== ''){
$.ajax({
type: "POST",
url: "edit-user.php",
data: {user: user, field: edit_field, content: edit_content},
cache: false,
success: function(html){
$("#my-username").html(html);
}
});
}return false;
});
});
</script>
I can't figure out why it doesn't submit. Firebug see's no XHR when the button is clicked. I'm not exactly confident with JS/jQ.. where am I going wrong?
Since you are dynamically adding #submit-my-username the click handler is not binded on page load.
$("#submit-my-username").click(function() {
Change the click handler to following
$("body").on( "click", "#submit-my-username", function() {
When you add html via javascript, in your case jquery, the click event (and any other trigger events) do not works.
You have to use on event, or live event, but the last one is deprecated.
For example:
$("#submit-my-username").live('click'. function()
$("#submit-my-username").on('click', function()
When page load,jquery ready funciton executed.The section 'Submit' does not exist,so '$("#submit-my-username").click(function() {}' script not works.
I think you should add onclick event in 'Submit' distinctly.
such as :
<button class="my-button small-btn" id="submit-my-username" onclick='func()'>Submit</button>
In your case, you should use .live() method, however it is now deprecated. instead of that you can use .on()
$("#my-username").on('click', '#submit-my-username', function(event) {}
Sorry for mis-interpreting your question.Below code can be user to submit form using jquery.
$("form").submit(function(){
//your code
});
Hope this is the answer to your question.

Categories