Ajax request called multiple times though I need only once? - javascript

I have been working on a e-commerce web application. There is a wishlist module which I'm trying to implement. I'm adding the products into wishlist using ajax calls and also removing it with ajax. The adding part works fine but I have a problem in removing part . What I'm trying to do is, making an ajax call to fetch the wishlist items from the database and adding a remove button dynamically using jquery. Although I know that I have to use a .live function to attach an event to it which I did but when i click on the button all the items which are present in the wishlist are removed . I see multiple ajax request was made in console under network tab and I don't get it why , although I clicked it only once. The following is a snippet of my code
$.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 id='remove' href='#'>REMOVE</a></div>");
foo(value['id']);
} 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>");
}
});
}
});
function foo(value) {
var pid = value;
$('#remove').live("click", function() {
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});
In the first ajax request I'm fetching products from the database then adding remove button to it dynamically then calling function foo which attach the click event using .live function and then make call to database to remove it.
Hey guys I'm not pro at web, so go easy on me if I made some silly mistake.
Thanks!

Problem:
You have same id for multiple hyperlink and you are using .live function on "id based" selector. It is applying click function again & again on first element.
Solution:
Update your hyperlink
<a href='#' onclick="foo(this)" pid=value['id']>REMOVE</a>
Then in foo() function
function foo(obj) {
var pid = $(obj).attr("pid");
$(obj).bind("click", function() {
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});

i don't get why you using same id multiple times.
and afaik, jQuery.live already deprecated.
you can use this if you want to get live behavior:
$(document).on('click', 'element-selector', function(){
...
});
with your code, it can rewriten to:
$(document).on('click', '[id=remove]', function(){
...ajax call...
});
now the problem with your fetch data function is this:
$.each(data, function(key, value) {
if (value['newVar'] === 1) {
...append element...
**foo(value['id']);**
} else {
...append element...
}
});
as we know foo() are your function that bind remove behavior.
based on your code, whenever that fetch data has newVar = 1, it will directly call foo. which mean binding remove behavior multiple times, as many as newVar = 1 was.
solution:
you can put pid as a attribute on your a element
maybe something like remove
and within remove click function, you can use $(this).attr('pid') to get that value.
and remove that foo() content to outside the function, since $(element).live(...) or $(document).on(event, element, ...) will listen the element, even the element dynamicly added to the page.

The issue happened because you register listener multiple times in each loop. So to resolve, you need to register once after all button has been populated. I also change selector to class ".remove" because you going to have multiple remove button so using id is will be duplicated, and using jquery .on() instead of .live() (deprecated)
$.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 class='remove' id='remove' data-pid='" + value['id'] + "' href='#'>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>");
}
});
foo();
}
});
function foo() {
$('.remove').on("click", function() {
var pid = $(this).data("pid");
$.ajax({
type: "POST",
url: "removeFromWishlist",
data: "pid=" + pid,
success: function(response) {
}
});
});

Related

jQuery click event is not working in first click

I using a code on my page. Like this:
$('#language_id').change(function () {
var urli = 'https://example.com/php/get_arch.php?language_id=' + language_id;
$.ajax({
type: "GET",
url: urli,
dataType: 'json',
success: function(response){
var options = '';
$.each(response.archs, function() {
options += '<option value="' + this.arch_id + '">' + this.name + '</option>';
});
$('#arch_id').html('<option value="0">- ' + selachitecture + ' -</option>'+options);
$('#arch_id').attr('disabled', false);
}
});
});
$('#arch_id').change(function(){
var version_id = $('#version_id :selected').val();
$('#selectBoxInfo').load('https://example.com/dl.php?fileName=' + arch_id + "&lang=" + lang);
return(false);
});
$('body').on('click', '.buttond a', function() {
alert("new link clicked!");
$("a").removeAttr("onclick");
});
I explain my code: when selecting an optional, it will create a button "Download". This button load by Ajax. I don't want feature pop-up of this button.
So, I tried to prevent this button turn on the pop-up.
The problem is: at first click in button, my Javascript is not working. It only works from the second click.
I don't know problem at here. I using 'on' to listen to all event.
replace your code with this code ..
$('#selectBoxInfo')
.load('https://example.com/dl.php?fileName=' + arch_id+"&lang="+lang
,function(){
$("a").removeAttr("onclick");
}
);

AJAX jQuery Iterate through response on Button Click

I am new to Coding and I got stuck for hours solving this problem:
The response from AJAX is a Json two-dimesional array jqXHR[][] the first index
describes each product id, the second one holds product details like prices etc.
So all i want to is to iterate through the first index by using the button "New_Suggestion" and to update the html content in the "result_wrapper".
The response works fine, but updating the html content doesn't work at all.
Thank you for your help.
$.ajax({
type: "POST",
url: "productsuggestion.php",
data: "criteria1=" + crit1 + "&criteria2=" + crit2 + "&criteria3=" + crit3 + "&criteria4=" + crit4 + "&criteria5=" + crit5,
dataType: "json",
success: function(jqXHR) {
var sug = 0;
$('#New_Suggestion').on('click', function() {
sug = sug + 1
});
$("#result_wrapper").html(
'<div id="prod_name">' + jqXHR[sug][0] + '</div> <br>' +
'<img id="prod_pic" src="' + jqXHR[sug][4] + '">' +
'<div id="prod_price">' + jqXHR[sug][2] + '</div> <br>'
);
}
});
Firstly, your "click" handler just increments a variable when it's clicked. It doesn't touch the output at all.
Secondly, every time the ajax runs, you add another click event handler to the button, without removing the previous one(s). It's easier to declare this outside the ajax context, and set a global variable for the suggestion count.
Something like this, I think (untested):
var sugCount = 0;
var sugData = null;
$.ajax({
type : "POST",
url : "productsuggestion.php",
data : "criteria1="+crit1+"&criteria2="+crit2+"&criteria3="+crit3+"&criteria4="+crit4+"&criteria5="+crit5,
dataType: "json",
success: function(data){
//reset global data after each ajax call
sugCount = 0;
sugData = data;
writeSuggestions(sugCount, sugData); //output the initial set of suggestions
}
});
$('#New_Suggestion').on('click',function(){
sugCount = sugCount + 1;
writeSuggestions(sugCount, sugData); //output updated suggestions
});
function writeSuggestions(count, data)
{
$("#result_wrapper").html('<div id="prod_name">'+data[count][0]+'</div> <br>'+
'<img id="prod_pic" src="'+data[count][4]+'">'+
'<div id="prod_price">'+data[count][2]+'</div> <br>');
}

String Not Appended to Dynamically Created Div

I've researched this in depth on stackexchange and I don't think I am making a 'common' mistake, and the other answers have not solved this.
The problem is I am trying to append data to a DEFINITELY existing div of a certain ID. What I DO know is that the div is dynamically generated, and that is probably why it is hidden.
Despite using jquery on I cannot seem to get jquery to find the particular div.
Here is the code:
$(document).ready(function() {
function example_append_terms(data) {
var sender_id = data['sender_id'];
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = '<span data-lemma="' + v['key'] + '" class="lemma">' + v['name'] + '</span>';
$('#' + sender_id + ' .lemmas').append(html);
}
});
}
function example_get_options(data) {
$.ajax({
url: '/example/',
type: 'post',
data: data,
success: function(data) {
//alert(JSON.stringify(data))
example_append_terms(data)
},
failure: function(data) {
alert('Got an error dude');
}
});
return false;
}
$(document).on('click', ".example-synset-option", function() {
var synset = $(this).data('name');
var sender_id = $(this).attr('id')
example_get_options({
'synset': synset,
'sender_id': sender_id,
});
});
});
On clicking a certain div, an action is fired to "get options" which in turn runs an ajax function. The ajax function runs the "replacer" function example_append_terms.
Having tested up to example_append_terms the .each iteration is definitely working. But when I did tested $('#' + sender_id + ' .lemmas').length I continue to get 0.
Where is this jquery newb going wrong?
I fixed it by changing stuff...
For some inexplicable reason fetching the data attribute worked better than the id..
function intellitag_append_terms(data) {
var sender_id = $('*[data-location="'+data['sender_id']+'"] .lemmas');
$.each(data, function(k, v) {
if (k != 'sender_id') {
html = $('<span data-lemma="' + v['key'] + '" class="label label-primary lemma">' + v['name'] + '</span>');
html.appendTo(sender_id)
//$('#' + sender_id).append(html);
}
});
}

reload div contents after ajax call

i know this question has been asked lot many times but not sure after seeing so many examples, i cannot figure why it is not happening..
this is my code
function update(tid,sid) {
var getTID = tid;
var getSID = sid;
$("#flow_" + getTID + "~" + getSID).html('Loading...');
$.ajax({
url: 'generate.cfm?tID=' + getTID + '&sID=' + getSID,
type: "GET",
cache: false,
success: function(data){
var k = $(data).find("img");
$("#flow_" + getTID + "~" + getSID).empty();
$("#flow_" + getTID + "~" + getSID).append(k);
}
});
}
here is the div code
<div id="flow_#tid#~#sid#" style="margin: 0 10px 0 0;float:right;height:150px;" class="code">
<img src="#request.webbaseurl#assets/codes/#code#.jpg" style="max-height: 230px;">
</div>
i am missing something here, not sure what like timeout or something but after successful call, it should reload that div
Update#1
Here i had made changes which i did the following after response,to make sure i get the image, rather than image tag, i used the div id and it loads the inside img element in alert, i tested that
success: function(data){
var k = $(data);
var hiddenField = $('<div type="hidden" ></div>');
hiddenField.append(k);
var images = hiddenField.find('#inner');
$("#ystack_" + getTID + "~" + getSID).hide();
$("#flow_" + getTID + "~" + getSID).empty();
$("#flow_" + getTID + "~" + getSID).append(images.html());
}
but it does reload the div, if i refresh the whole page, it do show me the changed contents
you are not able to find image object directly in response.
var k = $(data).find("img");
this will not work.store response HTML code in hidden element.and find for image tag .
HTML code
<div id="hiddendiv" style="display:none;"> </div>
JQuery ajax success
success: function(data){
$('#hiddendiv').HTML(data);
var obj =$('#hiddendiv').find(img);
$("#flow_" + getTID + "~" + getSID).empty();
$("#flow_" + getTID + "~" + getSID).append('<img src="'+obj.attr("src")+'"/>');
}

List of two JSON requests

I do not understand how to do the right thing.
With this query I get a JSON with the file names:
$.getJSON("http://api.server.com/my/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<div class='accordion-group span4'><div class='accordion-heading'>Video Frame<blockquote><a href='http://server.com/video/?my=" + result.File + "' target='_blank'><img src='http://jpg.server.com/" + result.File + ".jpg' class='img-polaroid'/></a><p>" + result.ListId + "</p><small>" + result.OwnerId + "</small><small>" + result.updatedAt + "</small> </blockquote><a class='accordion-toggle' data-toggle='collapse' data-parent='#accordion2' href='#" + result.File + "'>Share video</a></div><div id='" + result.File + "' class='accordion-body collapse'><div class='accordion-inner'><form class='share_file_form'>Set list<input name='nd' id='user_id' type='hidden'><input name='file' value = '" + result.File + "' type='hidden'><div class='list'></div><input type='text' placeholder='New list'><div class='modal-footer'><button class='share_file_submit'>Share video</button></div></form><div id='user_info_result'></div></div></div></div>");
});
$('#mytile').html(results.join(""));
}
);
With this query I get a JSON with the tag names:
$.getJSON("http://api.server.com/list/?callback=?",
function(data){
var results = [];
$.each(data['results'], function(i, result) {
results.push("<label class='radio'><input type='radio' name='list' id='" + result.List + "' value='" + result.List + "' checked>" + result.List + "</label>");
});
$('.my_list').html(results.join(""));
}
);
In the end, I need to display a list of files. Next to each file should to show a form with a file name and a list of tags:
$(document).on('click', '.share_file_form', function() {
$('.share_file_form').validate({
submitHandler: function(form) {
$.ajax({
type: "GET",
url: "http://api.server.com/set/",
timeout: 20000,
data: $(form).serialize(),
beforeSend: function() {
$(".share_file_submit").attr("disabled", true);
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
},
success: function(msg){
console.log("Data Saved: " + msg);
$("#share_file_submit").attr('disabled', false);
$("#share_file_submit").html("Share video");
$("#user_info_result_2").html(msg);
},
error: function(msg){
//////////////// $('#user_info_result_2').html("<div class='alert alert-error span3'>Failed from timeout. Please try again later. <span id='timer'></span> sec.</div>");
}
});
}
});
});
All of this works.
The question is how to make sure that each form will work separately?
Now only works the first form. If you press the button on the other forms will still work the first form.
Your mistake is in the way you identify the form on which the user clicked. The following line is the problem:
$('.share_file_form').validate({
Independent of what you clicked on, you always will get the first form with this selector.
Here is what you need instead:
$(document).on('click', '.share_file_form', function(event) {
$(event.target).validate({
submitHandler: function(form) {
hmm. I 'think' I know what you want..
how about wrapping the second call in a method, or perhaps both, ala.
function fireJSON(){
var func1 = function(){
//your first json code
func2(); // call your second json code
}
var func2 = function(){
// second json code
}
return {
func1: func1
}
}
fireJSON().func1();

Categories