jQuery click event is not working in first click - javascript

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

Related

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

event.preventDefault() not working if link added by js

i have a problem with event.preventDefault() because the event not stop.
i have two different functions. the first function is a xhrCall and show all posts and append the result to a table. in this function, i create a link with class="del" and href="#".
$.each(data, function(i, data){
$('#listMsg').append('<tr><td>' + data.id + '</td><td>' + data.msg + '</td><td><a class="del" rel="'+ data.id + '" href="#"> delete</a></td></tr>');
});
my next function is to handle the delete.
$(". del").click(function(e) {
e.preventDefault();
var id = $(this).attr('rel')
alert('delete + ' + id);
});
If i copy a link directly into my index.php file with the same class, the code work!
unfortunately, i don't know what i missed or how to talk to links that are insert with js.
thanks a lot for help!
Did you say you were adding the link with ajax? If so you need to do it this way:
$("#listMsg").on("click", ".del", function(e) {
e.preventDefault();
var id = $(this).attr('rel')
alert('delete + ' + id);
});
if Jquery is version 1.7 or older do it this way
$("#listMsg").delegate( ".del", "click", function(e) {
e.preventDefault();
var id = $(this).attr('rel')
alert('delete + ' + id);
});

Ajax request called multiple times though I need only once?

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

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

Javascript to display labels on the button with the same class

Here's a simple question:
On the page there are two javascript.
The first script gets JSON and used it to build multiple forms with buttons:
$.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(""));
}
);
The second script is a response by pressing a button on the form of constructing the first script:
$(document).on('click', '.share_file_form', function(event) {
$(this).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>");
}
});
}
});
});
Everything works, but at the time of the second script, the inscription appears on the buttons of all forms, and I need only one button, which I click.
The problem is this line:
$(".share_file_submit").html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
It sets the html for all elements with the "share_file_submit" class on the entire page. You can fix it by adding a context to the selector:
$(".share_file_submit", $(form)).html("Send <img src='http://src.server.com/loadr.gif' border='0'/>");
If you really want to use validate plugin properly you shouldn't initialize it within a click handler.
Should be initializing right after the form building code.
Within $.getJSON
$('#mytile').html(results.join(""));
$('.share_file_form').validate(/* options*/);
The submitHandler will over ride the default submit event of the form and validation will be active while user fills out form.
To fix button issue:
submitHandler: function(form) {// form is current form elemnt
$.ajax({
beforeSend:function(){
/* look within form for button*/
$(form).find(".share_file_submit").prop('disabled',true);
})
});
Now if user uses Enter key you aren't relying on a click event to prevent submittal by browser default

Categories