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 () {
}
});
}
Related
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 !
I have this jqgrid code below and I have a picture inside it and at the same time its function that I am using. But clicking the button inside my jqgrid it says Uncaught ReferenceError: clickmeapproved is not defined. Is there anything wrong with my code or the way that I am using them?. Same error with the disapproved button.
afterInsertRow: function (rowid) {
var obj = jQuery("#FiTATimeCorrectionV2List").getRowData(rowid);
var FADTLSID = obj.FitaAssignDtlID;
if (FADTLSID !== undefined) {
if (FADTLSID !== "") {
var btnApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/check.png' style='height:20px;width:20px;' style ='width: 90px' id='btnApproved" + rowid + "' onclick='clickmeapproved(" + rowid + " )' />"
var btnDisApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/delete.png' style='height:20px;width:20px;' style ='width: 90px' id='btnDisApproved" + rowid + "' onclick='clickmedisapproved(" + rowid + " )' />"
jQuery("#FiTATimeCorrectionV2List").setRowData(rowid, { FitaCorForApproval: btnApprove });
jQuery("#FiTATimeCorrectionV2List").setRowData(rowid, { FitaCorForDisApproval: btnDisApprove });
var temp = obj.FitaStatus;
if (temp == "Approved") {
$("#btnApproved" + rowid).hide();
$("#btnDisApproved" + rowid).hide();
}
else if (temp == "Disapproved") {
$("#btnApproved" + rowid).hide();
$("#btnDisApproved" + rowid).hide();
} else {
$("#btnApproved" + rowid).show();
$("#btnDisApproved" + rowid).show();
}
}
}
},
function clickmeapproved(rowid) {
var ans = confirm("Are you sure you want to approve the request of "+ globalFitaCorName +"?");
if (ans) {
$.ajax({
type: "POST",
url: '../Request/SaveFitaApproval?FAID=' + rowid,
dataType: 'json',
success: function (response) {
alert("Successfully approve!");
$("#FiTATimeCorrectionV2List").trigger("reloadGrid");
FiTATimeCorrectionV2(0);
globalFitaCorName = "";
$("#loader").hide();
},
error: function (reponse) {
$("#FiTATimeCorrectionV2List").trigger("reloadGrid");
FiTATimeCorrectionV2(0);
globalFitaCorName = "";
$("#loader").hide();
}
});
}
}
Your "clickmeapproved" function does not have global scope. Check by typing "window.clickmeapproved" in the web inspector.
Here is the code that I use to solve my issue.
var btnApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/check.png' style='height:20px;width:20px;' style ='width: 90px' id='btnApproved" + rowid + "' />"
var btnDisApprove = "<input type = 'image' img alt='' src='../../Content/Images/newimages/delete.png' style='height:20px;width:20px;' style ='width: 90px' id='btnDisApproved" + rowid + "' />"
I exclude the button click from it.
$("#btnApproved" + rowid + "").click(function(){
clickmeapproved(rowid);
});
$("#btnDisApproved" + rowid + "").click(function(){
clickmedisapproved(rowid);
});
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.
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");
});
}
}
I am not very experienced with JavaScript. Please see the code below:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
}
}
}
}
window.onload = GetSQLTable
</script>
The code incrementally builds a webpage i.e. x number of HTML tables are obtained and displayed to the webpage as and when they become ready. This works.
The problem is I don't know how to remove the LoadingImage once the webpage is complete i.e. $("#LoadingImage").hide();. OnSuccess is called x number of times depending on how many tables are returned so I cannot put it in there.
One way would be to count the number of successful onSuccess() calls, and hide your loading image when they are all complete:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.1.min.js"></script>
<script type = "text/javascript">
function GetSQLTable() {
//alert($("#<%=fieldGroupReferences.ClientID%>")[0].value)
var str = $("#<%=fieldGroupReferences.ClientID%>")[0].value
var res = str.split(",");
var numSucceeded = 0;
for (var i = 0; i < res.length; i++) {
$("#LoadingImage").show();
var div = document.createElement('div');
div.id = "div" + i
document.body.appendChild(div);
//alert(res[i]);
$.ajax({
type: "POST",
url: "Default3.aspx/GetSQLTable",
data: '{username: "' + $("#<%=fieldUserName.ClientID%>")[0].value + '", terminalname: "' + $("#<%=fieldTerminalName.ClientID%>")[0].value + '", terminalip: "' + $("#<%=fieldTerminalIP.ClientID%>")[0].value + '", mappingid: "' + res[i] + '", usergroup: "' + $("#<%=fieldUserGroup.ClientID%>")[0].value + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess(i,res.length),
failure: function (response) {
//alert(response.d);
alert('there was an error loading the webpage')
}
});
}
function OnSuccess(i,totalrows) {
return function (response) {
if (response.d != "") {
document.getElementById('div' + i).innerHTML = document.getElementById('div' + i).innerHTML + '<br>' + '<br>' + response.d;
numSucceeded++;
if (numSucceeded === totalrows) {
$("#LoadingImage").hide();
}
}
}
}
}
window.onload = GetSQLTable
</script>
Try using .when with an array of your ajax calls. Something like this (simplified to remove the irrelevant bits):
function GetSQLTable() {
//...
var calls = [];
for (var i = 0; i < res.length; i++) {
//..
calls.push($.ajax({
type: "POST",
//..
}));
}
$.when(calls).then(function(d) {
// all done!!!
});