I have been using this jQuery before I use $.ajax(); and it was working good:
$(document).ready(function(){
var urlSerilize = 'some link';
var appList = $("#applications > li > a");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//var appList = $(".body-list > ul > li");
//var appCheck = $('input[type=checkbox][data-level="subchild"]');
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
installbtn.on('click', function () {
event.preventDefault();
jQuery.each( form, function( i, val ) {
console.log(val);
var request = $.ajax({
url: urlSerilize,
type: 'GET',
data: $('#'+val).serialize(),
success: function( response ) {
console.log( response );
$('#applications').html();
$('#apps_box').html();
}
});
request.done(function(msg){
console.log('Ajax done: ' + 'Yeah it works!!!');
});
request.fail(function(jqXHR, textStatus){
console.log('failed to install this application: ' + textStatus);
});
});
});
});
but after I used this ajax code the .click() jQuery event don't work anymore:
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
})
request.fail(function() {
console.log("error");
})
request.always(function() {
console.log("complete");
});
//end loading apps
var showmore = $('.showapps');
showmore.click(function(){
var parent = $(this).parent('.tv_apps');
var displayC = parent.children('.body-list').css('display');
console.log(displayC);
if (displayC=='none') {
parent.children('.body-list').show('400');
$(this).children().find('img').rotate({animateTo: 180});
}else{
parent.children('.body-list').hide('400');
$(this).children().find('img').rotate({animateTo: 0});
};
});
});
at first place I though it was because of the ajax loads and don't stop, then i was wrong.
I have tried the window.load=function(); DOM function to load the script after Ajax finish loading and also was wrong.
So please if there any idea to fix this problem,
Thanks.
This is the event I want it to be fixed:
appList.click(function(){
console.log('here!');
if($(this).children().find("input").is(":checked")){
$(this).children().find("input").prop('checked', false);
$(this).children('form').removeClass('checked');
$(this).removeClass("li-checked");
var rmValue = $(this).children('form').attr('id');
form = jQuery.grep(form, function(value) {
return value != rmValue;
});
}else{
$(this).children().find("input").prop('checked',true);
$(this).addClass("li-checked");
$(this).children('form').addClass('checked');
form.push($(this).children('form').attr('id'));
}
console.log(form);
});
showmore.click(function(){
should be
$('.showapps').on('click', function(){
OR
$(document).on('click','.showapps', function(){
For dynamically added contents, you need to bind events to it.
For more info: http://learn.jquery.com/events/event-delegation/
Thanks everyone, at last I have found the solution.
It was a question of the DOM, when I use the ready method of jquery it loads an empty ul (without content), so then what I figured out in the first time was correct, all I did is to remove the ready and use a simple function that includes all the .click() events, then call it in request.done();.
This is the solution:
function loadInstaller(){
var urlSerilize = 'some link';
var appList = $("#applications > li");
var appCheck = $('input[type=checkbox][data-level="subchild"]');
var installbtn = $('#submitbtn');
var form = [];
var checked = [];
//...etc
};
$(document).ready(function() {
/* loading apps */
//console.log('active');
var request = $.ajax({
url: 'some link',
type: 'GET',
dataType: 'html',
data: {id: 0},
})
request.done(function(data) {
console.log("success");
$('#applications').empty().append(data);
loadInstaller();
})
//...etc
});
I hope this answer will help someone else :)
Related
I got an issue here. I found out that the global variable got changed every time it got into ajax.
$(document).on("keyup input", ".product-id", function () {
var id_prod = this.id.replace('prod_id_', '');
console.log('id_prod (outside ajax): ', id_prod);
var inputVal = $(this).val();
var resultDropdown = $('#result2').css({
"display": "block"
});
if (inputVal.length) {
$.ajax({
type: 'POST',
data: { term: inputVal },
url: 'backend-search-inv.php',
success: function (data) {
resultDropdown.html(data);
$(document).on("click", "#result2 p", function () {
var inv_id = $(this).text();
//console.log('inv_id: ',inv_id);
$.ajax({
type: 'POST',
data: {
term: inv_id
},
url: 'autocomplete_inv.php',
success: function (response) {
var inv_info = jQuery.parseJSON(response);
console.log('id_prod (in ajax): ', id_prod);
},
error: function () {
console.log('Unable to access database.');
}
});
}); //end of result being clicked
}
});
}
else {
resultDropdown.empty();
}
});
I don't get it why the variable id_prod gets incremented everytime when it goes into ajax. Here is the screenshot of the console.log.
Referring to the screenshot, everytime I want to enter something to the id_prod = 2, the ajax always ended up updating the id_prod = 1, and then id_prod = 2 again automatically, and result in duplication of my data.
Can someone help me on this?
So basically I just declare the id_prod as a global variable and assigned 0 as it's default value. Then, for id_prod is basically assigned to new value once it's in the keyup input event.
Thanks to Mohamed Yousef for his answer in my own question's comment section!
//DECLARE id_prod as a global variable...
var id_prod = 0;
$(document).on("keyup input", ".product-id", function(){
id_prod = this.id.replace('prod_id_', '');
var inputVal = $(this).val();
var resultDropdown = $('#result2').css({"display":"block"});
if(inputVal.length){
$.ajax({
type: 'POST',
data: {term:inputVal},
url: 'backend-search-inv.php',
success: function(data){
resultDropdown.html(data);
}
});
}
else{
resultDropdown.empty();
}
});
// WHEN RESULT BEING CLICKED...
$(document).on("click", "#result2 p", function(){
var inv_id = $(this).text();
$.ajax({
type: 'POST',
data: {term:inv_id},
url: 'autocomplete_inv.php',
success: function (response) {
var inv_info = jQuery.parseJSON(response);
console.log('id_prod (in ajax): ',id_prod);
$('#prod_id_'+id_prod).val(inv_info[0]);
$('#prod_qty_'+id_prod).val(1);
$('#prod_disct_'+id_prod).val(0);
$('#prod_type_'+id_prod).val(inv_info[1]);
$('#prod_colour_'+id_prod).val(inv_info[2]);
$('#prod_price_'+id_prod).val(inv_info[3]);
$('#result2').empty();
sumPrice();
},
error: function(){
console.log('Unable to access database.');
}
});});
I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});
I'm very new to ajax/javascript so I will try my best to explain my problem. Here's what I have so far:
$(function () {
$("#chkFilter").on("click", "input", function (e)
{
var filterCheckboxes = new Array();
$("#chkFilter").find("input:checked").each(function () {
//console.log($(this).val()); //works fine
filterCheckboxes.push($(this).val());
console.log($(this).val());
//var filterCheckboxes = new Array();
//for (var i = 0; i < e.length; i++) {
// if (e[i].checked)
// filterCheckboxes.push(e[i].value);
//}
});
console.log("calling ajax");
$.ajax({
url: "/tools/oppy/Default.aspx",
type: "post",
dataType: "json",
data: { UpdateQuery: filterCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
});
});
Every time a checkbox is checked, ajax passes the data onto the server. Here is an example of some checkbox values after a few have been checked in the data form obtained from the Developer's Console:
You can try the following code:
filterCheckboxes.push($(this).prop("name") + "=" + $(this).val());
This is my jQuery code to add html generated by a post in a div. The slidedown() function doesn't seem to be working right. Here is my script:
$(".expand").click(function(){
var button = $(this);
var id = $(this).attr("eid");
var url = "/get-complete/" + id + '/';
$.ajax({
type: "GET",
url: url,
success: function( data ) {
var obj = $.parseJSON(data);
var lang = '';
$.each(obj, function() {
lang += this['html'] + "<br/>";
});
button.siblings('.comment-expand').slideDown('slow', function(){
button.siblings('.comment-expand').html(lang);
});
button.attr('class', 'collapse');
button.html('Collapse');
},
});
return false;
});
Here is the html:
<a class="expand" href="/#" eid="{{ event.id }}">Expand</a>
<div class="comment-expand"></div>
This is the sample data returned by the GET request:
[{"html": "\n <div class=\"comment-count-bar\">\n</div>\n "}]
This is the code to collapse the post, but this isn't working either:
$("body").delegate(".collapse", "click", function(){
var button = $(this);
button.siblings('.comment-expand').slideUp('slow');
button.attr('class', 'expand');
button.html('Expand');
return false;
});
Try this:
$.ajax({
type: "GET",
url: url,
// setting the dataType to json, jQuery itself parses the response
dataType: 'json',
success: function(data) {
// Hiding the element and setting it's innerHTML
// before calling slideDown()
button.siblings('.comment-expand').hide().html(function() {
// Mapping the response and concatenating `html` properties
// If the response has only one array use:
// return data[0].html + '<br>'; instead
return $.map(data, function(v) {
return v.html + '<br>';
}).join('');
}).slideDown();
button.addClass('collapse')
.removeClass('expand')
.html('Collapse');
},
});
Edit: Since you are adding the class dynamically you should delegate the event:
$(document).on('click', '.collapse', function() {
// var button = $(this);
// ...
});
I am appending html by taking code from data-prototype attribute from one div.
The problem is this that I am appending with two select boxes on which I want to run later jquery, as I want to update second one after choosing option from first one, it is just not executing jQuery code. Everything is alright on select boxes which are inserted when page is loading, but for those from append it doesn't work.
My jQuery Code:
var $optionDefinitions = $('.option-definitions');
var collectionHolder = $('div#epos_productsbundle_variant_options');
var $addOptionsLink = $('Add an option');
var $newLinkLi = $('<li></li>').append($addOptionsLink);
$(function() {
collectionHolder.append($newLinkLi);
collectionHolder.data('index', collectionHolder.find(':input').length);
$addOptionsLink.on('click', function(e) {
e.preventDefault();
addOptionsForm(collectionHolder, $newLinkLi);
});
function addOptionsForm(collectionHolder, $newLinkLi) {
var prototype = collectionHolder.data('prototype');
var index = collectionHolder.data('index');
var newForm = prototype.replace(/__name__/g, index);
var $newFormLi = $('<li id="subform_'+index+'"></li>').append(newForm);
$newLinkLi.before($newFormLi);
collectionHolder.data('index', index + 1);
}
$optionDefinitions.change(function(event){
var $optionid = $(this).val();
var url = '{{ path('variant_options', {'id': 'optionid' }) }}'
url = url.replace("optionid", $optionid)
$.ajax({
url: url,
dataType: "html",
success: function(data){
$(event.target).next('select').html(data);
},
error: function(){
alert('failure');
}
});
})
});
I found the problem. After append I should use on.
So instead of
$optionDefinitions.change(function(event){
var $optionid = $(this).val();
var url = '{{ path('variant_options', {'id': 'optionid' }) }}'
url = url.replace("optionid", $optionid)
$.ajax({
url: url,
dataType: "html",
success: function(data){
$(event.target).next('select').html(data);
},
error: function(){
alert('failure');
}
});
})
I got know
$(body).on('change', $optionDefinitions, function(event){
var $optionid = $(event.target).val();
var url = '{{ path('variant_options', {'id': 'optionid' }) }}'
url = url.replace("optionid", $optionid)
$.ajax({
url: url,
dataType: "html",
success: function(data){
$(event.target).next('select').html(data);
},
error: function(){
alert('failure');
}
});
})
You can try this hack. setTimeout(after, 1);
93 var self = this;
94 var after = function() {
95 self. _container = $("#container");
96 self._slidebox = $("#slidebox");
97 self._slidebox_icon = $("#slidebox_icon");
98 }
99
100 setTimeout(after,1);