I am getting details from mongodb using express api and calling it using AJAX in front-end, i am able to get the details but not able to display it in a table.
I have tried appending it in a table. I have attached some code on what i have done.
The AJAX Part
$.ajax({
type: 'GET',
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost:8000/employees",
success:function(data){
data.forEach(element => {
$("#Name").append("<td>"+element.Name+"</td>");
$("#EmployeeId").append("<td>"+element.EmpId+"</td>");
$("#Designation").append("<td>"+element.Designation+"</td>");
$("#Email").append("<td>"+element.Email+"</td>");
});
},
error:function( errorMessage)
{
console.log(errorMessage);
}
});
The HTML part
<table>
<th>Name</th><th>EmployeeId</th><th>Designation</th><th>Email</th>
<tr>
<td id="Name"></td>
<td id="EmployeeId"></td>
<td id="Designation"></td>
<td id="Email"></td>
</tr>
</table>
I am currently getting entire output in single
i want the data in separate .
Current Output
You're getting all the data put into the same td because you're only using one row.
The way your code is running is basically...
<td id="Name">
<td>{value1}</td><td>{value2}</td>
</td>
....
You need to create rows tr inside the callback, instead of just appending data to the columns td
What you can do to fix this, is building entire rows in the success callback..
$.ajax({
type: 'GET',
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost:8000/employees",
success:function(data){
data.forEach(element => {
var row = document.createElement("tr");
var name = document.createElement('td');
var employeeID = document.createElement('td');
var designation = document.createElement('td');
var email = document.createElement('td');
name.innerHTML = element.Name;
employeeID.innerHTML = element.EmpID;
designation.innerHTML = element.Designation;
email.innerHTML = element.Email;
row.appendChild(name);
row.appendChild(employeeID);
row.appendChild(designation);
row.appendChild(email);
$('#table').append(row);
});
},
error:function( errorMessage)
{
console.log(errorMessage);
}
});
and in your HTML, just apply the ID to table or whatever you want.
Edit::
Also, syntactically, you should put the table headers inside a row as well, so,
<tr>
<th>Name</th>
<th>Employee ID</th>
...
</tr>
Related
I'm trying to pass a data to django view via ajax like I used to do with php but I get on print empty value but my console log show that there is a data value on javascript but on view return None
Quit the server with CONTROL-C.
None
my html file code
{% for image in images %}
<table style="width:100%;" id="tab-{{image.image_cid}}">
<tr>
<td style="width:70%;vertical-align:middle">
<img src="/medias/{{ image.image_value }}" alt="" width="100" >
</td>
<td style="width:30%;vertical-align:middle">
DELETE
</td>
</tr>
</table>
{% endfor %}
<script>
$(document).ready(function(){
$(".cl-img-del").click(function(e){
var imgID = e.target.id
console.log(imgID);
$.ajax({
headers: {'X-CSRFToken': '{{ csrf_token }}'},
url: "{% url 'delete-image-ajax' %}",
type: "POST",
data: { imageid: imgID },
contentType: false,
cache: false,
processData:false,
success: function(data){
if(data == 'done')
{
$('#tab-'+imgID).remove();
}
},
error: function(){}
});
});
});
</script>
and my view file code is
def deleteImageAjxFn(request):
if request.method == "POST":
imgid = request.POST.get('imageid')
print(imgid)
try:
image = Images.objects.filter(image_shw = int(0), image_cid=imgid).delete()
except Images.DoesNotExist:
image = None
if(image):
return HttpResponse('done')
else:
return HttpResponse('None')
use static url in ajax instead of dynamic django url tags
use this instead url: "/delete-image-ajax/"
I want to get the list of IP from a website and add them into an array. The website shows the data like this:
<tbody><tr role="row" class="odd">
<td>131.108.216.44</td>
<td>47267</td>
<td>BR</td>
<td class="hm">Brazil</td>
<td>elite proxy</td>
<td class="hm">no</td>
<td class="hx">yes</td>
<td class="hm">2 minutes ago</td>
</tr>
<tr role="row" class="even">
<td>85.173.165.36</td>
<td>46330</td>
<td>RU</td>
<td class="hm">Russian Federation</td>
<td>elite proxy</td>
<td class="hm">no</td>
<td class="hx">yes</td>
<td class="hm">2 minutes ago</td>
</tr>
</tbody>
This is actually a very long list with 100's of table but the format is the same.
What I did is :
var c = new Crawler({
maxConnections: 1,
callback: function (error, res, done) {
if (error) {
console.log(error)
} else {
var $ = res.$;
$('tbody>tr>td').each((i, el) => {
const item = $(el)
console.log(item.text());
})
}
done();
}
})
c.queue({
uri: 'https://free-proxy-list.net/'
})
I want to keep the first 10 IPs from the website and add them into an array.
The first 10 would look like this:
let proxies = $('tr[role=row]').map((i, tr) => {
let host = $(tr).find('td:nth-child(1)').text()
let port = $(tr).find('td:nth-child(2)').text()
return `${host}:${port}`
}).get().slice(0, 10)
For my class I have to design an app that says at the top of the page whether an incoming request is GET or POST, then has to print a table that shows all parameter names and values that were sent in the URL query string, and the property names and values that were received in the request body.
So far I have been able to get my localhost:port to work, it correctly shows whether a request is GET or POST. But when I go to the subpage that is supposed to display the tables, I get a 404 instead.
Here is the render page that I think is causing the problem:
function runQ(req) {
console.log(req.qParams);
console.log(req.body);
var context = {};
context.queryParams = [];
context.bodyParams = [];
context.queryCount = 0;
context.bodyCount = 0;
for( var p in req.qParams) {
context.queryCount++;
context.queryParams.push({'name': p, 'value': req.qParams[p] });
}
for( var p in req.body) {
context.bodyCount++;
context.bodyParams.push({'name': p, 'value': req.body[p] });
}
context.methodType = req.method;
return context;
}
app.get('/request', function(req, res) {
res.render('request', runQ(req));
});
app.post('/request', function(req, res) {
res.render('request', runQ(req));
});
I have a request.handlebar saved in my ubuntu/getpost/views folder along with the 404 and 500 handlebars.
The command I use for testing is:
$ curl --data "a=1&b=2&c=3" localhost:port
I replaced the localhost:port with an actual IP and port address when I have node running.
My console returns this on the tab that is running node:
undefined
{ a: '1', b: '2', c: '3' }
And this on the tab where I typed the cURL command:
<!doctype html>
<html>
<head>
<title>Demo Page</title>
</head>
<body>
<h1>POST Request Received</h1>
<table>
<caption><p>Request Body Table</p></caption>
<thead>
<tr>
<th>Property Names</th>
<th>Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>1</td>
</tr>
<tr>
<td>b</td>
<td>2</td>
</tr>
<tr>
<td>c</td>
<td>3</td>
</tr>
</tbody>
</table>
</body>
So everything seems to be working from the console but when I try to access localhost:port/request, I go to the 404 error instead of a page that displays the tables.
Can anyone tell me what I'm doing wrong? Thank you all for your time.
I have a view with a table of products that can be added to a shopping cart. Each row has a DropDownList with allowed quantities that can be ordered along with a button to add to cart. Everything is populating and displaying properly. I know how to pass the item ID in the ActionLink but how can I get the value of the DownDownList associated with the table row of the ActionLink that was clicked?
I am guessing possibly using JQuery that fires when the ActionLink is clicked?
I also thought of making every row a form but that seems overkill.
Is there an easy MVC way to do this?
In prepping more info for a proper question and went ahead and solved it. Thank you Stephen for the nudge and info.
I tried putting a Html.BeginForm around each <tr> tag in the details section. This did indeed work for me. I was able to easily get the unique form info to POST for each individual row. However, when I would enable JQuery DataTables the submit would break. DataTables must be capturing the submit or click somehow. Haven't figured that out but it made me try JQuery which seems a much better way to do it.
Here is how I construct the table data row:
#foreach (var item in Model)
{
<tr>
<td>
<img src="#item.GetFrontImage()" width="100" />
</td>
<td>
<strong>#Html.DisplayFor(modelItem => item.DisplayName)</strong>
</td>
<td>
#Html.DisplayFor(modelItem => item.CustomerSKU)
</td>
<td>
#Html.DropDownList("OrderQty", item.GetAllowedOrderQuantities(), htmlAttributes: new { #class = "form-control" })
</td>
<td>
<a class="btn btn-default pull-right" data-id="#item.ID">Add to Cart</a>
</td>
</tr>
}
This creates a select with id of OrderQty and I embedded the item ID in data-id attribute of the link. I then used this JQuery to capture the info and POST it to my controller. Just have a test div displaying the results in this example:
// Add to Cart click
$('table .btn').click(function () {
// Gather data for post
var dataAddToCard = {
ID: $(this).data('id'), // Get data-id attribute (Item ID)
Quantity: $(this).parent().parent().find('select').val() // Get selected value of dropdown in same row as button that was clicked
}
// POST data to controller
$.ajax({
url: '#Url.Action("AddToCart","Shopping")',
type: 'POST',
data: JSON.stringify(dataAddToCard),
contentType: 'application/json',
success: function (data) { $('#Result').html(data.ID + ' ' + data.Quantity); }
})
});
The JQuery function receives the reference to the link being clicked so I can extract the Item ID from the data-id attribute. I can then get a reference to the dropdown (select) that is in the same row by using .parent.parent (gets me to the <tr> tag) and then just finding the next 'select' tag. Probably pretty obvious to a lot of you.
This works great for my purposes. I can also update other elements with data returned from the POST.
Thank you
Karl
for the table in html:
<div class="table-responsive">
<table id="employeeTable"class="table table-bordered">
<thead>
<tr>
<th class="text-center">ُُُEmpId</th>
<th class="text-center">Name</th>
<th class="text-center">Absense State</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.Id</td>
<td>#item.Name</td>
<td class="text-center">#Html.DropDownList("DDL_AbsentStatus", new SelectList(ViewBag.statusList, "Id", "Name"), new { #class = "form-control text-center" })</td>
</tr>
}
</tbody>
</table>
</div>
in javascript to get the selected value:
//Collect Date For Pass To Controller
$("#btn_save").click(function (e) {
e.preventDefault();
if ($.trim($("#datepicker1").val()) == "") {
alert("ادخل تاريخ يوم صحيح!")
return;
}
var employeesArr = [];
employeesArr.length = 0;
$.each($("#employeeTable tbody tr"), function () {
employeesArr.push({
EmpId: $(this).find('td:eq(0)').html(),
EntryDate: $.trim($("#datepicker1").val()),
StatusId: $(this).find('#DDL_AbsentStatus').val()
});
});
$.ajax({
url: '/Home/SaveAbsentState',
type: "POST",
dataType: "json",
data: JSON.stringify(employeesArr),
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
emptyItems();
},
error: function (err) {
alert(err.statusText);
}
});
})
Is it possible to create a form visual webpart with fields like name, email, address and submit button. After user submit data should be submitted to sharepoint custom list here custom list will have same fields like name, email, address. I created one custom list.
I search on internet but i didn't find any solutions for that. Also am new to sharepoint. If any one can provide some links it will be helpful.
Thanks
Yes, this is very possible using jQuery and AJAX.
So, lets say that, just to be brief, this is your input:
<input type='text' id='name' />
<input type='submit' id='submitdata' value='submit />
Using jquery, you would do this:
$(function(){
$('#submitdata').click(function(){
//this gets the value from your name input
var name = $('#name').val();
var list = "PutYourListNameHere";
addListItem(name, list);
});
});
function addListItem(name, listname) {
var listType = "PutTheTypeOfListHere";
// Prepping our update & building the data object.
// Template: "nameOfField" : "dataToPutInField"
var item = {
"__metadata": { "type": listType},
"name": name
}
// Executing our add
$.ajax({
url: url + "/_api/web/lists/getbytitle('" + listname + "')/items",
type: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log("Success!");
console.log(data); // Returns the newly created list item information
},
error: function (data) {
console.log("Error!");
console.log(data);
}
});
}
This SHOULD work. I am not at work where my SharePoint station is, so if you are still having issues with this, let me know.
You may use SPServices also, It will work
<script type="text/javascript" src="~/jquery-1.5.2.min.js"></script>
<script type="text/javascript" src="~/jquery.SPServices-0.7.2.min.js"></script>
HTML
<input type='text' id='name' />
<input type='text' id='email' />
<input type='text' id='mobile' />
<input type='submit' id='submit' value='Submit' />
SPServices
<script type="text/javascript">
$("#submit").click(function(){
var Fname=$("#name").val();
var Email =$("#email").val();
var Mobile =$("#mobile").val();
$().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "New",
listName: "YourCustomListName",
valuepairs: [["Fname", Fname], ["Email", Email], ["Mobile", Mobile]], //"Fname","EMail" and "Mobile" are Fields Name of your custom list
completefunc: function(xData, status) {
if (status == "success") {
alert ("Thank you for your inquiry!" );
}
else {
alert ("Unable to submit your request at this time.");
}
}
});
});
</script>