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 !
Related
I have multiple classes with the same tag (.offer) I am going through a loop and it adds the image to all my .offer divs. I just want to add the image specific to the user who posted. How can I do this? Assume the backend is working completely fine
jQuery (1st function)
function getOffers(key) {
dict = {
'key': key// pk value of post sent to retrieve offers to it
};
generateCSRFToken();
$.ajax({
url: "/retrieve_offers/",
method: "POST",
data: JSON.stringify(dict),
success: function (data) {
data = JSON.parse(data);
console.log(appendUserImage(38));
$("#offercontainer").empty();
$(".offer").empty();
for (var i = 0; i < data.length; i++) {
var string = data[i].fields.author_name;
$("#offercontainer").append(
"<div class='offer'>" +
"<p class=offername>" + string + "</p>" +
"<p class=offertext> offered his " + " " + data[i].fields.item_name + "</p>" +
"</div>"
);
appendUserImage(data[i].fields.author);
}
},
error: function () {
}
})
}
jQuery (2nd function)
function appendUserImage(key) {
dict = {
'key': key// pk value of post sent to retrieve offers to it
};
generateCSRFToken();
$.ajax({
url: "/get_user/",
method: "POST",
data: JSON.stringify(dict),
success: function (data) {
$('<img />', {
src: data["image"],
class: "offer_user_image"
}).appendTo($('.offer'))
},
error: function () {
}
});
}
I just want to append the image to its respective offer div pls help
you can pass to appendUserImage the div getOffers function creates or do something like this, add an unique key selector to the created .offer container and targeting it in the appendUserImage function.
in function getOffers(key) {
$("#offercontainer").append(
"<div class='offer' data-author-key='" + data[i].fields.author +"'>" +
"<p class=offername>" + string + "</p>" +
"<p class=offertext> offered his " + " " + data[i].fields.item_name + "</p>" +
"</div>");
appendUserImage(data[i].fields.author);
in function appendUserImage(key) {
$('<img />', {
src: data["image"],
class: "offer_user_image"
}).appendTo($('.offer[data-author-key="' + key + '"]'))
thanks for the people who tried answering I managed to fix my problem by using nth child and doing this:
for (var i = 0; i < data.length; i++) {
var string = data[i].fields.author_name;
$("#offercontainer").append(
"<div class='offer'>" +
"<p class=offername>" + string + "</p>" +
"<p class=offertext> offered his " + " " + data[i].fields.item_name + "</p>" +
"</div>"
);
appendUserImage(i,data[i].fields.author);
}
2nd function:
function appendUserImage(i,key) {
dict = {
'key': key// pk value of post sent to retrieve offers to it
};
generateCSRFToken();
$.ajax({
url: "/get_user/",
method: "POST",
data: JSON.stringify(dict),
success: function (data) {
$('<img />', {
src: data["image"],
class: "offer_user_image"
}).appendTo($('.offer:nth-child(' + (i+1) + ')'))
},
error: function () {
}
});
}
this is my code to change the drop down list values when the checkbox is checked. I use asp.net mvc framework and java script to call the action. The list of the drop-down should show only the expired medicines when the checkbox is checked. But, it results in (Error: [object:object]). It didn't hit the controller action 'getmedicine'. Can anyone help me?
function GetMedicineList(_isExp) {
var url = "getmedicine";
$.ajax({
url: url,
data: { IsExp: _isExp },
cache: false,
type: "GET",
dataType: "json",
success: function (data) {
var markup = "<option value='0'>Please Select Expired Medicine</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#clientId").html(markup).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
}
and in the view,
#Html.CheckBoxFor(m => m.IsExp, new { Id = "isExp", #onchange = "GetMedicineList(this.value);" })
I solved the problem. One error is the action that I use to trigger is not an action result. It is a list. I changed it. I also I have did some changes in js. It works properly now.
var GetMedicine= function () {
var url = UrlMedicine.GetMedicineChecked;
var isExp = $('#isExp').val();
var url = url + '?isExp=' + isExp;
$.get(url, null, function (data) {
{
var markup = "<option value='0'>Please Select Expird medicine</option>";
for (var x = 0; x < data.length; x++) {
markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
}
$("#medicineId").html(markup).show();
}
});
}
var GetMedicineList = function () {
if ($('#isExp').is(":checked")) {
userMedicineHistory.GetMedicine();
}
}
return {
GetMedicineList: GetMedicineList,
GetMedicine: GetMedicine
};
$(document).ready(function () {
$("#isExp").change(userMedicineHistory.GetMedicineList)
});
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?
I'm using an ajax request to post a new message to a database. The page auto loads elements from the database onload. I want to delete the elements and re-add them when a user makes a post to add the current most post to the top of the list and its not working. I'm not sure why. There is no console error but it doesn't remove them.
onload ajax call
$.ajax({
url : "/getposts/",
type : "POST",
dataType: "json",
data : {
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success : function(json) {
document.getElementById('output').innerHTML = (json['message']);
for (var index = 0; index < json['user_posts'].length; index++) {
var div_make_badassness = document.createElement('div');
div_make_badassness.id = json['user_posts'][index][3];
document.getElementById('post_section').appendChild(div_make_badassness);
document.getElementById(json['user_posts'][index][3]).innerHTML = "<div id=" + json['user_posts'][index][3] + ">" + "Title:" + json['user_posts'][index][1] + "<br>" + json['user_posts'][index][0] + " Chomps: " + json['user_posts'][index][2] + "</div>" ;
}
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
document.getElementById('output').innerHTML = "Request Failed.";
}
});
on submit ajax call
$.ajax({
url : "/makepost/",
type : "POST",
dataType: "json",
data : {
csrfmiddlewaretoken: '{{ csrf_token }}',
username: username,
post_title: post_title,
post_text: post_text,
},
success : function(json) {
document.getElementById('output').innerHTML = (json['message']);
var post_section = document.getElementById("post_section");
for (var index = 0; index < post_section.length; index++) {
post_section.removeChild(post_section.childNodes[index]);
}
div tag
<div id ='post_section'>
</div>
for (var index = 0; index < json['user_posts'].length; index++) {
console.log(json['user_posts'][index][3] + json['user_posts'][index][1] + json['user_posts'][index][2]);
var div_make_badassness = document.createElement('div');
div_make_badassness.id = json['user_posts'][index][3];
document.getElementById('post_section').appendChild(div_make_badassness);
document.getElementById(json['user_posts'][index][3]).innerHTML = "<div id=" + json['user_posts'][index][3] + ">" + "Title:" + json['user_posts'][index][1] + "<br>" + json['user_posts'][index][0] + " Chomps: " + json['user_posts'][index][2] + "</div>" ;
}
Because you're using jQuery, I'll just do it in jQuery.
// Will remove any html in "post_section" and add in the new posts
function updatePostSection(user_posts) {
var post_section = $('#post_section');
post_section.html(''); // Remove all html contents inside
for(var i = 0; i < user_posts.length; i++) {
var div = $('<div>');
div.attr('id', user_posts[i][3]);
div.html("Title:" + user_posts[i][1]);
post_section.append(div);
}
}
In the success ajax function you can do something like...
// ...
success : function(json) {
updatePostSection(json['user_posts']);
},
// ...
Then you should be able to use it for both your getposts and makepost ajax calls assuming the json is the same structure.
Update: There are ways to optimize this so you're only writing to the dom once, but this is just an example.
OK I am building something that makes an ajax request to one server where it determines the url it needs to then make a new ajax request to another place. Everything is progressing thanks to all the help at SO =) .. however I am stuck again. I am struggling with getting the variables to return to the different functions as I need. The second (jsonp) request returns a json function which looks like :
jsonResponse(
{"it.exists":"1"},"");
and my code...
var img = "null";
var z = "null";
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
$(data).find("ITEM").each(function()
{
query = $("SKU", this).text();
query = 'http://domain.com/' + query + '?req=exists,json';
img = $("SKU", this).text();
img = '<img src="http://domain.com/' + img + '">';
var date =$("LAST_SCAN" , this).text();
$.ajax({
url: query,
dataType: 'jsonp'
});
$("table").append('<tr>'+'<td>' + (date) + '</td>' + '<td>' + (z) + '</td>');
});
}
});
});
// function required to interpret jsonp
function jsonResponse(response){
var x = response["it.exists"];
// console.log(x);
if (x == 0) {
console.log("NO");
var z = "NO IMG";
}
if (x == 1) {
console.log(img);
//this only returns the first image path from the loop of the parseXml function over and over
var z = (img);
}
return z;
}
So I guess my problem is a two parter.. one how do I get the img variable to loop into that if statement and then once that works how can I return that z variable to be used in the first xml parser?
Try this synchronous approach:
var itemQueue = [];
$(document).ready(function ()
{
$.ajax({
type: "GET",
url: "connect.php",
dataType: "xml",
success: function parseXml(data)
{
itemQueue= $(data).find("ITEM").map(function ()
{
return {
sku: $("SKU", this).text(),
date: $("LAST_SCAN", this).text()
};
}).get();
getNextItem();
}
});
});
function getNextItem()
{
var item = itemQueue[0];
var query = "http://domain.com/" + item.sku + "?req=exists,json";
$.ajax({
url: query,
dataType: 'jsonp'
});
}
function jsonResponse(response)
{
var item = itemQueue.shift();
if (itemQueue.length)
{
getNextItem();
}
var x = response["it.exists"];
var z = x == "0" ? "NO IMG" : "<img src=\"http://domain.com/" + item.sku + "\">";
$("table").append("<tr><td>" + item.date + "</td><td>" + z + "</td>");
}
Store 'date' in a global variable, and move the logic to append HTML elements into the jsonResponse function. You cannot return control flow from jsonResponse because it's called asynchronously, but you can continue doing anything you'd like from that function.