add a variable in an id attribute in ajax's div.append - ajax

I am developing a web app with Django and i have this ajax where i'm refreshing some images from the db in order to display them in a template.
function refreshUploadedImages() {
var inputs = ['Designer Name', 'Color', 'Fabric', 'Type', 'Tag', 'Subtag'];
$.getJSON('/admin/image-uploader/images', function(data) {
$('#uploadedFiles').empty();
for (uiid in data) {
ui = data[uiid];
var div = $('<div>');
div.data('id', ui.id);
// image
var image = new Image();
image.src = ui.url
image.width = 180;
div.append($('<div>').append(image));
// list
var ul = $('<ul>')
div.append(ul)
// inputs
for (input in inputs) {
ul.append(
$('<li>').append(
$('<label>').append(
$('<span>').append(document.createTextNode(inputs[input] + ':'))
).append($('<input>'))));
}
$('#uploadedFiles').append(div);
div.append('<li><input type="button" class="delete-img-btn" id = <<ui.id>> img-id=image.id value="Delete"/></li>');
}
$(window).trigger('uploadedImagesRefresh');
});
$(function(){
//
$('.delete-img-btn').live('click', function() {
//asign the image id from the button attribute 'img-id'
var id= $(this).attr('img-id');
//The data to be send via ajax the server will recieve 2 POST variables ie. 'action' and 'id'(which is the img id)
var data={
'action':'/admin/image-uploader/',
'pk' : id,
'success':refreshUploadedImages
};
//The ajax request.
vary = $('.delete-img-btn').attr('id');
$.post("/admin/image-uploader/delete/"+vary , data);
});
});
}
My problem is, in this line
div.append('<li><input type="button" class="delete-img-btn" id = <<ui.id>> img-id=<<<image.id>>> value="Delete"/></li>');
I want to assign id a variable ui.id i.e (id = <<ui.id>> ) which is defined somewhere outside the div.append. Can you help me on how to do it please.

Is this all you're trying to do?
div.append(
'<li><input type="button" class="delete-img-btn" id="'
+ ui.id + '" img-id="'
+ image.id + '" value="Delete"/></li>');
image.id isn't defined though.

Related

There was an unexpected failure with this assessment, invalid type provided

I'm attempting to run the following code which is pretty much copied from the OoTheBox UI Action called "View User's Response".
function showRiskAssessment(){
var ra = new GlideRecord('asmt_assessment_instance');
ra.addQuery('task_id', '=', current.sys_id);
ra.orderByDesc('taken_on');
ra.setLimit(1);
ra.query();
// var id = g_form.getUniqueValue();
var id = ra.sys_id;
//var type = g_form.getValue('metric_type');
var type = '468aeff2db9357008aeba9f7059619ca';
var url = 'assessment_take2.do?sysparm_assessable_sysid=' + id + '&sysparm_assessable_type=' + type + '&sysparm_reader_view=true';
var d = new GlideOverlay({
title: "User's Response",
iframe: url,
width:'80%',
height: '100%',
onAfterLoad: function() {
var iframe = d.getIFrameElement();
setTimeout(function(){
iframe.height = parseInt(iframe.height)+1;
},0);
}
});
d.render();
}
If I hardcode it like this it works. All I'm trying to do is on the change record I want to look up the most recent Assessment Instance for that particular change and display in the overlay. Obviously I can't hardcode the id however it seems the query isn't recognizing that info at all anyways.
function showRiskAssessment(){
// var ra = new GlideRecord('asmt_assessment_instance');
// ra.addQuery('task_id', '=', current.sys_id);
// ra.orderByDesc('taken_on');
// ra.setLimit(1);
// ra.query();
// var id = g_form.getUniqueValue();
var id = '5c516eeddb87d090ebce60ab1396198a';
//var type = g_form.getValue('metric_type');
var type = '468aeff2db9357008aeba9f7059619ca';
var url = 'assessment_take2.do?sysparm_assessable_sysid=' + id + '&sysparm_assessable_type=' + type + '&sysparm_reader_view=true';
var d = new GlideOverlay({
title: "User's Response",
iframe: url,
width:'80%',
height: '100%',
onAfterLoad: function() {
var iframe = d.getIFrameElement();
setTimeout(function(){
iframe.height = parseInt(iframe.height)+1;
},0);
}
});
d.render();
}
You're trying to use current.sys_id in a client side script. It is recommended to use g_form for client side scripts. You're also trying a GlideRecord on a client script, which is also not recommended.
To fix, replace:
ra.addQuery('task_id', '=', current.sys_id);
with:
var sysId = g_form.getUniqueValue();
ra.addQuery('task_id', '=', sysId);
Also, for the difference between g_form and current have a look here.

jquery plugin pass variable inside config settings

I would like to pass an array in my plugin defaults config settings. I am trying to give the user, the option to add as many title and src variable as they like for instance:
desktop_xl: {
"title":"beach",
"src":"http://images.smh.com.au/2013/02/25/4061249/art-Whitehaven-Beach-620x349.jpg"
},
{
"title":"sunset",
"src":"https://lh5.googleusercontent.com/-Oh0HlfM31BQ/TlXHejUNpeI/AAAAAAAABiI/tQbJJEGEOnU/s400/red_sunset_beach.jpg"
}
I have seen this question on stack overflow but could not find an answer that works for me.
I did some reading and figured out that I can create an array of objects, it works well only on my index.html page as per the below fiddle, http://jsfiddle.net/michelm/7gS6g/2/
The issue is that I would like to use this array as a config option in my plugin so users can add as many title and src variables as they need, but the array does not work inside the plugin.
When I did console.log(desktop_xl); on my index.html page, it shows as an object.
I read the documentation at http://api.jquery.com/jquery.extend/ and from what I understand I need to merge my objects to pass them as a config option, here is the link to my plugin from my drop box account (js fiddle did not take the https link for some reasons), please see below link to jquery.myplugin.js (random name for now, but will use unique naming convention once I work out the logic):
https://www.dropbox.com/s/boadofib6nggfzp/jquery.myplugin.js
Can anyone help me figure out how to pass this variable in my config option so users can add as many "title" and "src" from the option desktop_xl please?
UPDATE:
I have figured out how to pull array information and append it to my images, however, I still have no idea on how to "link" this to the plugin option settings as I need to give the user the option to add as many images with title as they would like in the option settings.
Here is how I have figured out how to pull data from array:
//create img desktop_xl loop
$.each(desktop_xl, function( index , value ){
$('#container').append(
$("<img />").attr({
id: value.title,
src: value.src,
title: value.title
})
);
});
UPDATE 2:
I have done some more work on the plugin, here is the code so far:
;(function($, window, document, undefined){
//define MyjQueryPlugin object with default config settings:
$.MyjQueryPlugin = {
defaults: {
imagecontainer: "#container",
version: "v01"
// add my Arrays to default options here?
// arrays should allow users to add as many images to #container div as they require
// arrays are desktop_xl[] , desktop_l[] , ipad_p[] , mobile_l[], mobile_p[]
}
};
//extend jquery with the plugin
$.fn.extend({
MyjQueryPlugin:function(config) {
//use defaults or properties supplied by user
var config = $.extend({}, $.MyjQueryPlugin.defaults, config );
//append slides
$(config.imagecontainer).append('<div class="imagecontainerfordesktop_xlarray" </div>').css('height', $(window).height() );
// append MyjQueryPlugin sidebar
this.append( '<div id="Mysidebar" class="open">' +
'<p class="review">Version ' + config.version + '- ready for review</p>'+
'<hr>' +
'</div>')
.children()
.css('height', $(window).height() );
//create array of objects
var desktop_xl = [
{
"title":"Homepage", // text for sidebar
"src":"slides/1200/Homepage.jpg"// path to image >= 1200px wide
},
{
"title":"Categories", // text for sidebar
"src":"slides/1200/Categories.jpg"// path to image >= 1200px wide
},
{
"title":"Product description", // text for sidebar
"src":"slides/1200/Product_description.jpg" // path to image >= 1200px wide
}
];
var desktop_l = [
// if array is empty, remove elements from the page
];
var ipad_p = [
{
"title":"Homepage", // text for sidebar
"src":"slides/480/Homepage.jpg" // path to image >= 480px wide
}
];
var mobile_l = [];
var mobile_p = [];
// set Global Variables
var width = $(window).width();
var currHeight = $(window).height();
var ctrl = $(".ctrl");
var ulscreenlia = $('ul.screen li a');
var sidebarlia = $('#MyjQueryPluginsidebar li a');
var sidebar = $("#MyjQueryPluginsidebar");
var ulscreenli = $('ul.screen li');
if (desktop_xl.length === 0) {
ulscreenli.eq(0).hide();
$('div.select_join option[value="xld"]').remove();
}
if (desktop_l.length === 0) {
ulscreenli.eq(1).hide();
$('div.select_join option[value="ld"]').remove();
}
if (ipad_p.length === 0) {
ulscreenli.eq(2).hide();
$('div.select_join option[value="ip"]').remove();
}
if (mobile_l.length === 0) {
ulscreenli.eq(3).hide();
$('div.select_join option[value="ml"]').remove();
}
if (mobile_p.length === 0) {
ulscreenli.eq(4).hide();
$('div.select_join option[value="mp"]').remove();
}
//create img desktop_xl loop
$.each(desktop_xl, function( index , value ){
$('#container .slides-xld').append(
//getting values from array but cannot understand how to pass array(s): desktop_xl, desktop_l, ipad_p, mobile_l, mobile_p inside config option
//And Each arrays should allow user to add multiple images to #container dive
$("<img />").attr({
id: value.title,
src: value.src,
title: value.title
})
);
});
//create img ipadp loop
$.each(ipad_p, function( index , value){
$('#container .slides-ipadp').append(
$("<img />").attr({
id: value.title,
src: value.src,
title: value.title
})
);
});
function rundateobject(){
var current_date = new Date ( );
var month_names = new Array ( );
month_names[month_names.length] = "January";
month_names[month_names.length] = "February";
month_names[month_names.length] = "March";
month_names[month_names.length] = "April";
month_names[month_names.length] = "May";
month_names[month_names.length] = "June";
month_names[month_names.length] = "July";
month_names[month_names.length] = "August";
month_names[month_names.length] = "September";
month_names[month_names.length] = "October";
month_names[month_names.length] = "November";
month_names[month_names.length] = "December";
var day_names = new Array ( );
day_names[day_names.length] = "Sunday";
day_names[day_names.length] = "Monday";
day_names[day_names.length] = "Tuesday";
day_names[day_names.length] = "Wednesday";
day_names[day_names.length] = "Thursday";
day_names[day_names.length] = "Friday";
day_names[day_names.length] = "Saturday";
$('#date').html( day_names[current_date.getDay()]
+ ', '
+ month_names[current_date.getMonth()]
+ ' '
+ current_date.getDate()
+ ' '
+ current_date.getFullYear() );
};
//create animation for anchor links with jQuery DOM ready function
$(function(){
$('a').hover(function(){
$(this).animate({
'margin-left':10,
'padding-left':20
},200);
$(this).dequeue();
},
function() {
$(this).animate({
'margin-left':0,
'padding-left':15
},200);
$(this).dequeue();
}
);
});
//on resize browser, adjust elements height
//initialise plugins
$(".nano").nanoScroller();
//initialise functions
rundateobject();
//return the jquery object for chaining
return this;
}// config options
}); // jQuery extend
})(jQuery, window, document);
The answer was given to me on jquery.com by user kbwood.au
defaults: {
imagecontainer: "#container",
version: "v01",
desktop_xl: [] //Array
}
Then in the .each function we need to pass the array as a config.desktop_xl:
//create img desktop_xl loop
$.each(config.desktop_xl, function( index , value ){
$('#container').append(
$("<img />").attr({
id: value.title,
src: value.src,
title: value.title
})
);
});

titanium mobile:get row value from tableview on button click issue

Hello friends,
I am developing an app using Google Place API in Titanium Development and successfully got data and display in tableview and add button in each row but my issue is that I want to get name and address on button click in each row so please give me idea or any link to solve my issue.
Please take a look in my screenshot so on btnclick I want to get name and address.
Thanks in advance.
var categoryName;
var addressLabel;
var row;
var tableData=[];
PlacesListCells = function createRow()
{
//var tableData=[];
var loader = Titanium.Network.createHTTPClient();
var url = "https://maps.googleapis.com/maps/api/place/search/json?";
url = url + "location=" + lat + ',' + lon;
url = url + "&radius=" + radius;
url = url + "&name=" + name;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader.open("GET",url);
// Create our HTTP Client and name it "loader"
// Runs the function when the data is ready for us to process
loader.onload = function()
{
var obj = JSON.parse(this.responseText);
Ti.API.log(obj);
var results = obj.results;
Ti.API.log(results);
for (var i = 0; i < results.length; i++)
{
categoryName = obj.results[i].name;
reference = obj.results[i].reference;
Ti.API.log('Refernce:'+reference);
// Create a row and set its height to auto
row = Titanium.UI.createTableViewRow({height:'78'});
var placeImage = Titanium.UI.createImageView
({
image:'../iphone/appicon.png',
width:70,
height:50,
top:12,
left:5
});
// Create the label to hold the tweet message
var nameLabel = Titanium.UI.createLabel({
//text:name,
left:80,
top:5,
height:'auto',
width:185,
textAlign:'left',
font:{fontSize:12}
});
// Create the label to hold the tweet message
addressLabel = Titanium.UI.createLabel({
left:80,
top:25,
height:'auto',
width:185,
textAlign:'left',
font:{fontSize:14}
});
var arrowImage = Ti.UI.createImageView
({
image:'../iphone/appicon.png',
width:20,
height:20,
left:280,
top:30
});
var favoriteButton = Ti.UI.createButton
({
title:'btn',
//font:{fontFamily:'Helvetica Neue',fontSize:15},
top:20,
left:255,
height:30,
width:50,
url:'../Images/favorite.png'
//image:'../Images/favorite.png'
});
nameLabel.text = categoryName;
getDetailsData(addressLabel,row,i);
row.add(placeImage);
row.add(nameLabel);
row.add(addressLabel);
row.add(favoriteButton);
//row.add(arrowImage);
tableData[i] = row;
//set page title for each row
row.pageTitle = nameLabel.text;
favoriteButton.row = i;
favoriteButton.addEventListener('click', function(e)
{
Ti.API.log('favoriteButton clicked on row ' + e.source.row +' at ' + new Date().getSeconds());
alert('favoriteButton clicked on row ' + e.source.row);
var index = e.source.row;
var name = tableData[index];
alert('name'+name);
});
}
tableView.setData(tableData);
};
//-- Network error
loader.onerror = function(e)
{
Ti.API.info('Network error: ' + JSON.stringify(e));
};
// Send the HTTP request
loader.send();
return tableData;
};
Once you have your index, you should be able to reference your original data source by that.
var favoriteButton = Ti.UI.createButton({
title:'btn',
//font:{fontFamily:'Helvetica Neue',fontSize:15},
top:20,
left:255,
height:30,
width:50,
url:'../Images/favorite.png'
//image:'../Images/favorite.png',
name:categoryName,
address:address;//address mention here
});
row.add(favoriteButton);
favoriteButton.addEventListener('click', function(e)
{
var index = e.source.row;
var name = e.source.name;
var address = e.source.address;
alert('name'+name);
});
}
I think this might help you a lot.

titanium mobile:onload function called issue in json parsing

Hello friends,
I am developing an app in Titanium Studio sdk 1.8.1 using Google Place API to display category atm list & address in tableview so I use json parsing using this link but loader.onload function of getData method is not called immediately after send function of getData method in json parsing so its called after getDetailsData() function and also can't display address in tableview so please give me idea how to solve it.
Thanks in advance.
var lat ,lon ,radius , name , sensor , key , reference, address;
lat = '-33.8670522';//'23.042067';
lon = '151.1957362';//'72.530835';//
radius = '500';
name = title;
sensor = 'false';
key = 'AIzaSyDALrXHC4uMtfSrpCg6NHxqPhsLccLYPZE';
var rowData = [];
// getCategoryData using Google Place API
function getData()
{
var loader = Titanium.Network.createHTTPClient();
var url = "https://maps.googleapis.com/maps/api/place/search/json?";
url = url + "location=" + lat + ',' + lon;
url = url + "&radius=" + radius;
url = url + "&name=" + name;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader.open("GET",url);
// Create our HTTP Client and name it "loader"
// Runs the function when the data is ready for us to process
loader.onload = function()
{
var obj = JSON.parse(this.responseText);
Ti.API.log(obj);
var results = obj.results;
Ti.API.log(results);
for (var i = 0; i < results.length; i++)
{
var name = obj.results[i].name;
reference = obj.results[i].reference;
Ti.API.log('Refernce:'+reference);
getDetailsData();
// Create a row and set its height to auto
var row = Titanium.UI.createTableViewRow({height:'auto'});
// Create the view that will contain the text and avatar
var post_view = Titanium.UI.createView({
height:'auto',
layout:'vertical',
top:5,
right:5,
bottom:5,
left:5
});
// Create the label to hold the tweet message
var nameLabel = Titanium.UI.createLabel({
//text:name,
left:30,
top:0,
bottom:2,
height:'auto',
width:236,
textAlign:'left',
font:{fontSize:14}
});
// Create the label to hold the tweet message
var addressLabel = Titanium.UI.createLabel({
text:'Address',
left:30,
top:0,
bottom:2,
height:'auto',
width:236,
textAlign:'left',
font:{fontSize:14}
});
nameLabel.text = name;
//addressLabel.text = placeAddress;
post_view.add(nameLabel);
post_view.add(addressLabel);
// Add the post view to the row
row.add(post_view);
// Give each row a class name
//row.className = "item"+i;
// Add row to the rowData array
rowData[i] = row;
//rowData.push(row);
}
//tableView.setData(rowData);
// Create the table view and set its data source to "rowData" array
var tableView = Titanium.UI.createTableView({data:rowData});
//Add the table view to the window
showWin.add(tableView);
};
//-- Network error
loader.onerror = function(e)
{
Ti.API.info('Network error: ' + JSON.stringify(e));
};
// Send the HTTP request
loader.send();
}
function getDetailsData ()
{
var loader1 = Titanium.Network.createHTTPClient();
Ti.API.log('getDetailsData');
var url = "https://maps.googleapis.com/maps/api/place/details/json?";
url = url + "reference=" + reference;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader1.open("GET",url);
// Runs the function when the data is ready for us to process
loader1.onload = function()
{
var detailsObj = JSON.parse(this.responseText);
Ti.API.log(detailsObj);
address = detailsObj.result.formatted_address;
Ti.API.log('Address:'+address);
phoneno = detailsObj.result.formatted_phone_number;
Ti.API.log('Phone No:'+phoneno);
};
//-- Network error
loader1.onerror = function(event)
{
Ti.API.info('Network error: ' + JSON.stringify(event));
};
// Send the HTTP request
loader1.send();
return address;
}
getData();
Dont't use the return in the second http request.
Pass the label object in the function like:
getDetailsData(addressLabel);
and set the text inside loader1.onload like this:
address = detailsObj.result.formatted_address;
addressLabel.text = address;

Inline editing with AJAX - how do I create multiple editable areas on the same page?

I found a tutorial on how to create editable regions on a page using AJAX.
This is great, except it was written for a single element with a unique ID. I'd like to be able to click on multiple elements on the same page and have them also be editable (e.g., I'd like to alter the script below so it works not with a single element, but with multiple elements of a particular class).
Here is my HTML:
<h2>Edit This</h2>
<p class="edit">This is some editable content</p>
<p class="edit">This is some more editable content</p>
<p class="edit">I could do this all day</p>
Here is the JS file I'm working with (I updated the script per Rex's answer below): This script is, unfortunately, not working - can anyone point me in the right direction?
Event.observe(window, 'load', init, false);
function init() {
makeEditable('edit');
}
function makeEditable(className) {
var editElements = document.getElementsByClassName(className);
for(var i=0;i<editElements.length;i++) {
Event.observe(editElements[i], 'click', function(){edit($(className))}, false);
Event.observe(editElements[i], 'mouseover', function(){showAsEditable($(className))}, false);
Event.observe(editElements[i], 'mouseout', function(){showAsEditable($(className), true)}, false);
}
}
function showAsEditable(obj, clear) {
if (!clear) {
Element.addClassName(obj, 'editable');
} else {
Element.removeClassName(obj, 'editable');
}
}
function edit(obj) {
Element.hide(obj);
var textarea ='<div id="' + obj.id + '_editor"><textarea cols="60" rows="4" name="' + obj.id + '" id="' + obj.id + '_edit">' + obj.innerHTML + '</textarea>';
var button = '<input type="button" value="SAVE" id="' + obj.id + '_save"/> OR <input type="button" value="CANCEL" id="' + obj.id + '_cancel"/></div>';
new Insertion.After(obj, textarea+button);
Event.observe(obj.id+'_save', 'click', function(){saveChanges(obj)}, false);
Event.observe(obj.id+'_cancel', 'click', function(){cleanUp(obj)}, false);
}
function cleanUp(obj, keepEditable) {
Element.remove(obj.id+'_editor');
Element.show(obj);
if (!keepEditable) showAsEditable(obj, true);
}
function saveChanges(obj) {
var new_content = escape($F(obj.id+'_edit'));
obj.preUpdate = obj.innerHTML // stow contents prior to saving in case of an error
obj.innerHTML = "Saving…";
cleanUp(obj, true);
var success = function(t){editComplete(t, obj);}
var failure = function(t){editFailed(t, obj);}
var url = 'http://portal.3roadsmedia.com/scripts/edit.php';
var pars = 'id=' + obj.id + '&content=' + new_content + '&pre=' + obj.preUpdate;
var myAjax = new Ajax.Request(url, {method:'post',
postBody:pars, onSuccess:success, onFailure:failure});
}
function editComplete(t, obj) {
obj.innerHTML = t.responseText;
showAsEditable(obj, true);
}
function editFailed(t, obj) {
obj.innerHTML = 'Sorry, the update failed.';
cleanUp(obj);
}
The Event.observe method currently attaches to a single element with the ID specified. You should change this to iterate over a collection of elements located by classname and attach to each of them. According to the Prototype documentation, you can provide an element object as the first parameter, instead of an ID.
Currently, id is a string:
function makeEditable(id) {
Event.observe(id, 'click', function(){edit($(id))}, false);
//...
Which means Event.observe is attaching to the click event of the element with the ID provided. You want to attach to all elements with a class. Try:
function makeEditable(className) {
var editElements = document.getElementsByClassName(className);
for(var i=0;i<editElements.length;i++) {
Event.observe(editElements[i], 'click', function()
//...
}
//...

Resources