How to to create as much dynamicEl, as we received from PHP - php

On main page have Gallery, on click a image need open lightGallery slideshow with images that found on ftp directory, with gallery name that clicked on main page.
PHP for finding images and count it:
<?php
header("Content-Type: application/json");
$dirname = $_POST["galleryName"];
$imgGallery = glob("../gallery/" . $dirname . "/".$dirname."_*.*");
$thumbGallery = glob("../gallery/" . $dirname . "/thumb_*.*");
$countImages = count($imgGallery);
echo json_encode(array("imgNormal" => $imgGallery, "imgThumb" => $thumbGallery, "imgCount" => $countImages));
?>
JS:
$('.info').click(function() {
var galleryName = $(this).closest('.imgGallery').find('img.img-thumbnail').attr('name');
$.ajax({
url: "gallery/imgFinder.php",
dataType: "json",
type: "post",
data: {
galleryName: galleryName
},
success: function(xhr) {
if (xhr.imgCount != 0) {
console.log(xhr.imgNormal);
console.log(xhr.imgThumb);
console.log(xhr.imgCount);
for (var i = 1; i <= xhr.imgCount; i++) {
$(this).lightGallery({
dynamic: true,
dynamicEl: [{ //We need to create as much as we received w "xhr.imgCount"
"src": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg",
"thumb": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg"
}]
})
return;
}
} else {
console.log('Gallery \'' + galleryName + '\' has no images');
return;
}
},
error: function(xhr) {
console.error("Some error found");
}
});
});
We need to create as much dynamicEl with image/thumb variables, as we received xhr.imgCount
To get something like this:
dynamicEl: [{
"src": '...',
'thumb': '...'
}, {
'src': '...',
'thumb': '...'
}, {
'src': '...',
'thumb': '...'
}, {
'src': '...',
'thumb': '...'
}]

inside your JS code you needs to be updated something like below:
if (xhr.imgCount != 0) {
console.log(xhr.imgNormal);
console.log(xhr.imgThumb);
console.log(xhr.imgCount);
var dynamicEls = [];
for (var i = 0; i <= xhr.imgCount; i++) {
dynamicEls[i] = {
"src": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg",
"thumb": "/gallery/" + galleryName + "/" + galleryName + "_" + i + ".jpg"
};
}
dynamicEls.pop(); //For remove unrealized last url/data
$(this).lightGallery({
dynamic: true,
dynamicEl: dynamicEls
});
}
So, I am using and temp variable dynamicEls and after the loop filling it in correct position.

Related

Uncaught TypeError. Item.replace is not a function, autoComplete plugin

I'm using jQuery plugin autoComplete https://goodies.pixabay.com/jquery/auto-complete/demo.html, and I'm trying to use their ajax request unfortunately I got an error.
It says the
item.replace is not a function at object.renderItem
$.fn.autoComplete.defaults = {
source: 0,
minChars: 3,
delay: 150,
cache: 1,
menuClass: '',
renderItem: function (item, search){
// escape special characters
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
return '<div class="autocomplete-suggestion" data-val="' + item + '">' + item.replace(re, "<b>$1</b>") + '</div>';
},
onSelect: function(e, term, item){}
};
Here is my code
$('.to_msg').autoComplete({
source: function(term, response){
$.getJSON('ajax/auto_complete_ajax.php', { q: term },
function(data){
response(data);
});
}
});
And my PHP response
$recipient = $_GET['q'];
$a_json = array();
$a_json_row = array();
//restrict the store
$query_filter = $db->query("SELECT * from master_data.user_account where Name like '%$recipient%'");
while($result_filter = $query_filter->whileFetch()){
$name = htmlentities(stripcslashes($result_filter['Name']));
$user_id = htmlentities(stripcslashes($result_filter['user_id']));
$a_json_row['user_id'] = $user_id;
$a_json_row['value'] = $name;
$a_json_row['label'] = $name;
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
flush();
Here is the JSON output
[
{"user_id":"5","value":"Melde Feliciano ","label":"Melde Feliciano "},
{"user_id":"46","value":"Melanie Charlton ","label":"Melanie Charlton "}
]
item in renderItem(item, search) is an object. Try replacing item.replace() with item.label.replace().
$.fn.autoComplete.defaults = {
source: 0,
minChars: 3,
delay: 150,
cache: 1,
menuClass: '',
renderItem: function (item, search){
// escape special characters
search = search.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
var re = new RegExp("(" + search.split(' ').join('|') + ")", "gi");
return '<div class="autocomplete-suggestion" data-val="' + item.value + '">' + item.label.replace(re, "<b>$1</b>") + '</div>';
},
onSelect: function(e, term, item){}
};

ajax function doesn't work when referred to from instagram

My function seems to return nothing for the destination element when the link is referred to from Instagram. It works fine if I directly visit the page.
function getTeamsByLeague(league) {
//console.log("League Set: " + league);
$.ajax({
url: "<?php echo SITE_BASE_URL; ?>json.php",
data: {method: "getteamsbyregion", league: league},
success: function (data) {
if (data && data.length > 0) {
$("#destination").empty();
var selected = "";
$.each(data, function (index, item) {
if (item.team == teamSelected) {
selected = " selected";
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
} else {
selected = "";
}
$("#destination").append('<option ' + selected + ' value="' + item.lat + ',' + item.lng + '">' + item.team + '</option>');
if (index == 0) {
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
}
});
}
},
type: "GET",
dataType: "json"
});
}

Returned JSON not displaying a value

I have a jQuery script that returns JSON data and for some reason a specific value is not displayed and I don't know why since all the other properties are displayed fine. The value that is not working correctly is data.code.
$(document).ready(function() {
$(".cos").click(function(e) {
e.preventDefault();
var href = $(this).attr('href');
var produs_href = $(this).closest('.productinfo').find('a:first').attr('href');
var id_prod = $(this).data('id');
var color = $(this).closest(".col-sm-4").find(".selected").data("color");
if (typeof color === 'undefined') {
alert ("selecteaza o culoare!");
} else {
$.getJSON(href + '&color=' + color).done(function(data) {
$.each(data, function(key, val) {
$("#cnt").empty();
$("#cnt").append('' + val.cnt + '');
$.ajax({
url: "/engine/shop/produse_cos_popup.php?id=" + id_prod + "&color=" + color,
type: "GET",
datatype: 'json',
success: function(data) {
$('#qty').html('Cantitate: ' + data.qty + '');
$('.nr_prod').html('' + data.qty_total + 'produse în cosul dvs');
$('#nume').html('' + data.nume + '');
$('#pret').html('' + data.pret_total + '');
if (data.poza!='') {
$('.produs_img').html(data.poza);
} else {
$('.produs_img').html('<img class="img-responsive" src="/images/no_photo.jpg">');
}
$('#cod').html('<b>Cod Produs:</b ' + data.code + '');
$('#culoare').html('<b>Culoare:</b> ' + data.culoare + '');
$('#greutate').html('<b>Greutate:</b> ' + data.greutate +'');
$('#viteza').html('<b>Viteza maximă:</b> ' + data.viteza + '');
$('#autonomie').html('<b>Autonomie:</b> ' + data.autonomie + '');
$('#putere').html('<b>Putere motor:</b> ' + data.putere + '');
$('#detalii_prod').modal('show');
}
});
});
});
}
});
});
Here is the JSON returned. As you can see the variable code is there. It displays `Cod Produs: but without the value.
{
"qty": "4",
"poza": "<img class=\"img-responsive\" src=\"images\/trotineta_verde.png\">",
"id": "1",
"nume": "Eco",
"code": "etw1",
"greutate": "10.7 kg",
"viteza": "27 km\/h",
"autonomie": "30 km",
"putere": "350 Watt",
"culoare": "verde",
"pret_total": "37560",
"qty_total": "18"
}
You are not closing the </b
Change
$('#cod').html('<b>Cod Produs:</b ' + data.code + '');
For
$('#cod').html('<b>Cod Produs:</b> ' + data.code + '');

jquery ajax returning text of php script instead of json

I have a php script that works correctly when executed directly:
The PHP:
<?php
header('Content-Type: application/json');
$fileName = "../appfiles/Courses.json";
if (file_exists($fileName))
{
$json = json_decode(file_get_contents($fileName), true);
echo json_encode($json);
}
else
{
echo "The file $fileName does not exist";
}
;
?>
Running
http://localhost/RickVideos/php/getRegCourses.php
, I get:
[{"coursecode":"ACCTD_001","cflag":"Y","pflag":"Y","dateregistered":"08\/11\/14","timeregistered":"12:55 pm."},{"coursecode":"LWPRG1_004","cflag":"Y","pflag":"Y","dateregistered":"08\/18\/14","timeregistered":"3:30 pm."},{"coursecode":"LWPRG2_005","cflag":"Y","pflag":"Y","dateregistered":"08\/18\/14","timeregistered":"3:32 pm."}]
Trying to run the php from jquery ajax, what returns seems to be the text of the script rather than the json data.
JavaScript:
// registered courses
var registeredCourses = {
init: function ()
{
$.ajax(
{
type: 'POST',
dataType: "JSON",
url: "php/getRegCourses.php",
}
)
.done(function(data)
{
$.each(data, function(index, element)
{
$('#registeredCourses').append(
$('<option value="' + index + '">' + this['coursecode'] + '</option>')
);
}
);
$('#registeredCourses').val('0');
$("#registeredCourses").trigger('chosen:updated');
registeredCourses.getSelected();
}
)
.fail (function(jqXHR, textStatus, errorThrown )
{
alert('request failed :'+errorThrown);
alert ('textStatus :'+textStatus);
console.log(jqXHR);
}
);
},
getSelected: function ()
{
$.ajax(
{
type: 'GET',
url: "getSelCourseInfo.php",
data:
{
course: $("#registeredCourses option:selected").text()
}
}
)
.done(function( data )
{
$("#courseCode").val($("#registeredCourses option:selected").text());
$("#courseTitle").val(data.Title);
$("#projectManager").val(data.ProjectManager);
$("#initRegDate").val (data.LastModDate + ' at ' + data.LastModTime);
var tasks = [ ];
$.each(data.ProjectTasks, function(i, item)
{
$("#projectTasks").append(
'<tr>' +
'<td>' + this + '</td>' +
'</tr>'
);
tasks[i] = this;
}
);
var projectMems = [ ];
$.each(data.ProjectMembers, function(i, item)
{
$("#projectMembers").append(
'<tr>' +
'<td>' + this.PersonName + '</td>' +
'<td>' + this.EmailAddress + '</td>' +
'</tr>'
);
projectMems[i] = this.PersonName;
}
);
$("#selectedCourseData").find("tr:gt(0)").remove();
$.each(data.Chapters, function(i, item)
{
$("#selectedCourseData").append(
'<tr>' +
'<td>' + this.label + '</td>' +
'<td>' + this.title + '</td>' +
'<td>' + registeredCourses.makeList('Sciptwriter1', i, projectMems, this.ScriptWriter) + '</td>' +
'<td>' + registeredCourses.makeList('Recorder1', i, projectMems, this.Recorder) + '</td>' +
'<td>' + registeredCourses.makeList('Status1', i, tasks, this.Status) + '</td>' +
'<td>' + registeredCourses.makeList('Assignedto1', i, projectMems, this.Assignedto) + '</td>' +
'</tr>'
);
}
);
}
);
},
makeList: function (cname, num, array, selected)
{
var string = '<select class="' + cname +'">';
if (selected== " " && array[0] != " ")
{
array.splice(0, 0, " ");
};
for (var i=0; i < array.length; i++)
{
if (array[i]==selected)
{
string = string + '<option value="' + array[i] + '" selected>' + array[i] + '</option>';
}
else
{
string = string + '<option value="' + array[i] + '">' + array[i] + '</option>';
};
};
string = string + '</select>';
return string;
}
};
The first alert shows:
request failed :SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
The second alert shows:
textStatus :parsererror
And the response text for the jqXHR object shows:
"<?php header('Content-Type: application/json'); $fileName = "../appfiles/Courses.json"; if (file_exists($fileName)) { $json = json_decode(file_get_contents($fileName), true); echo json_encode($json); } else { echo "The file $fileName does not exist"; } ; ?> "
Why is the text of the script showing rather than the json data?
Not sure if this helps or not but the following code works for me. Set up a directory with your json, your php, and an html file for basically just populating the select menu. This works fine for me and when taking a look at your code there were some js errors:
$('<option value="' + index + '">' + this['coursecode'] +/option>') is missing the '< before the option close tag
Also missing a } after you ) at the end of fail. After fixing those files your code worked for me as far as populating the dropdown, though you get js errors because registeredCourses.getSelected(); doesn't exist. Which makes me wonder if the above code is complete?
If all that doesn't help then have you looked at teh raw html that is output when you go directly to your php file, like viewing the source?
`bonk.php`
<?php
header('Content-Type: application/json');
$fileName = "courses.json";
if (file_exists($fileName))
{
$json = json_decode(file_get_contents($fileName), true);
echo json_encode($json);
}
else
{
echo "The file $fileName does not exist";
}
;
?>
`courses.json`
[
{
"coursecode": "ACCTD_001",
"cflag": "Y",
"pflag": "Y",
"dateregistered": "08/11/14",
"timeregistered": "12:55 pm."
},
{
"coursecode": "LWPRG1_004",
"cflag": "Y",
"pflag": "Y",
"dateregistered": "08/18/14",
"timeregistered": "3:30 pm."
},
{
"coursecode": "LWPRG2_005",
"cflag": "Y",
"pflag": "Y",
"dateregistered": "08/18/14",
"timeregistered": "3:32 pm."
}
]
`html file`
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var registeredCourses = {
init: function (){
$.ajax ({
type: 'GET',
dataType: "JSON",
url: "bonk.php",
})
.done(function(data){
$.each(data, function(index, element){
$('#registeredCourses')
.append($("<option></option>")
.attr("value",index)
.text(this['coursecode']));
});
})
.fail (function(jqXHR, textStatus, errorThrown){
console.log(errorThrown, textStatus, jqXHR);
})
}
};
registeredCourses.init();
</script>
</head>
<body>
<select name="test" id="registeredCourses"></select>
</body>
</html>
I coverted both the php file and the Courses.json file to utf-8 and it now runs.

Getting Thumbnail from RSS Feed and Display in Listview

i need some help with my RSS Feed Reader Script...
I want Thumbnails in my Listview taken from Rss Feeds Thumbnail
"content": [
{
"medium": "image",
"url": "http://www......de/wp-content/uploads/2010/11/sgroth_web.jpg",
"title": {
"type": "html",
"content": "sgroth_web"
},
"description": {
"type": "html",
"content": "contenthere 4."
},
"thumbnail": {
"url": "http://www.sdddd.de/wp-content/uploads/2010/11/sgroth_web-150x150.jpg"
}
have a look what i mean:
Preview
First comes the Thumbnail and then the Title of the Rss Feed..
This Code is Jquery and PHP...
and here is my Code to Display RssFeeds in JS:
$(function(){
getOnlineFeed('http://salzstreuner.de/category/aktuelle_ausgabe/feed');
});
/* functions */
var listEntries = function(json) {
if (!json.responseData.feed.entries) return false;
$('#widgetTitle').text(json.responseData.feed.title);
var articleLength =json.responseData.feed.entries.length;
articleLength = (articleLength > maxLength) ? maxLength : articleLength;
for (var i = 1; i <= articleLength ; i++) {
var entry = json.responseData.feed.entries[i-1];
$('#link' + i).text(entry.title);
$('#articleHeader' + i).text(entry.title);
$('#openButton' + i).attr('href', entry.link);
$('#articleContent' + i).append(entry.content);
$('#articleImage').append('<img src="' + entry.thumbnail + '">');
}
$('#article1 .prevButton').remove();
$('#article' + articleLength + ' .nextButton').remove();
if (articleLength < maxLength) {
for (i = articleLength + 1; i <= maxLength; i++) {
$('#list' + i).remove();
$('#article' + i).remove();
}
}
};
var getOnlineFeed = function(url) {
var script = document.createElement('script');
script.setAttribute('src', 'http://ajax.googleapis.com/ajax/services/feed/load?callback=listEntries&hl=ja&output=json-in-script&q='
+ encodeURIComponent(url)
+ '&v=1.0&num=' + maxLength);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
var getOfflineFeed = function(url) {
var script = document.createElement('script');
script.setAttribute('src', url);
script.setAttribute('type', 'text/javascript');
document.documentElement.firstChild.appendChild(script);
};
Output looks like This:
for(var i=1; i<=maxLength; i++){
document.write(
'<li id="list' + i + '"><img src="#articleImage"/> </li>'
);
I have Played with #articleImage but it doesn't work. I hope someone Outside can help me with this littleBig Problem...
THX
MAsterluke
You should use the url of the thumbnail:
('#articleImage').append('<img src="' + entry.thumbnail.url + '">');

Categories