populating a unite gallery using ajax - javascript

Hi i am currently trying to populate a unite gallery using ajax however the gallery is just hanging with a loading icon and not displaying any of the images any help with be appreciated
Ajax
$('document').ready(function () {
var folder = "http://localhost/client%20side%20web%20coursework/files/";
jQuery("#gallery").unitegallery();
$.ajax({
url: folder,
asynch: false,
cache: false,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if (val.match(/\.(jpe?g|png|gif)$/)) {
$("#gallery").append("<img alt='uploaded file' src='" + folder + val + "'data-image='" + folder + val + "'data-description='uploaded file by user'>'");
}
});
}
});
});
div we are trying to populate
<div id="gallery" style="display:none;">
</div>
the documentation for unite gallery can be found here for anyone who is not familiar with it http://unitegallery.net/index.php?page=documentation#installing_the_gallery
Any help will be appreciated

$('document').ready(function(){
var folder = "http://localhost/client%20side%20web%20coursework/files/";
$.ajax({
url : folder,
asynch : false,
cache : false,
success: function (data) {
var $gallery = $("#gallery");
var imgsToAppend = '';
$(data).find("a").each(function(i, el) {
var val = $(el).attr('href');
if (val.match(/\.(jpe?g|png|gif)$/)) {
imgsToAppend+="<img alt='uploaded file' src='" + folder + val + "' data-image='" + folder + val + "' data-description='uploaded file by user'>";
}
});
if(imgsToAppend){
$gallery.append(imgsToAppend);
}
$gallery.unitegallery();
}
});
});
This solved the problem. Thanks for the help anyway.

You make a ajax request to the folder wich contains your images? is there a index.php or a index.html wich retruns you a html?
You have some useless additional quotes in your .append argument, try with this :
$("#gallery").append("<img alt='uploaded file' src='" + folder + val + "' data-image='" + folder + val + "' data-description='uploaded file by user'>");
And do a console.log(data) after the ajax response, if you have nothing, add the error calback to your ajax function and console.log the error, or see the response in your browser console in the network tab
EDIT
I think that the jQuery .find function doesn't accept any callback arguments, you would use the .each function:
var $gallery = $("#gallery");
$(data).find("a").each(function(i, el) {
var val = $(el).attr('href');
if (val.match(/\.(jpe?g|png|gif)$/)) {
$gallery.append("<img alt='uploaded file' src='" + folder + val + "' data-image='" + folder + val + "' data-description='uploaded file by user'>");
}
});

Related

PHP generated option list only appearing on first Ajax dynamically generated container

I am having an issue where my php generated select/option list is not applying to all of my dynamically generated blocks/containers. It only adds the PHP select to the last container/block instance, despite being called for each container. When troubleshooting with alerts it seems to run through all of the iterations prior to adding the containers/blocks and generating the select, hence why it always appears on the last only-
n = -1
function addDiv() {
n++;
So, a brief overview - on page initialize the code will get how many entries are in the database within a certain criteria and apply that number to 'length', which then runs the function addDiv() that many times. Usually, when adding a block one at a time via button it will populate the created block with a Select/list of Options via php in the addDiv() function, however when automating this with a loop ( the initialize() function ) the above issue occurs.
$( document ).ready(function() {
initialize();
});
function initialize() {
$.ajax({
url: 'get-entries.php',
type: 'POST',
dataType: 'text',
cache: false,
success: function(data) {
result = data;
var arrayJson = JSON.parse(data);
console.log(arrayJson);
length = arrayJson.length;
console.log(length);
for(var i = 0; i < length; i++) {
addDiv();
};
},
error: function(jqXHR) {
alert("Error while fetching data");
console.log("Error while fetching data: " + jqXHR.status + " " + jqXHR.statusText + " " + jqXHR.responseText); //improved error logging
}
});
};
here is the addDiv related code with some redactions to make it easier to read.
var n = -1;
function addDiv() {
n++;
$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + n).html(data);
});
$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");
}
and finally here is the contents of the PHP file for generating the option list based off of json data -
<?php
$json = file_get_contents("../ticker/full.json");
$decode = json_decode($json, true);
sort($decode);
echo '<select name="coinname">';
foreach($decode as $a){
echo "<option value='{$a['id']}'>{$a['name']}</option>";
}
echo '</select>';
?>
I know this is messy and may require a bit of an in depth read through, so I appreciate anyone taking the time to look.
Is there anything glaringly obvious that can help nudge me in the right direction? I have tried breaking the 'addDiv()' calls within initialize() by wrapping 'addDiv()' with a setTimeout function, but no joy.
it should work with this (I named the arguments differently for comprehension, but index and index_t can all be named n):
var n = -1;
function sendToGenerator(index){
var index_t = index;
$.post(
"json-option-generator.php",
{}
).done(
function(data)
{
$('#selectedcoin' + index_t).html(data);
}
);
}
function addDiv() {
n++;
sendToGenerator(n);
$("<div class='coinmarketcap fill' id='container"
+ n +
"'><form id='"
+ n +
"' name='"
+ n +
"' class='formClass' method='post' action=''><select onchange='mySelect(this)' type='text' class='coinname' id='selectedcoin"
+ n +
"' name='selectedcoin"
+ n +
//.etc.....
"' autocomplete='off' value=''><select></select>").appendTo(".main-container");
}

Update: How do I dynamically populate a list with data from a JSON file?

I want to dynamically populate a list with elements from a JSON file. The idea is to switch the test_ID in the list with the actual object from the JSON file. How do I do this?
JSON file
[
{
"id": "a",
"test": "Java",
"testDate": "2016-08-01"
},
{
"id": "b",
"test":"JavaScript",
"testDate": "2016-08-01"
}
]
jQuery
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
});
$("#test_ID").empty(); //emtpy the UL before starting
$.each(arr_json, function(i, v, d) {
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
});
}
});
});
HTML
<li id="test_ID"></li>
I do receive a couple of errors. The Line:
$("#test_ID").append("<li id='" + v.id +'" + v.test +"' >" + v.testDate + "<li>");
gives the following error: invalid number of arguments and unclosed String literal.
I am also unsure of how to identify to specific elements in the JSON file.
Update
I would like if the list element was in this format "Java 2016-08-01" and "JavaScript 2016-08-01". Thank you!
You have a couple of errors in your javascript. See the corrected version below:
$(function(){
$.ajax({
type : 'GET',
url : 'json/data.json',
async : false,
beforeSend : function(){/*loading*/},
dataType : 'json',
success : function(result) {
$("#test_ID").empty(); //emtpy the UL before starting
// **************** correction made to the line below ***********************
$.each(result, function(i, v, d) {
// **************** correction made to the line below ***********************
$("#test_ID").append('<li id="' + v.id + '">' + v.test + ' ' + v.testDate + '</li>'); // correction made here
});
}
});
});
I did a quick fiddle. I don't quite understand what you're doing with v.test being unmarked inside the HTML tags so I did not include it. I used minimal JQuery to avoid complexity.
https://jsfiddle.net/ndx5da97/
for (record in data) {
$("#test_ID").append('<li id="' + data[record].id + '">' + data[record].testDate + '</li>');
}
Hope this helps!

how to show the loader dynamically until all the image load in jquery mobile phonegap listview

am having trouble to showing loader untill all the image is load in the listview.the following code is used in my app.it shows the loader untill all the image is load but the problem is , append the last src value to all the image attribute src.please help me.
$.ajax({
url: "http://www.some.com/",
type: 'POST',
data: param,
dataType: "jsonp",
success: function (result) {
$.each(result.results, function (k, v) {
var searchPic = "http://www.some.com" + $.trim(v.eventIcon);
var localarray = new Array();
var c = v.eventText;
strs = c.slice(0, 60);
$('[data-role="listview"]').append('<li> ' + '<img alt="img" class="pic1" src=" ">' + '<h4 >' + v.eventTitle + '</h4>' + '<p>' + strs + '...' + '</p></li>');
$('[data-role="listview"]').listview('refresh');
imgload(searchPic);
});
$('[data-role="listview"]').append('<li id="no-results">There is no record found based on your search criteria, please refine your search.</li>');
}
});
function imgload(tx) {
$('.pic1').load(function () {
$.mobile.loading('hide');
}).attr('src', tx);
}
});

JQuery, HTML5 Uploader - get data response after upload

How can I get data response after uploading image and insert that response into a tag as data-id attribute (after successful post I am getting id of inserted image ). Where in the function is happening this? The function:
function img_upload(url) {
{
var fileTemplate = "<div id=\"{{id}}\">";
fileTemplate += "<div class=\"preview\"></div>";
fileTemplate += "<div class=\"filename\">{{filename}}</div>";
fileTemplate += "ObriĊĦi Sliku";
fileTemplate += "</div>";
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
return text;
}
$("#dropbox").html5Uploader({
postUrl: url,
onClientLoadStart: function (e, file, data) {
var upload = $("#upload");
if (upload.is(":hidden")) {
upload.show();
}
upload.append(fileTemplate.replace(/{{id}}/g, slugify(file.name)).replace(/{{filename}}/g, file.name));
console.log(data);
},
onClientLoad: function (e, file) {
$("#" + slugify(file.name))
.find(".preview")
.append("<img class=img_upload title=\"" + file.name + "\" src=\"" + e.target.result + "\" alt=\"\">")
.on('click', function () {
img_name = $(this).find('.img_upload').attr('title'),
url = '<?php echo base_url() ?>admin/galerija_naslovna_slika/' + img_name.replace(/\s/g, "_") + '/' + id;
$.post(url);
});
var img_delete = $('.image_delete');
delete_image(img_delete);
},
onServerLoad: function (e, file) {
}
});
}
}
I know this is old, But what I do is pass the id in the postURL.
So something like: /image_upload/212/
You need to use apache's mod_rewrite though to get to your php file. And then you can simply look at the request path to get the ID.
Or the other way to do it is pass the ID as a POST var.
You could have a hidden "input" with the id as the value.
docid = $('#docid').val();
$.ajax({
url: '/upload.php',
type: "POST",
data: {'docid': docid},
success: function(data, status, jqXHR) {
set_status('info', 'Success!');
},
error: function(jqXHR, status, err) {
set_status('danger', 'Error: ' + err + ' - ' + status);
},
complete: function(jqXHR, status) {
}
});

Array and while loop: make unique clickable

I have an array (via ajax) that looks like this:
data[i].id: gives the id of user i
data[i].name: gives the name of user i
I want to output the array like this:
X Leonardo Da Vinci
X Albert Einstein
X William Shakespeare
...
The X is an image (x.gif) that must be clickable. On click, it must go to functiontwo(), passing the parameter data[i].id. Functiontwo will open a jquery dialog with the question "Delete id data[i].id"?
I know this can't be too hard to do, but I can't seem to figure it out...
This is what I have so far:
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
$("." + data[i].id + "").click(function () {
functiontwo(myvar);
});
i++;
}
}
});
}
function functiontwo(id) {
...}
I know why this isn't working. Var i gets populated again and again in the while loop. When the while loop stops, i is just a number (in this case the array length), and the jquery becomes (for example):
$("." + data[4].id + "").click(function () {
functiontwo(myvar);
});
, making only the last X clickable.
How can I fix this?
Thanks a lot!!!
EDIT:
This is my 2nd function:
function functiontwo(id) {
$("#dialogdelete").dialog("open");
$('#submitbutton').click(function () {
$('#submitbutton').hide();
$('.loading').show();
$.ajax({
type : 'POST',
url : 'delete.php',
dataType : 'json',
data: {
id : id
},
success : function(data){
var mess = data;
$('.loading').hide();
$('#message').html(mess).fadeIn('fast');
}
});
//cancel the submit button default behaviours
return false;
});
}
In delete.php there's nothing special, I used $_POST['id'].
As I pointed out in my comment. The problem is the .click part. Either use bind, or use a class for all the elements, and a click-event like this $('.classnamehere').live('click',function () { // stuff });
function functionone() {
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
success : function(data){
var message = "";
var i = 0;
while (i < (data.length - 1))
{
var myvar = data[i].id;
message = message + "<div class=\"clickable\" id=" + data[i].id + "><img src=x.gif></div>" + data[i].name + "<br />";
$('#somediv').html(message).fadeIn('fast');
i++;
}
}
});
}
$('.clickable').live('click',function () {
alert($(this).attr('id') + ' this is your ID');
});
The usual trick is create a separate function to create the event handler. The separate function will receive i as a parameter and the generated event will be able to keep this variable for itself
make_event_handler(name){
return function(){
functiontwo(name);
};
}
...
$("." + data[i].id + "").click( make_event_handler(myvar) );

Categories

Resources