I have a little problem and hoping someone with JQuery knowledge can look at my code and spot what I'm doing wrong.
I have two unordered lists (dynamically created) that get updated with ajax.
With script below I can only get one list to update but not both. I cloned first script and changed variables for second list but only one gets updated.
Thanks for you help.
Here is the html code:
List one: <ul data-options="" class="elgg-list-mainriver elgg-sync elgg-list-river elgg-river"><li> .....</li>
</ul>
List Two: <ul data-options="" class="elgg-list-miniriver elgg-sync elgg-list-river elgg-river"><li> .....</li>
</ul>
And JQuery code:
elgg.provide('elgg.river');
elgg.river.init = function() {
var riverList = $('ul.elgg-list-mainriver');
//var miniriverList = $('.elgg-list-miniriver');
var time = 20000;
if (!window.rivertimer) {
window.rivertimer = true;
var refresh_river = window.setTimeout(function(){
elgg.river.timedRefresh(riverList);
//elgg.river.MinitimedRefresh(miniriverList);
}, time);
}
};
elgg.river.timedRefresh = function(object) {
var first = $('li:first', object);
if (!first.length) {
first = object;
}
var time = first.data('timestamp');
elgg.getJSON('activity', {
data : {
sync : 'new',
time : time,
options : object.data('options')
},
success : function(output) {
if (output) {
$.each(output, function(key, val) {
var new_item = $(val).hide();
//new_item = $(val).show();
object.prepend(new_item.fadeIn(600));
//object.prepend(new_item.$(val).show());
});
}
window.rivertimer = false;
elgg.trigger_hook('success', 'elgg:river:ajax');
}
});
}
elgg.provide('elgg.river_miniriver');
elgg.river_miniriver.init = function() {
var miniriverList = $('ul.elgg-list-miniriver');
var time = 20000;
if (!window.rivertimer) {
window.rivertimer = true;
var refresh_river = window.setTimeout(function(){
elgg.river_miniriver.timedRefresh(miniriverList);
}, time);
}
};
elgg.river_miniriver.timedRefresh = function(object) {
var first = $('li:first', object);
if (!first.length) {
first = object;
}
var time = first.data('timestamp');
elgg.getJSON('activity', {
data : {
sync : 'new',
time : time,
options : object.data('options')
},
success : function(output) {
if (output) {
$.each(output, function(key, val) {
var new_item = $(val).hide();
//new_item = $(val).show();
object.prepend(new_item.fadeIn(600));
//object.prepend(new_item.$(val).show());
});
}
window.rivertimer = false;
elgg.trigger_hook('success', 'elgg:river:ajax');
}
});
}
elgg.register_hook_handler('init', 'system', elgg.river.init);
elgg.register_hook_handler('success', 'elgg:river:ajax', elgg.river.init, 500);
elgg.register_hook_handler('init', 'system', elgg.river_miniriver.init);
elgg.register_hook_handler('success', 'elgg:river:ajax', elgg.river_miniriver.init, 500);
If I try to combine both lists class in the function "$('ul.elgg-list-miniriver, ul.elgg-list-mainriver')" than both lists get updated but first list item (li) gets "opacity:0;" in style????
This code:
elgg.river_miniriver.init = function() {
var miniriverList = $('ul.elgg-list-miniriver, ul.elgg-list-mainriver');
var time = 20000;
if (!window.rivertimer) {
window.rivertimer = true;
var refresh_river = window.setTimeout(function(){
elgg.river_miniriver.timedRefresh(miniriverList);
}, time);
}
};
elgg.river_miniriver.timedRefresh = function(object) {
var first = $('li:first', object);
if (!first.length) {
first = object;
}
var time = first.data('timestamp');
elgg.getJSON('activity', {
data : {
sync : 'new',
time : time,
options : object.data('options')
},
success : function(output) {
if (output) {
$.each(output, function(key, val) {
var new_item = $(val).hide();
//new_item = $(val).show();
object.prepend(new_item.fadeIn(1000));
//object.prepend(new_item.$(val).show());
});
}
window.rivertimer = false;
elgg.trigger_hook('success', 'elgg:river:ajax');
}
});
}
Related
sorry for my english but i will try my best to ask my question correctly.
As layout i'm using this = https://codepen.io/Sool/pen/vvodgj with minor changes to support url hash.
Isotope JS Code:
$(document).ready(function($) {
var $grid = $('.grid').isotope({
// options
itemSelector: '.grid-item',
layoutMode: 'fitRows',
});
var filterFns = {
// show if number is greater than 50
numberGreaterThan50: function() {
var number = $(this).find('.number').text();
return parseInt(number, 10) > 50;
},
// show if name ends with -ium
ium: function() {
var name = $(this).find('.name').text();
return name.match(/ium$/);
}
};
function getHashFilter() {
// get filter=filterName
var matches = location.hash.match(/filter=([^&]+)/i);
var hashFilter = matches && matches[1];
return hashFilter && decodeURIComponent(hashFilter);
}
// change is-checked class on buttons
var $buttonGroup = $('.filters');
$buttonGroup.on('click', 'li', function(event) {
$buttonGroup.find('.is-checked').removeClass('is-checked');
var $button = $(event.currentTarget);
$button.addClass('is-checked');
var filterValue = $button.attr('data-filter');
// set filter in hash
location.hash = 'filter=' + encodeURIComponent(filterValue);
$grid.isotope({ filter: filterValue });
});
var isIsotopeInit = false;
function onHashchange() {
var hashFilter = getHashFilter();
if (!hashFilter && isIsotopeInit) {
return;
}
isIsotopeInit = true;
// filter isotope
$grid.isotope({
itemSelector: '.element-item',
layoutMode: 'fitRows',
// use filterFns
filter: filterFns[hashFilter] || hashFilter
});
// set selected class on button
if (hashFilter) {
$buttonGroup.find('.is-checked').removeClass('is-checked');
$buttonGroup.find('[data-filter="' + hashFilter + '"]').addClass('is-checked');
}
}
$(window).on('hashchange', onHashchange);
// trigger event handler to init Isotope
onHashchange();
})
AJAX Code:
$(document).ready(function() {
var limit = 7;
var start = 4;
var action = 'inactive';
function load_country_data(limit, start) {
$.ajax({
url: "fetch.php",
method: "POST",
data: { limit: limit, start: start },
cache: false,
success: function(data) {
$('#load_data').append(data);
if (data == '') {
$('#load_data_message').html("<button type='button'>All images loaded</button>");
action = 'active';
} else {
$('#load_data_message').html("<button type='button'>Loading images.....</button>");
action = "inactive";
}
}
});
}
if (action == 'inactive') {
action = 'active';
load_country_data(limit, start);
}
$(window).scroll(function() {
if ($(window).scrollTop() + $(document).height() > $("#load_data").height() && action == 'inactive') {
action = 'active';
start = start + limit;
setTimeout(function() {
load_country_data(limit, start);
}, 1000);
}
});
});
PHP Code to fetch data:
<?php
if(isset($_POST["limit"], $_POST["start"]))
{
include "mysqli_connection.php";
$query = "SELECT * FROM gallery ORDER BY order ASC LIMIT ".$_POST["start"].", ".$_POST["limit"]."";
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<div class="col-md-3 grid-item <?= htmlspecialchars($row["category"]) ?>" data-category="<?= htmlspecialchars($row["category"]) ?>">
<img data-src="/assets/images/gallery/<?= htmlspecialchars($row["image"]) ?>" data-srcset="/assets/images/gallery/<?= htmlspecialchars($row["image"]) ?>" class="img-fluid" alt="<?= htmlspecialchars($row["title"]) ?> Image" srcset="/assets/images/gallery/<?= htmlspecialchars($row["image"]) ?>" src="<?= htmlspecialchars($row["image"]) ?>">
</div>
<?php
}
mysqli_close($conn);
}
?>
The data is loaded from the database and everything seems to be fine. But at the same time, filtering stops working. How to make filtering work with ajax?
How to make sure that when you click on a certain category, data from a certain category is loaded? With ajax and working url hash, something like that domain.com/#filter=category1 or domain.com/#filter=category3.
I would be very grateful for any advice or help on this issue, thank you.
Below is the code which I use to upload images through dropzone.
<script>
Dropzone.options.uploaddeadlineimages = {
// The camelized version of the ID of the form element
// The configuration
paramName: 'files',
url:"<?=base_url()."Product/upload_listing_images";?>",
dictDefaultMessage: "<img src='<?=base_url()."public/images/";?>/frontend/camera-black.png'><h2>Drag and drop your photos here to upload</h2><p><a href='javascript:void(0)'>Or Click here to browse for photos</a></p>",
uploadMultiple: false,
createImageThumbnails: true,
addRemoveLinks: true,
parallelUploads:100,
dictInvalidFileType:'Please upload only valid file type(png,jpg,gif,pdf)',
clickable:true,
maxFiles:100,
autoProcessQueue: true,
success: function( file, response ) {
var return_value = response;
var old_value = $('#listing_images').val();
if(old_value=="" || old_value==" " || old_value==null){
var new_value = return_value;
}else{
var new_value = old_value+","+return_value;
}
$('#listing_images').val(new_value);
},
// The setting up of the dropzone
init: function() {
var myDropzone = this;
//alert after success
this.on('queuecomplete', function( file, resp ){
//alert('hahahahahaha');
});
// First change the button to actually tell Dropzone to process the queue.
document.getElementById("create_listing_button").addEventListener("click", function(e) {
// Make sure that the form isn't actually being sent.
});
// Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
// of the sending event because uploadMultiple is set to true.
this.on("sendingmultiple", function() {
});
this.on("successmultiple", function(files, response) {
// Gets triggered when the files have successfully been sent.
// Redirect user or notify of success.
});
this.on("errormultiple", function(files, response) {
// Gets triggered when there was an error sending the files.
// Maybe show form again, and notify user of error
});
}
}
</script>
the code has this parth which is used to append the new filename into hidden field so that i can save those names in database then. but the problem is that when i click on delete button i need to delete the name of that file from the hidden field too. I am getting an encrypted name from the server.
success: function( file, response ) {
var return_value = response;
var old_value = $('#listing_images').val();
if(old_value=="" || old_value==" " || old_value==null){
var new_value = return_value;
}else{
var new_value = old_value+","+return_value;
}
$('#listing_images').val(new_value);
},
I don't need the exact code. I just need a method by which i can pass the new filename to a function when i click on delete button. this should not prevent the delete from doing it default function
well i found an answer . just update the success part according to your need. but as in my case i needed the image name as id of preview element. it will be done in this way.
success: function( file, response ) {
var return_value = response;
var old_value = $('#listing_images').val();
if(old_value=="" || old_value==" " || old_value==null){
var new_value = return_value;
file.previewElement.id = response;
}else{
file.previewElement.id = response;
var new_value = old_value+","+return_value;
}
$('#listing_images').val(new_value);
},
to change the value of list after delete button just add the following code in dropzone.js file(just the way i did it).
the code starts from line number 274. just change it from this
removeFileEvent = (function(_this) {
return function(e) {
e.preventDefault();
e.stopPropagation();
if (file.status === Dropzone.UPLOADING) {
return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() {
return _this.removeFile(file);
});
} else {
if (_this.options.dictRemoveFileConfirmation) {
return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() {
return _this.removeFile(file);
});
} else {
return _this.removeFile(file);
}
}
};
})(this);
_ref2 = file.previewElement.querySelectorAll("[data-dz-remove]");
_results = [];
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
removeLink = _ref2[_k];
_results.push(removeLink.addEventListener("click", removeFileEvent));
}
return _results;
}
},
to this(just four lines added. do it carefully, otherwise you can mess up all)
removeFileEvent = (function(_this) {
return function(e) {
e.preventDefault();
e.stopPropagation();
if (file.status === Dropzone.UPLOADING) {
return Dropzone.confirm(_this.options.dictCancelUploadConfirmation, function() {
return _this.removeFile(file);
});
} else {
if (_this.options.dictRemoveFileConfirmation) {
return Dropzone.confirm(_this.options.dictRemoveFileConfirmation, function() {
var id = $(this).closest("div").prop("id");
update_img_list(id);
return _this.removeFile(file);
});
} else {
var id = $(this).closest("div").prop("id");
update_img_list(id);
return _this.removeFile(file);
}
}
};
})(this);
_ref2 = file.previewElement.querySelectorAll("[data-dz-remove]");
_results = [];
for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
removeLink = _ref2[_k];
_results.push(removeLink.addEventListener("click", removeFileEvent));
}
return _results;
}
},
add this function at the end of file change ('#listing_images') to ('#id_of_your_field_which_contains_the_list')
function update_img_list(id){
var list = $('#listing_images').val();
separator = ",";
var values = list.split(separator);
for(var i = 0 ; i < values.length ; i++) {
if(values[i] == id) {
values.splice(i, 1);
$('#listing_images').val(values.join(separator)) ;
}
}
return list;
}
So I'm trying to pass 2 datas from AJAX to PHP so I can insert it in my database but there seems to be something wrong.
My computation of the score is right but it seems that no value is being passed to my php file, that's why it's not inserting anything to my db.
AJAX:
<script type = "text/javascript" language="javascript">
$(document).ready(function() {
$("#finishgs").click(function(){
var scoregs = 0;
var remarkgs = "F";
var radios = document.getElementsByClassName('grammar');
for (var x=0; x<radios.length; x++){
if (radios[x].checked) {
scoregs++;
}
else
scoregs = scoregs;
}
if (scoregs >= 12){
remarkgs = "P";
}
else{
remarkgs = "F";
}
});
});
$(document).ready(function() {
$("#GTScore").click(function(event) {
$.post(
"dbinsert.php",
{ scoregs:scoregs , remarkgs: remarkgs},
function(data){
$('#inputhere').html(data);
}
);
});
});
PHP:
if( $_REQUEST["scoregs"] || $_REQUEST["remarkgs"]) {
$scoregs = $_REQUEST['scoregs'];
$remarkgs = $_REQUEST['remarkgs'];
}
There is an extra closing bracket );, you should remove. Try this:
$(document).ready(function() {
$("#GTScore").click(function(event) {
event.preventDefault();//to prevent default submit
$.ajax({
type:'POST',
url: "dbinsert.php",
{
scoregs:scoregs ,
remarkgs: remarkgs
},
success: function(data){
$('#inputhere').html(data);
}
});
});
And in php, you need to echo the variable or success/fail message after you insert data into the database:
echo $scoregs;
echo $remarkgs;
I am using Laravel 4.1 and created a global filter which redirects to a particular page if any of the following value is null.
Name
email
DOB
Religion
Caste
In the above values Caste is populated dynamically. When the religion value is changed. Everything was working fine With the below code in filter.php:
if (is_null(value->name)) {
return Redirect::to('confirm');
}
if (is_null(value->email)) {
return Redirect::to('confirm');
}
if (is_null($value->dob) {
return Redirect::to('confirm');
}
But when I added Religion or caste or both. The jQuery in the page crashes that is the dropdown isn't populating properly and the entire browser hangs.
if (is_null(value->name)) {
return Redirect::to('confirm');
}
if (is_null(value->email)) {
return Redirect::to('confirm');
}
if (is_null($value->dob) {
return Redirect::to('confirm');
}
if (is_null($value->religion) {
return Redirect::to('confirm');
}
if (is_null($value->caste) {
return Redirect::to('confirm');
}
I don't why it is happening; the first three work completely fine.
jQuery:
var Religion = '#Religion' ;
var Caste = '#Caste' ;
var caste = new Array();
var usr ;
$(function () {
$.ajaxSetup({
async: false
});
usr = getUser();
if(!$.isEmptyObject(usr))
{
var data = getCasteForReligion(usr.religionid) ;
if (data != null) {
// alert(data);
caste = new Array();
for (var i = 0; i < data.length; i++) {
caste.push(data[i]);
}
loadCastes(caste);
}
if(user.casteid != null)
{
$(Caste).val(usr.casteid).trigger('list:updated');
}
}
$(Religion).change(function () {
if ($(Religion).val() != "") {
var data = getCasteForReligion($(Religion).val());
if (data != null) {
// alert(data);
caste = new Array();
for (var i = 0; i < data.length; i++) {
caste.push(data[i]);
}
loadCastes(caste);
}
}
else {
}
});
});
function getCasteForReligion(religionid) {
var result;
$.get('/getCastes',
{ religionId : religionid },
function(data) {
result = data;
});
return result;
}
function getUser() {
var result;
$.get( '/User',
{ },
function(data) {
result = data;
});
return result;
}
//Generate Products variant for Indent
function loadCastes(castlst) {
$(Caste).find('option').remove();
$(Caste).val('').trigger('list:updated');
$(Caste).append(new Option("--Select--", "")).trigger('list:updated');
for (var i = 0; i < castlst.length; i++) {
$(Caste).append(new Option(castlst[i].name, castlst[i].id)).trigger('list:updated');
}
}
I have a PHP process which updates files, and writes a status report with each file.
While that is happening, I was hoping to update the user's browser until the final response.
Unless there is a better way, I simply wanted some advice on how to loop infinitely refreshing getJSON() results until the ajax response comes.
What is the best way to do this?
This ended up being the solution I used:
$(document).on('click', "#ss_batch_edit_processing", function (e) {
var ids = get_selected();
var status_location = '<?php echo symbiostock_TMPDIR . '/report.txt' ?>';
if(ids == 0){
return;
}
$('.' + loading_icon_small).show();
var data = {
action: 'ss_professional_ajax',
security: '<?php echo $ajax_nonce; ?>',
reprocessing_action: $('input:radio[name=ss_reprocessing_action]:checked').val(),
ids: ids,
};
var completed = 0;
$.post(ajaxurl, data, function (response) {
$('.' + loading_icon_small).hide();
completed = 1;
});
var get_update = function(){
$.getJSON(status_location, function (data) {
var update = '<ul><li><strong>'+data['title']+'</strong></li><li><strong>Count:</strong> '+data['count']+' / '+data['total']+'</li><li><strong>Last processed</strong>: Image # '+data['last_id']+'</li></ul>';
$('#ss-reprocessing-results').html(update).delay(1000);
});
if(completed == 1){
clearInterval(timed_requests)
return false;
}
};
var interval = 1000; // every 1 second
var timed_requests = setInterval(get_update, interval);
});