I have created a table using an array of JSON Objects that are returned by my servlet. I am trying to make it so that when I click on the image I add before each row it will call a function. The code below should work but it does not and I think I'm missing something simple.
$(document).ready(function(){
loadData();
$("#item").bind("click", function() { alert("test"); });
});
function loadData(){
$.ajax({
type: "POST",
url: "http://myservlet.com/orders",
data: { }
}).done(function( msg ) {
response = $.parseJSON(msg);
$.each(response, function(key,value) {
alert(value.order_id);
var item = 0;
$("#ordersTable tbody").append(
"<tr>"+
"<td><img src=http://examplewebsiteurl.com/plus.png id='item'></img></td>"+
"<td>"+value.order_id+"</td>"+
"<td>"+value.sku+"</td>"+
"<td>"+value.quantity_purchased+"</td>"+
"<td>"+value.product_name+"</td>"+
"<td>"+value.buyer_name+"</td>"+
"<td>"+value.buyer_phone_number+"</td>"+
"</tr>"
);
});
});
}
Try like
$(document).on('click', '#item', function() {
alert("test");
});
Loading data is asynchronous operation that's why you can't bind anything before DOM is populated. You can provide a callback function to be called once data has come and available. Or you can use the fact that $.ajax is Promise object. For example:
function loadData() {
return $.ajax({
type: "POST",
url: "http://myservlet.com/orders",
data: {}
}).done(function (msg) {
$.each(response, function (key, value) {
var item = 0;
$("#ordersTable tbody").append(
"<tr>" +
"<td><img src=http://examplewebsiteurl.com/plus.png class='item'/></td>" +
"<td>" + value.order_id + "</td>" +
"<td>" + value.sku + "</td>" +
"<td>" + value.quantity_purchased + "</td>" +
"<td>" + value.product_name + "</td>" +
"<td>" + value.buyer_name + "</td>" +
"<td>" + value.buyer_phone_number + "</td>" +
"</tr>");
});
});
}
loadData().done(function() {
$(".item").bind("click", function() { alert("test"); });
});
Related
I have JSON data saved in this api https://api.myjson.com/bins/xeza2. I want to print the data in a table by using only JavaScript or jQuery. I have tried a few things. I have used XMLHTTP request. Json.parse() . Every method on stack.
This was the first thing I have tried
$(function () {
var people = [];
$.getJSON('https://api.myjson.com/bins/xeza2', function (data) {
$.each(data.info, function (i, f) {
var tblRow = "<tr>" + "<td>" + f.id + "</td>" +
"<td>" + f.name + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
data.info is undefined hence why you weren't getting anything added to the table. You need to change it to data.ct_info.
The below code can access the JSON data in your request's response and appends it to the table. I am not sure how you want the data to look or what properties you are trying to access (hence the undefined's) that I'll leave up to you but the below should help get you started.
f.job and f.roll are non-existent properties.
$(function() {
var people = [];
$.getJSON('https://api.myjson.com/bins/xeza2', function(data) {
$.each(data.ct_info, function(i, f) {
var tblRow = "<tr>" + `<td id=${f.id}>` + "</td>" +
"<td>" + f.name + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
var users = []
//GET USER INFO
f.Qid_info.forEach((x) => {
x.user_info.forEach((y) => {
//avoid duplicates
var foundUser = users.find((user) => {
return user.id === y.id
})
if (!foundUser) {
users.push(y)
}
})
})
$.each(users, function(i, user) {
var userRow = "<tr>" + `<td id=${user.id}>` + "User's Name:" +
"</td>" +
"<td>" + user.name + "</td>" + "</tr>"
$(userRow).appendTo("#userdata tbody");
})
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='userdata'>
<tbody>
</tbody>
</table>
Based on the database value status will be Y or N. If it Y means it will active.png will be displayed. it is working fine. when i click active.png image then anchor tag onclick="GetRecords1(' + item.ModuleID + '); Function the ID value is not passed to the event.
How to pass the active.png image click the ID value.
<script>
$(document).ready(function () {
$("#DomainID").change(function () {
var id = $(this).val();
$("#example tbody tr").remove();
$.ajax({
type: 'POST',
url: '#Url.Action("ViewModules")',
dataType: 'json',
data: { id: id },
success: function (data) {
var items = '';
$.each(data.EmpList, function (i, item) {
$("#findValue").show();
/*Find Role here - Comparing Emp List ModuleId to RoleList ModuleId*/
var RoleName = $(data.role).filter(function (index, item) {
return item.ModuleID == item.ModuleID
});
if (item.ParentModuleID == -1) {
item.ModuleName = " -- " + item.ModuleName
} else {
item.ModuleName = item.ModuleName
}
var Status = '';
if (item.Status == "Y") {
Status = '<img src="/img/Active.png" height="22" width="42"/>'
} else {
Status = '<img src="/img/InActive.png" height="22" width="42"/>'
}
var rows = "<tr>"
+ "<td>" + (i + 1) + "</td>"
+ "<td>" + item.ModuleName + "</td>"
+ "<td>" + item.Url + "</td>"
+ "<td>" + RoleName[i].RoleName + "</td>"
+ "<td>" + ' ' + Status + "</td>"
+ "</tr>";
$('#example tbody').append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
alert("StackTrace: " + r.StackTrace);
alert("ExceptionType: " + r.ExceptionType);
}
});
return false;
});
});
</script>
Pass:
<script>
$(document).ready(function () {
$('#example tbody').on('click', function GetRecords1(ModuleID) {
var id = ModuleID;
alert("Status Clicked:" + ModuleID);
});
});
</script>
<a id="123" onclick="someFunction(this.id)"></a>
JavaScript code:
someFunction(id) {
console.log(id)
}
Why are you using in-line JavaScript? You could easily use event delegate on to bind click events.
Here is your modified code:
Status = '<img src="/img/Active.png" height="22" width="42"/>'
Added a class user-status to a tag and assigned id to data-id attribute.
Now get id from click event:
$(document).on('click','.user-status', function(){
var getId = $(this).data('id');
var getStatus = $(this).data('status');
alert("Status Clicked:" + getId );
});
Chrome dev tools is telling me there is an error on line 3 but I am unsure what it is. Admittedly I am new to coding with jQuery so it's possible that the tutorials that I followed had something wrong.
$.ajax({
url: 'https://www.carcraft.atsbusinessandgames.com/xmls/carcraft_1-7-10Test.xml',
type: "Get",
dataType: 'xml',
success: function (result) {
}
$(result).find('Module').each(function() {
//$("#ModsList").append($(this).text());
var authors = $(this).find('authors').text();
var version = $(this).find('version').text();
var date = $(this).find('date').text();
var episode = $(this).find('episode').text();
$("#ModsList").append("<tr>" + "<td>" + $authors + "</td>" + "<td>" + $version + "</td>" + "<td>" + $date + "</td>" + "<td>" + $episode + "</td>" + "</tr>");
});
error: function() {
alert("Notify the site owner that the xml file has a syntax error and is therefore unreadable.");
}
});
This is the table I'm trying to modify via above code:
<table id="ModsList">
<tr style="font-weight: bold;">
<td>Mod Name</td>
<td>Author(s)</td>
<td>Version</td>
<td>Date added/updated</td>
<td>Episode Added</td>
</tr>
</table>
Your success handler is not declared appropriately. You have to put the code in between the { } for the success function. As you have it now, you're inserting random code into an object definition, which is not legal.
Change the code to this:
$.ajax({
url: 'https://www.carcraft.atsbusinessandgames.com/xmls/carcraft_1-7-10Test.xml',
type: "Get",
dataType: 'xml',
success: function (result) {
$(result).find('Module').each(function() {
//$("#ModsList").append($(this).text());
var authors = $(this).find('authors').text();
var version = $(this).find('version').text();
var date = $(this).find('date').text();
var episode = $(this).find('episode').text();
$("#ModsList").append("<tr>" + "<td>" + authors + "</td>" + "<td>" + version + "</td>" + "<td>" + date + "</td>" + "<td>"+episode+"</td>" + "</tr>");
});
},
error: function() {
alert("Notify the site owner that the xml file has a syntax error and is therefore unreadable.");
}
});
Why success: function (result) {} is being empty? Hope the result should be accessible only at success function.
Try this
$.ajax({
url: 'https://www.carcraft.atsbusinessandgames.com/xmls/carcraft_1-7-10Test.xml',
type: "Get",
dataType: 'xml',
success: function (result) {
$(result).find('Module').each(function() {
//$("#ModsList").append($(this).text());
var authors = $(this).find('authors').text();
var version = $(this).find('version').text();
var date = $(this).find('date').text();
var episode = $(this).find('episode').text();
$("#ModsList").append("<tr>" + "<td>" +authors+ "</td>" + "<td>" +version+ "</td>" + "<td>" +date +"</td>" + "<td>" +episode+ "</td>" + "</tr>");
});
},
failure: function() {
alert("Notify the site owner that the xml file has a syntax error and is therefore unreadable.");
}
});
Code:
function fillChooseCompInAddDeviceDiv(){
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "2"},
dataType: "json",
success: function(data) {
$("table#choseComponentAddDeviceDiv").find("td").remove();
for(var i = 0; i<data.length; i++) {
$("table#choseComponentAddDeviceDiv").append("<tr>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].price + "</td>" + "<td>" + data[i].amount + "</td>" + "<td>" + data[i].description + "</td>" + "<td>" + data[i].categoryName + "</td>" + "<td>" + "<a href='" + data[i].link + "'>" + data[i].link + "</a>" + "</td>" + "<td>" + "<img src = '" + data[i].imagePath + "' />" + "</td>" + "<td>" + "<input type='checkbox' class='checkBoxCol' value='" + data[i].name + "'>" + "</td>" + "</tr>");
}
alert("ALERT 1");
},
error: function(status) {
//Do something
}
});
}
//any edit clicked in eny table
function anyEditOnCLick(buttonId, buttonVal){
window.editIsClicked = true;
$("input.nameInput").attr("readonly", true);
if (buttonId === "device"){
$("#addDeviceDiv").css("visibility", "visible");
window.location.hash = "#addDeviceDiv";
fillChooseCompInAddDeviceDiv();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "11", toEdit: buttonVal},
dataType: "json",
success: function(data) {
// puni text area
$("#addDeviceFieldName").val(data.name);
$("#addDeviceFieldDescription").val(data.description);
// cekira odgovarajuce komponente, jedan samo data se ocekuje, ne data[]
//fillChooseCompInAddDeviceDiv();
for (var i = 0; i<data.components.length; i++){
$("table#choseComponentAddDeviceDiv td input").filter(function(){return this.value == data.components[i].name}).attr("checked", true);
}
alert("ALERT 2");
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addDeviceDiv input#addDeviceFieldName").attr("readonly", true);
} else if (buttonId === "component"){
$("#addComponentDiv").css("visibility", "visible");
window.location.hash = "#addComponentDiv";
fillCategorySelection();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "21", toEdit: buttonVal},
dataType: "json",
success: function(data) {
$("#addComponentFieldName").val(data.name);
$("#addComponentFieldPrice").val(data.price);
$("#addComponentFieldAmount").val(data.amount);
$("#addComponentFieldDescription").val(data.description);
$("#addComponentFieldLink").val(data.link);
$("#form#uploadForm #imageFile").attr("value", data.imagePath);
//fillCategorySelection();
$("#addComponentDiv select.categorySelect option").filter(function(){return this.value == data.categoryName}).attr("selected", "selected");
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addComponentDiv input#addComponentFieldName").attr("readonly", true);
} else if (buttonId === "category"){
$("#addCategoryDiv").css("visibility", "visible");
window.location.hash = "#addCategoryDiv";
fillChoseSubCategoriesinAddCategoriesDiv();
$.ajax({
url: "${pageContext.request.contextPath}/StoreServlet",
type: "get",
data: {ajaxId: "31", toEdit: buttonVal},
dataType: "json",
success: function(data) {
$("#addCategoryFieldName").val(data.name);
$("#addCategoryFieldDescription").val(data.description);
//fillChoseSubCategoriesinAddCategoriesDiv();
for (var i = 0; i<data.subCategories.length; i++){
$("table#choseSubCategoriesinAddCategoriesDiv td input").filter(function(){return this.value == data.subCategories[i].name}).attr("checked", true);
}
},
error: function(status) {
//Do something
}
});
//name is unique - cannot be changed
$("#addCategoryDiv input#addCategoryFieldName").attr("readonly", true);
}
}
Function anyEditOnCLick(arg1, arg2) is event function and is placed in onClick tag of a button.
When I click on this button browser always first shows ALERT 2 message and after that go execute fillChooseCompInAddDeviceDiv() and shows ALERT 1. Can someone explain what is really happend here and how can I "persuade" javascript first execute fillChooseCompInAddDeviceDiv()? Before this, i thought function call provides executing whole function body before resuming execution of outer code.
I'm trying to show search results via AJAX to the view. The action gets JSON and sends it, but the AJAX seems to not be receiving the data.
$(function () {
$("#btnSearchForUser").click(function () {
var searchUserResult = $("#UserName").val();
var jsonResult = {
UserName: searchUserResult
};
$.ajax({
type: "POST",
async: false,
dataType: "json",
url: "/Car/ReturnCars",
data: jsonResult,
success: function (jsonResults) {
var table = $("#tblCarResults");
table.empty();
for (var i = 0; i < jsonResults.length; i++) {
var btnBill = "<td><input type='button' value='Get bill'/> <td>";
var btnReturn = "<td><input type='button' value='Return car'/></td>";
var tdUserName = "<td>" + jsonResults[i].UserName + "</td>";
var tdManufacture = "<td>" + jsonResults[i].Manufacturer + "</td>";
var tdModel = "<td>" + jsonResults[i].Model + "</td>";
var tdFee = "<td>" + jsonResults[i].Fee + "</td>";
var tr = tdManufacture + tdModel + tdFee + btnBill + btnReturn;
$(tr).appendTo(table);
};
},
error: function (error) {
alert("Error: " + error.status);
}
});
});
})
Edit: the success was not a mistype and has been corrected.
Since you have not answered my question in the comments. I am guessing btnSearchForUser is a submit button and you are not cancelling its click action.
$("#btnSearchForUser").click(function (event) {
event.preventDefault();