External resources not reaching inside of function scope - javascript

I'm trying to make an inventory picker for my trading website, but I'm having some trouble calling external resources.
When originally calling the external function, all goes correctly, but whenever I try to call the external function INSIDE of a function in the html, it errors, saying
Uncaught TypeError: $(...).imagepicker is not a function
This is my relevant code.
<script src="~/Scripts/image-picker.js"></script>
<script>
var name = "HomeguardDev";
var inventory = [];
var selectedItems = [];
$.ajax({
async: false,
type: 'GET',
url: "/Home/getInventory/?username=" + name + "&page=1",
success: function (data) {
var parsed = JSON.parse(data);
for (var i = 0; i < parsed.length; i++) {
var text = parsed[i].Name;
inventory[i] = parsed[i];
if (parsed[i].SerialNumber !== "---") {
text = text + " [#" + parsed[i].SerialNumber + " / " + parsed[i].SerialNumberTotal + "]";
}
$("#sendingItems").append('<option data-img-label="<small>' + text + '</small>" data-img-src="' + parsed[i].ImageLink + '" value="' + i + '">' + text + '</option>');
}
}
});
$("#sendingItems").imagepicker({
show_label: true
});
function addItem() {
if (selectedItems.length < 4) {
var obj = (inventory[$("#sendingItems").val()]);
if (!containsObject(obj, selectedItems)) {
$('#sendingItems option[value="' + ($("#sendingItems").val()) + '"]').remove();
selectedItems.push(obj);
$("#sendingItems").imagepicker({
show_label: true
});
}
}
}
</script>
<p><a><input type="button" id="addItemButton" onclick="addItem()" value="Add item" /></a></p>
<p><a><input type="button" id="sendTradeButton" onclick="sendTrade()" value="Send Trade" /></a></p>
The error occurs inside of the function addItem() when calling imagepicker, but in the main block it calls and functions correctly. What am I doing incorrectly?

Related

display all json data with bootstrap card in a dynamic div using jquery

i'm still learning ajax,jquery and js here.. So in this problem i want to get the json data and display each of it into div id="card-body" dynamically one by one per ID, but it seems my code doesn't work because the result only show one div that have all the data inside of it. Are there any suggestion that can be added or changed within the code here?
<div class="container">
<div class="card">
<div class="card-header">
</div>
<div class="addDiv">
<div id="card-body">
</div>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function () {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function (result) {
$.each(result, function (index, item) {
var userId = item.userId;
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $("<p/>").html("user id: " + userId + "<br>"
+ "id: " + typeId + "<br>"
+ "title: " + titleId + "<br>"
+ "body: " + bodyId);
var html = '<div id="card-body>';
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
html += '</div>';
$(".addDiv").append(html);
$("div#card-body").append($info);
});
// console.log('success', result);
// console.log(result[0].body);
// console.log($(result).length);
}
});
});
</script>
for (let i = 0; i < $(result).length; i++) {
const element = $(result)[i];
}
what is here going to do?
or you mean this? --- Updated
$(function() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function(result) {
var container = $("div#list");
$.each(result, function (index, item) {
var userId = item.userId;
var id = "card-body-" + userId;
var el = $('div#' + id)
console.log(el)
var typeId = item.id;
var titleId = item.title;
var bodyId = item.body;
var $info = $('<div>').html(
"user id: " + userId + "<br>" +
"id: " + typeId + "<br>" +
"title: " + titleId + "<br>" +
"body: " + bodyId
);
if (!el.length) {
// not found, create new one
el = $('<div id="' + id + '">')
container.append(el)
}
el.append($info)
});
}
});
});

button function is not defined with htmlstring

I am able to display out all the details including the button. However, the main problem is that the when I click the button, nothing happens. It says that BtnRemoveAdmin() is not defined when I inspect for errors. However, I have function BtnRemoveAdmin()?? I have tried to move the function to htmlstring. Nothing works. I am not sure what went wrong.
(function () {
$(document).ready(function () {
showadmin();
});
function showadmin() {
var url = serverURL() + "/showadmin.php";
var userid = "userid";
var employeename = "employeename";
var role ="role";
var JSONObject = {
"userid": userid,
"employeename": employeename,
"role": role,
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getAdminResult(arr);
},
error: function () {
alert("fail");
}
});
}
function _getAdminResult(arr) {
for (var i = 0; i < arr.length; i++) {
htmlstring = '<div class="grid-container">' +
'<div>' + arr[i].userid + '</div>' +
'<div>' + arr[i].employeename + '</div>' +
'<div>' + arr[i].role + '</div>' +
'<div>' + '<button onclick="BtnRemoveAdmin()">Remove</button>' + // 'BtnRemoveAdmin' is not defined
'</div>' ;
$("#name").append(htmlstring);
}
function BtnRemoveAdmin() {
var data = event.data;
removeadmin(data.id);
}
}
function removeadmin(userid) {
window.location = "removeadmin.php?userid=" + userid;
}
})();
All your code is defined inside an IIFE.
That includes BtnRemoveAdmin.
When you generate your JavaScript as a string, it is evaled in a different scope.
BtnRemoveAdmin does not exist in that scope.
Don't generate your HTML by mashing strings together.
Use DOM instead.
function _getAdminResult(arr) {
var gridcontainers = [];
for (var i = 0; i < arr.length; i++) {
var gridcontainer = $("<div />").addClass("grid-container");
gridcontainer.append($("<div />").text(arr[i].userid));
gridcontainer.append($("<div />").text(arr[i].employeename));
gridcontainer.append($("<div />").text(arr[i].role));
gridcontainer.append($("<div />").append(
$("<button />")
.on("click", BtnRemoveAdmin)
.text("Remove")
));
gridcontainers.push(gridcontainer);
}
$("#name").append(gridcontainers);
}
I use JQuery, and sometimes I get the same problem with plain JS functions not being called.
So I create JQuery functions :
$.fn.extend({
btnRemoveAdmin: function() {
...//Do what you want here
}
});
To call it use :
<button onclick="$().btnRemoveAdmin();"></button>
Hope it helps you !

Appending content from RSS feeds to separate divs

I'm trying to display RSS using the following JS code. But when I execute this, both the RSS feeds are changed to same content (the one that is execute later) and all the feeds are appended to the same div. I think rss = this is causing the problem. Any workaround ?
HTML:
<div id="rss1" class="rss-widget">
<ul></ul>
</div>
<div id="rss2" class="rss-widget">
<ul></ul>
</div>
<div id="rss3" class="rss-widget">
<ul></ul>
</div>
JS:
function RSSWidget(id, url) {
rss = this;
rss.FEED_URL = url;
rss.JSON = new Array();
rss.widgetHolder = $('#' + id + ' ul ');
rss.storiesLimit = 15;
rss.renderBlogItem = function (object) {
var item = '<li class="blog-item">';
item += '<a href="' + object.link + '">';
item += '<div class="blog-item-title">' + object.title + '</div>';
item += '<div class="blog-item-author">' + object.author + '</div>';
// item += '<div class="blog-item-content">' + object.content + '</div>';
item += '</a>'
item += '</li>';
rss.widgetHolder.append(item);
}
return $.ajax({
url: 'http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&callback=?&q=' + encodeURIComponent(rss.FEED_URL),
dataType: 'json',
success: function (data) {
if (data.responseData.feed && data.responseData.feed.entries) {
$.each(data.responseData.feed.entries, function (i, e) {
rss.JSON.push({ //add objects to the array
title: e.title,
author: e.author,
content: e.content || "",
link: e.link
});
});
if (rss.storiesLimit > rss.JSON.length)
rss.storiesLimit = rss.JSON.length;
for (var i = 0; i < rss.storiesLimit; i++) {
rss.renderBlogItem(rss.JSON[i]);
}
$('#' + id + ' li ').each(function () {
var delay = ($(this).index() / rss.storiesLimit) + 's';
$(this).css({
webkitAnimationDelay: delay,
mozAnimationDelay: delay,
animationDelay: delay
});
});
}
}
});
}
$.when(RSSWidget('rss1', "http://rss.cnn.com/rss/money_markets.rss"))
.then(function () {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
.then(function () {
RSSWidget('rss3', "http://finance.yahoo.com/rss/topfinstories")
});
.then(RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews"));
is immediately invoked. Try calling second RSSWidget within .then() anonymous function
.then(function() {
RSSWidget('rss2', "http://feeds.reuters.com/reuters/financialsNews")
})
Also, no promise is returned from RSSWidget; you can include return $.ajax(/* settings */) from RSSWidget to return the jQuery promise object from RSSWidget.

Javascript error with sort

i have this code as shown below,
i got this from a developer who went afk because he has family troubles
basically this code below should grab the json results and form them into a table after sorting the price and then placing it in the table.
heres the code
//first define a function
var sortTable = function () {
$("#tableid tbody tr").detach().sort(function (a, b) {
//substring was added to omit currency sign, you can remove it if data-price attribute does not contain it.
return parseFloat($(a).data('price').substring(1)) - parseFloat($(b).data('price').substring(1));
})
.appendTo('#tableid tbody');
};
//include two files where rows are loaded
//1.js
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: 'api link here',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].price;
var button = "<button class='redirect-button' data-url='LINK'>Compare</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
//and here is the 2nd js file
$.ajax({
type: 'GET',
crossDomain: true,
dataType: 'json',
url: '2nd api',
success: function (json) {
//var json = $.parseJSON(data);
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
sortTable();
},
error: function (error) {
console.log(error);
}
});
Accessing the DOM, to get data that needs to be sorted, is a bad practice IMO. Even worse when you had the results in raw JSON form in the first place (in the success callback of the ajax call). Your success function should do something like this
success: function (json) {
//first sort the results - or better store these results somewhere
//and use that as a data store that is responsible for what is rendered in the DOM
json.results.sort(function(a,b) {
//using substring and parseFloat just like it was done in sortTable
//assuming price field has prices as strings with currency symbol in the first place
return parseFloat(a.substring(1)) - parseFloat(b.substring(1))
});
for (var i = 0; i < json.results.length; i++) {
var section = json.results[i].section;
var no = json.results[i].avalible;
var price = json.results[i].amount;
var button = "<button class='redirect-button' data-url='LINK'>Click Here</button>";
$("#tableid tbody").append("<tr data-price='" + price + "'><td>" + section + "</td><td>" + no + "</td><td>" + price + "</td><td>" + button + "</td></tr>");
$("#tableid").find(".redirect-button").click(function () {
location.href = $(this).attr("data-url");
});
}
}

Dynamic jquery AJAX upload form with text and file fields

I am trying to make a dynamic form wherein a single item has a file, text and select html input types and number of items can be dynamic. The problem is when doing AJAX using jquery, the Form wont serialize for the file input type. Please suggest any technique to do it. My code is below:
<form id="Form1" enctype="multipart/form-data">
<div id="divMain"></div>
<div>
<button id="Upload" type="button" value="Upload"><span>Upload</span></button>
<input id="Add" type="button" value="Add" />
</div>
</form>
<div id="status"></div>
<script type="text/javascript">
var counter = 0;
AddElements(); //add first element
$("#Add").click(function () {
AddElements();
});
function AddElements() {
counter++;
$("#divMain").append("<div><input id='Browse" + counter + "' name='Browse[]' type='file' value='Browse' data-target='#Name" + counter + "' />" +
"<input id='Name" + counter + "' name='Name[]' type='text'/>" +
"<select id='Type" + counter + "' name='Type[]'>" +
"<option>Option1</option>" +
"<option>Option2</option>" +
"</select></div>");
$("#Browse" + counter + "").change(function () {
var filename = $(this).val();
var textbox = $($(this).attr("data-target"));
var lastIndex = filename.lastIndexOf("\\");
var b = filename.lastIndexOf(".");
if ((b == -1) | (b < lastIndex))
filename = filename.substring(lastIndex + 1);
else
filename = filename.substring(lastIndex + 1, b - lastIndex - 1);
textbox.val(filename);
});
}
$("#Upload").click(function (e) {
e.preventDefault();
$("#status").html('Uploading....');
var ajaxData = $("#Form1").serialize();
$.ajax({
url: "AjaxPostDemo.aspx",
type: "POST",
data: ajaxData,
cache: false,
processData: false,
success: function (data) {
$("#status").html("success: " + data);
},
error: function (result) {
$("#status").html("error: " + result);
}
});
});
</script>
Change Your To script It Will Definately Work. :-)
<script type="text/javascript">
var counter = 0;
$(document).ready(function () {
AddElements(); //add first element
$("#Add").click(function () {
AddElements();
});
function AddElements() {
counter++;
$("#divMain").append("<div><input id='Browse" + counter + "' name='Browse[]' type='file' value='Browse' data-target='#Name" + counter + "' />" +
"<input id='Name" + counter + "' name='Name[]' type='text'/>" +
"<select id='Type" + counter + "' name='Type[]'>" +
"<option>Option1</option>" +
"<option>Option2</option>" +
"</select></div>");
$("#Browse" + counter + "").change(function () {
var filename = $(this).val();
var textbox = $($(this).attr("data-target"));
var lastIndex = filename.lastIndexOf("\\");
var b = filename.lastIndexOf(".");
if ((b == -1) | (b < lastIndex))
filename = filename.substring(lastIndex + 1);
else
filename = filename.substring(lastIndex + 1, b - lastIndex - 1);
textbox.val(filename);
});
}
});
$(document).ready(function () {
$("#Upload").click(function (e) {
e.preventDefault();
$("#status").html('Uploading....');
var ajaxData = $("#Form1").serialize();
$.ajax({
url: "AjaxPostDemo.aspx",
type: "POST",
data: ajaxData,
cache: false,
processData: false,
success: function (data) {
$("#status").html("success: " + data);
},
error: function (result) {
$("#status").html("error: " + result);
}
});
});
});
</script>
Second Option
http://www.uploadify.com/documentation/uploadify/multi/
Prefer This It will Uploaded Multifiles on one time with great UI. :-)

Categories

Resources