Can't select json elements added dynamically with append - javascript

I am trying to make a simple cross-fade slider but this time with images retrieved from a json file and added dynamically to a container.
I can easily get all pictures with all the information inside the json file but as soon as I have to select them later I can't. It's like they are not there. It's not the first time I add dynamically a html element. I use really often .append() or .prepend() and I can as easily find their children once they are created.
So I have a div in which I load dynamically some images. I want to pick them up again (not from the json file this time, but from the dom) so I can make a slider plugin with them.
$.fn.slider = function(options) {
var picstore, $fig,
def = {
json: undefined,
dataName: 'jsonslider'
},
cfg = $.extend( true, def, options ),
store = cfg.json,
dataN = cfg.dataName,
$wrap = $( this ),
$next = $wrap.next();
$.getJSON( store, function( data ) {
picstore = data.pictures;
for ( i = 0; i < picstore.length; i++ ) {
$wrap.append( '<figure data-' + dataN +'="' + i + '"><img src="' + picstore[i].url + '" alt="' + picstore[i].alt + '"/></figure>' );
};
I tried everything!
$fig = $wrap.children() does not work
$fig = $( '[data-' + dataN + '="0"]' ) does not work
What do you suggest me to do?
demo
github index.html raw file
github js raw file
github json raw file

Here the solution.
$.getJSON( store, function( data ) {
var arr = $.map(data, function(el){ return el; });
for ( i = 0; i < arr.length; i++ ) {
$wrap.append($('<figure data-' + dataN +'="' + i + '"><img src="' + arr[i].url + '" alt="' + arr[i].alt + '"/></figure>'));
};
var figs = $wrap.children();
figs.first().addClass( 'slider-active' );
});
You can't access json dynamically objects outside the function.

Related

Nestable.js issue with callback updating textarea

I'm having an issue with nestable.js and maybe I'm using the callback incorrectly. Below is my current code and I'm loading the JSON from the php variable $primary_menu_json that is passed into the function. It creates the menu with no issues and I can move my menu elements around that are created from the JSON no problem, but it's not updating my hidden textarea (#nestableOutput) on the callback.
The way I understand the callback from the documentation is it's fired when elements are reordered or nested. In my mind this would be the place to update the hidden textarea when an element is dropped. Maybe I am wrong in this thinking. Any help?
$(document).ready(function () {
function nestableJSON(jsonArray, root) {
if (typeof root === 'undefined') {
root = $('body');
}
var $div = $('<div id="nestable02a" class="dd" data-plugin="nestable"><ol class="dd-list dd3-list"></ol></div>');
root.append($div);
for(var i = 0; i < jsonArray.length; i++) {
var $li = $("<li class='dd-item dd-item-alt' id='item-" + jsonArray[i].id + "' data-id='" + jsonArray[i].id + "' data-title='" + jsonArray[i].title + "'><div class='dd-handle'></div><div class='dd-content'>" + jsonArray[i].title + "<span class='float-right wb-trash'></span></div></li>");
root.find('ol.dd-list:first').append($li);
if (typeof jsonArray[i].children !== 'undefined') {
nestableJSON(jsonArray[i].children, $li);
}
}
$('#nestable02a').nestable({
group: 1,
maxDepth: 3,
callback: function(e){
var list = e.length ? e : $(e.target);
$('#nestableOutput').text(window.JSON.stringify(list.nestable('serialize')));
console.log('json updated');
}
});
}
nestableJSON(<?php echo $primary_menu_json; ?>);
});

CKfinder multiple image upload without CKEditor

I am using the ckfinder modal without CKEditor to upload multiple files to the form section.
I used the code provided in the documentation section,
CKfinder modal opens as expected, selected multiple file but i couldn't able to get all the images url. The response i got only the first image.
window.CKFinder = {
_popupOptions: {
'popup-1-config': { // Config ID for first popup
chooseFiles: true,
onInit: function( finder ) {
finder.on( 'files:choose', function( evt ) {
var file = evt.data.files.first();
var output = document.getElementById( 'output' );
output.innerHTML = 'Selected in popup 1: ' + file.get( 'name' ) + '<br>URL: <img src=" ' + file.getUrl() + '">';
} );
}
},
}
};
var popupWindowOptions = [
'location=no',
'menubar=no',
'toolbar=no',
'dependent=yes',
'minimizable=no',
'modal=yes',
'alwaysRaised=yes',
'resizable=yes',
'scrollbars=yes',
'width=800',
'height=600'
].join( ',' );
document.getElementById( 'popup-1-button' ).onclick = function() {
// Note that config ID is passed in configId parameter
window.open( 'http://foxhills.localhost/admin/ckfinder/ckfinder.html?popup=1&configId=popup-1-config', 'CKFinderPopup1', popupWindowOptions );
};
In the above code var file = evt.data.files.first(); is the reason why i am getting the first image. How i can change the code to get the all the urls as array.
For your event, try testing with this
finder.on( 'files:choose', function( evt ) {
var files = evt.data.files;
var chosenFiles = '';
files.forEach( function( file, i ) {
chosenFiles += ( i + 1 ) + '. ' + file.get( 'name' ) + '\n';
} );
alert( chosenFiles );
} );
Source: https://ckeditor.com/docs/ckfinder/ckfinder3/#!/api/CKFinder.Application-event-files_choose

How to get more data from json array when a value in option tag is selected jquery

I'm trying to display more info of the museum when a museum name is clicked fro the option dropdown box. I am getting my data from a json array. I was able to populate the option box with the name of the museum but could not display more details. Could anyone please help me with this. I'm using jquery for this code.
function getMuseums() {
var museumSelect = $("<select id=\"museumlist\" name=\"museumlist\" onChange=\"getMuseumInfo()\" />");
var info = $("<span>Select Museum: </span>")
$.get("museums.php",function(data,status) {
var response = '';
var json = $.parseJSON(data);
museums = json.museums;
$.each(museums, function (index, item) {
$('<option />').attr({"value" : index}).text(item.museum_name).appendTo(museumSelect);
/*response += "<option value='"+index+"'>" + item.museum_name + "</option>";
$("#museumlist").html(response);*/
});
$('#content').empty().append(info, museumSelect);
$("<div id=\"museumDetails\" />").appendTo("#MuseumDiv");
getMuseumInfo()
});
}
function getMuseumInfo() {
var museum_id = $("#museumlist").val();
selectedMuseumid = museum_id;
$("#MuseumDiv").empty().append("<div id=\"museumDetails\"/>");
var url = "museums.php?museum_id=" +escape(museum_id);
$.get(url,function(data,status) {
var json = $.parseJSON(data);
museums = json.museums;
var museum_name = museums.museum_name;
var museum_description = museums.museum_description;
var museumInfo = "<h3>" + museum_name + "</h3><p>" + museum_description + "</p>";
$("#museumDetails").empty().append(museumInfo);
});
}
You can pass option value to your function as a parameter getMuseumInfo(this.value):
var museumSelect = $("<select id=\"museumlist\" name=\"museumlist\" onChange=\"getMuseumInfo(this.value)\" />");
And than you can use iterate through museums and check if index is the same as option value, and then print only properties for that item.
$.each(museums, function(index, item) {
if (index == id) {
var museumInfo = "<h3>" + item.museum_name + "</h3><p>" + item.museum_description + "</p>";
$("#MuseumDiv").empty().append(museumInfo);
}
});
But better check working code (also turn on console in app):
codePen
NOTE:
I make example of request to create JSON data. I make get request to url:
https://api.myjson.com/bins/58j10

Parsing links from an XML files with JavaScript

To display my latest blog-posts on a different page I want to parse the rss-feed from the blog and then generate elements with it.
I first tried to parse a fixed .xml file for which I wrote the following code:
var maxBlogposts = 5;
var blogPosts = 0;
$.get("rss.xml", function(data) {
$(data).find("item").each(function() {
if(blogPosts === maxBlogposts) return;
var el = $(this);
//Only display 3 posts on small devices.
var extra = (blogPosts >= 3) ? "not-small 12u(small)" : "12u(small)";
var div = $('<div class="6u ' + extra + '" class="blog-entry"></div>');
var h = $('<h4>' + el.find("title").text() + '</h4>');
var description = el.find("description").text().replace('[…]', '[…]');
var p = $('<p>' + description + '</p>');
div.append(h);
div.append(p);
$('#blog').append(div);
blogPosts++;
});
});
This worked perfectly fine. Now I want to parse the actual rss-feed. For this I wrote a PHP script which simply gets the feed and echos it.
<?php
$rss = file_get_contents('http://xn--der-grne-baum-1ob.net/feed/');
die($rss);
?>
And again I get the correct XML file on the frontend.
The problem I have is that now my code is no longer working. Getting the description was failing as well as the links. I fixed the description by accessing
el.find(description")[0].innerHTML
However I can't seem to get the links to work. The data returned from the PHP file contains a node with the link in it. The "el"-element also contains children named "link" but those no longer contain the actual link.
I feel like the links may get "escaped" during parsing? At least that is the only reason i could think of that would result in what I am observing.
The XML I am parsing comes from http://xn--der-grne-baum-1ob.net/feed/
Try
var maxBlogposts = 5
, blogPosts = 0;
$.get("https://query.yahooapis.com/v1/public/yql?q=select"
+ " * from feed where url='http://xn--der-grne-baum-1ob.net/feed/'")
.then(function(data) {
$(data.documentElement).find("results item")
.each(function() {
if(blogPosts === maxBlogposts) return;
var el = $(this);
//Only display 3 posts on small devices.
var extra = (blogPosts >= 3) ? "not-small 12u(small)" : "12u(small)";
var div = $('<div class="6u ' + extra + '" class="blog-entry"></div>');
var h = $('<h4>' + el.find("title").text() + '</h4>');
var description = el.find("description").text().replace('[…]', '[…]');
var p = $('<p>' + description + '</p>');
div.append(h);
div.append(p);
$('#blog').append(div);
blogPosts++;
});
}, function(jqxhr, textStatus, errorThrown) {
console.log(textStatus, errorThrown)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="blog"></div>
See YQL Console

Bring from a PHP file data sent by $.ajax using Json

As I need to bring separate data from a php file, and create an HTML piece to be injected with jQuery, I've choosen Json.
I send it from my PHP main file (between script tags) like this:
$.ajax({dataType: "json", url:'course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></div></div><div class="contentColumn10"><div class="tableIconLink"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></div></div></div>';}
This sends properly editedCourseId value. And what's inside course_generator.php is:
$courseId = $_POST['co_subj_co'];
$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);
$newCourseId = $result_co['co_id'];
$newCourseName = $result_co['co_name'];
$newCourseAbbrev = $result_co['co_abbrev'];
$newCourseTypeId = $result_co['co_fk_ct_id'];
$newCourseTypeName = $result_co['ct_name'];
$isMultisubjectValue = $result_co['co_multisubject'];
$newCourseValues = '{"newCourseId":'.$newCourseId.',"newCourseName":'.$newCourseName.',"newCourseAbbrev":'.$newCourseAbbrev.',"newCourseTypeId":'.$newCourseTypeId.',"newCourseTypeName":'.$newCourseTypeName.',"isMultisubjectValue":'.$isMultisubjectValue.'}';
I am afraid Im not receiving it properly by $courseId = $_POST['co_subj_co'];, and neither $newCourseValues are being received properly on my main PHP file as my newCourseStructure is not generating anything. Could you please identify the several errors I am sure I'm making? Thank you.
UPDATE:
After changing my PHP main file to:
$.ajax({type : 'POST', dataType: "json", url:'config/forms/course_conf/course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></div></div><div class="contentColumn10"><div class="tableIconLink"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></div></div></div>';}
And my course_generator.php file to:
$courseId = intval($_POST['co_subj_co']);
$subjectList = "";
$data ="";
$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
$outArr['newCourseAbbrev'] = $result_co['co_abbrev'];
$outArr['newCourseTypeId'] = $result_co['co_fk_ct_id'];
$outArr['newCourseTypeName'] = $result_co['ct_name'];
$outArr['isMultisubjectValue'] = $result_co['co_multisubject'];
$subjectsNum=mysql_num_rows(mysql_query("SELECT * FROM co_rel_subj WHERE co_subj_co = '$courseId'"));
$outArr['subjectsNum'] = $subjectsNum;
echo json_encode($outArr);
Instead of showing the HTML piece structured, this is what $newCourseStructure results:
{"newCourseId":"243","newCourseName":"a","newCourseAbbrev":"ae","newCourseTypeId":"1","newCourseTypeName":"M\u00e1ster","isMultisubjectValue":"1","subjectList":"
Edici\u00f3n y Acabado de Imagen Digital<\/div>
","subjectsNum":1}
Your JSON string is not valid JSON because you don't use quotes around the string values. Instead of manually creating JSON, create an array or object and then json_encode() it.
You don't apper to output the JSON string. Use echo or print.
Add dataType : 'json' to your ajax request so that jQuery will parse the JSON, returning the native JavaScript object. All of the variables you use in the success function are undefined. After parsing the JSON you should use
var courseId = newCourse.newCourseId; // and so on
Your ajax request doesn't have a type and so will default to GET. add type : 'POST' if you want to use POST.
Try $_GET['co_subj_co']; instead of POST.
As long as you don't specify the method to jQuery's ajax call, it's made by GET, not POST.
I have annotated two things in the code:
$.ajax({
type : 'POST',
dataType: "json",
url:'config/forms/course_conf/course_generator.php',
data:{
co_subj_co:editedCourseId
}})
.done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow"'
+ ' data-isMultisubjectValue="' + isMultisubjectValue + '"'
+ ' data-subjectsNum="' + subjectsNum + '"'
+ ' data-id="' + courseId + '"'
+ ' id="' + courseId + '"'
+ ' data-abbrev="' + newCourseAbbrev + '"'
+ ' data-courseTypeId="' + newCourseTypeId + '"'
+ ' title="' + newCourseName + '">'
+ '<div class="contentColumn40"><span class="tableContentText">'
+ newCourseName + ' (' + newCourseTypeName + ')</span></div>'
// WHERE IS subjectList DEFINED?
+ '<div class="contentColumn40">' + subjectList
+ '</div>'
+ '<div class="contentColumn10"><div class="tableIconLink">'
+ '<a href="#"><div class="editIcon" data-id="' + courseId + '"'
+ ' title="Editar ' + newCourseName + '"></div>'
+ '</a></div></div><div class="contentColumn10"><div class="tableIconLink">'
+ '<a href="#"><div data-id="'+courseId+'" class="discontinueIcon" '
+ 'title="Discontinuar '+newCourseName+'"></div></a></div></div></div>';
/*
* your HTML is generated, but you never put it in the DOM
*/
$('#idOutputWrapper').empty().html(newCourseStructure);
}
When you use subjectList from the json response, please notice that it comes with a closing </div> tag for some reason, maybe you should change that, too.
btw: Your code formatting is horrible, sorry to say so. You can compress your js before uploading it to the server, but while working on it, it NEEDS to be readable. I just edited it to fit better in the codeblock here.
Are you actually using POST, or are you firing off a GET request (your browser's developer tools should tell you this easily). You should also make sure that $courseId is an integer by $courseId = intval($_POST['co_cubj_co']);. In addition, you should add a condition for the event that the requested ID is not found.
As MueR suggests, the reason to make sure that courseID is an integer is to prevent SQL injection (unless you want people to do things like delete your entire DB at will). This, of course, assumes that courseID is something like an autoincrement int.
However, you've got a number of other problems. Your JSON is invalid since you're ostensibly writing out unquoted strings... you should just use json_encode:
$outArr = array();
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
...
echo json_encode($outArr);
Personally, I prefer to just use $_REQUEST, which concatenates both $_POST and $_GET. Makes it easier.

Categories

Resources