This is the part of my html code that binds to the view using a Model object.
#if (Model.Comments != null)
{
#foreach (var thread in Model.Comments.Threads)
{
<div class="comment-wrap">
<div class="comment-head">
<div class="subsciber-user" style="background: #DDEFC5">#thread.UserName.Substring(0, 2).ToUpper()</div> #thread.UserName <span>#thread.PostedDate.ToString("dd MMM yyyy")</span>
<div class="edit-comment"><img class="comment-edit-img" src="~/images/edit-task.svg"></div>
</div>
<div class="clearfix"></div>
<div class="comment-content">
#thread.Content
</div>
#if (thread.Attachment != null)
{
<div class="comment-attachment">
<div class="ca-head">#thread.Attachment.Count() Attachments<i><img class="c-download" src="~/images/download.svg" alt="" /></i></div>
<div class="ca-tiles">
#foreach (var item in thread.Attachment)
{
<span><img src="#item.AttachmentUrl" alt="Smiley face"></span>
}
</div>
</div>
}
</div>
}
}
My requirement is I want to bind this HTML from a jquery Ajax Success. for that, I created an Ajax call.
var val1 = $('#TaskId').val();
#*$(document).ready(function () {
$.ajax({
url: '/Task/GetTaskComments',
data: { id: val1},
dataType: "json",
success: function (comments) {
// here i neeed to bind this Html block using each loop,
// here we are getting the same response that we are getting Model.Comments in the above code as json
}
});
});
I want to append the looped Html content from ajax success inside my
<div class="bindComments">
</div>
Related
I want to get values of a BeginCollectionItem using javascript but it seems like i am not winning
my html
#using HtmlHelpers.BeginCollectionItemCore
#using E_Commerce.Application.Models
#model ProductImageModel
<li class="mb-2">
#using (Html.BeginCollectionItem("ProductImages"))
{
Html.RenderPartial("_imagesPartial", Model);
}
</li>
the _imagesPartial html
#model E_Commerce.Application.Models.ProductImageModel
<div class="col-md-12 row mb-2">
<div class="col-md-4 imageDiv">
<img class="border rounded" />
</div>
<div class="col-md-4">
<input type="file" asp-for="File" onchange="uploadImageTest(this)" />
</div>
<div class="col-md-4">
Remove
</div>
</div>
and my javascript
let addNewImagesFormSubmit = (event) => {
var Id = $("#Id").val();
var productImages = $("#ProductImages").val();
$.ajax({
url: "#Url.Action("AddNewImages","ProductImage")",
data: {
Id: Id,
productImages:productImages
},
success: function (data) {
$("#productImagesDiv").html(data);
}
})
}
the server side does not seem to get any images when using javascript to get the BeginCollectionItem.
how do i get it to work
I have this part of HTML:
<div class="container">
<div class="row">
<div class="col-sm-4">
<div class="card">
<div class="card-body">
<h4 class="card-title">{title}</h4>
<p class="card-text">{content}</p>
Read...
</div>
</div>
</div>
</div>
</div>
and I have ajax request which calls after page loading:
<script>
$(window).on('load', function () {
loadArticles();
});
function loadArticles() {
$.ajax({
dataType: "json",
url: "/articles", success: function (result) {
}
});
}
</script>
I need to create list of cards(<div class="card">) with data from response. For example, I get 5 articles in response. I need to create 5 card divs and fill its data from the response. How can I do it?
Loop over the objects you get back from the ajax call and use the jQuery .append() function to add them to the dom.
First, you need to add an identifying class (or id) to the parent div in your HTML and remove the card HTML:
<div class="container">
<div class="row">
<div class="col-sm-4 cards-wrapper"></div>
</div>
</div>
Then in your loadArticles function loop over your ajax response and append to that jQuery selected we just defined - '.cards-wrapper':
function loadArticles() {
$.ajax({
dataType: "json",
url: "/articles",
}).done(function(data) {
const cards = data.body.cards; // Or however you need to traverse the response object
cards.forEach(function(card) {
$('.cards-wrapper').append('<div class="card"><div class="card-body"><h4 class="card-title">' + card.title + '</h4><p class="card-text">' + card.content + '</p>Read...</div></div>');
})
});
}
Ideally you should extract out that append code into its own function for readability, etc.
You can do it by simply using html template
HTML
First you need to add card-container id to the HTMl tag in which we will inject HTMl using ajax
<div class="container">
<div class="row">
<div class="col-sm-4" id="card-container">
</div>
</div>
</div>
Javascript
<script>
$(window).on('load', function () {
loadArticles();
});
function loadArticles() {
$.ajax({
dataType: "json",
url: "/articles", success: function (result) {
//Get template html using ajax and append it with **card-container**
var cardTemplate = $("#cardTemplate").html();
result.forEach(function (card) {
$('#card-container').append(cardTemplate.replace("{title}",
card.title).replace("{content}", card.content));
})
}
});
}
</script>
HTML Template
Assign id cardTemplate to html template
<template id="cardTemplate">
<div class="card">
<div class="card-body">
<h4 class="card-title">{title}</h4>
<p class="card-text">{content}</p>
Read...
</div>
</div>
</template>
I have also implemented on my end so it will surely gonna work !!!
I am returning JsonResponse with the required hash from Django view on a ajax call.
How to use the Json object inside html via {{}} (jinja templating). Below is my ajax call:
$(function () {
$('#getData').submit(function (e) {
e.preventDefault();
$.ajax({
url: "/Report",
type: 'get',
data: {
'date1': $('#d1').val(),
'date2': $('#d2').val(),
},
success: function (data) {
alert("Success");
// How to pass the data here to use it in html
}
});
});
});
My sample html :
<div id="maindiv" class="col col-5 col-sm-10" style="display: none;">
<div>
<h3> Showing Results for {{info.fromDate}} to {{info.toDate}}</h3>
</div>
<br><br>
<div id="summary">
<div class="card-deck">
<div class="card mx-auto">
<div class="card-body text-center">
<p style="text-align: center;vertical-align: middle;padding: 20px;" class="card-text">
<h1><b><span style="font-size:80px;">{{info.total}}</span></b></h1>
<h6> Total </h6>
</p>
</div>
</div>
<div class="card" id='chart1' style="width: 100%; height: 500px;">
<div class="card-body text-center">
<script>
Info = {{ info.marks| safe }}
createpiechart("marks", 'chart1', Info); <!-- This creates an amchart -->
</script>
</div>
</div>
</div>
</div>
This is just a sample. I have many more charts and processing for which I used the jsonresponse variable via {{}} inside html. What is the correct way to get the data from ajax to html?
Initially I used render to return response to html. But I see that the data I capture in ajax has the entire html replaced with the {{}} variable's value
return render(request=request, template_name='home/home.html', context={"info": InfoArray})
How to use the hash/context I pass from Django view inside html via a ajax ?
App\home.urls file:
urlpatterns = [
#path('', views.index, name = "index"),
path('', views.homepage, name="homepage"),
]
App\urls file:
urlpatterns = [
path('Report/', include('home.urls')),
path('admin/', admin.site.urls),
]
I have a scenario:
Here's my HTML code:
<input type="submit" id="btnpin" data-url="#Url.Action("PIn", "PIO")" value="P In" class="btn pin-btn" data-toggle="modal" data-target="#popup-article"/>
<div id="popup-article" class="popup">
<div class="popup__block">
<div style="overflow: auto">
<div class="top-left-logo">
<img src="~/Images/my-logo.png" width="270" height="99">
</div>
<div class="modal-top-right animated bounce delay-3s">
</div>
</div>
<div class='grid'>
<div class='col modal-left-panel '>
#{
foreach (var m in DTR.Models.DataDetails.lstDetails)
{
<div class="modal-left-text-container-top">
<div class="modal-employee-name animated bounceInLeft fast delay-2s" >#m.Name</div>
<div class="modal-employee-info">#m.Pos</div>
<div class="modal-employee-info">#m.Dep</div>
</div>
<div class="modal-left-text-container-mid">
<div class="modal-show-punch">
<div class="modal-show-punch-text">#m.PIO</div>
<div class="modal-show-punch-time">#m.IO</div>
<div class="modal-show-punch-date">#m.DateIO</div>
</div>
</div>
}
}
</div>
<div class='col modal-right-panel'>
}
</div>
</div>
</div>
</div>
And Here's my JS code:
$(document).ready(function () {
$('#btnpin').click(function () {
var url = $(this).data('url');
var punchIn = 'PunchIn';
$.ajax({
async: false,
type: "post",
contentType: "application/json; charset=utf-8",
data: "{'punchIn':'" + punchIn.toString() + "'}",
url: url,
success: function (response) {
//$(document).ajaxStop(function () {
// punchIn = null;
//});
if (response !== null && response.success) {
window.location.href = "#popup-article";
location.reload();
}
else {
alert("Already P In.");
}
},
error: function (response){
alert("Error Message");
},
});
});
});
This Code is working fine but my Problem is i need to use location.reload();
upon clicking the button btnpin because the value not showing if don't have this location.reload();
When loading the page the value is already fetched and done but when i click the button there's nothing else showing on the popup portion.
The problem of this location.reload();, the page showing two times and its annoying but the page and the value load perfectly.
How to make it with out using this location.reload();? it seems like i need to have some .fucos() on that particular popup class when the page is loaded.
Any idea is pretty much appreciated.
I have a list of resources which needs to be filtered based on the location. I have a form to filter and on click of a button, the data is filtered based on the location. I have an AJAX request and it sends a post request to /filterresources and the data matching that criteria is also fetched from the db and the resourcefilter.ejs is rendered using res.render() as given below:
resourcefilter.js:
router.post('/filterresources',function(req,res,next){
var category = req.body.category;
User.find({_id: {$ne: req.user._id}},(err,user) => {
if(err) throw err;
if(user)
{
db.findAll(Resource,{category:category})
.then(function(data){
res.render('resourcefilter',{title:"Steel Smiling",user:req.user,header:true,navbar:true,resources:data});
})
.catch(function(err){
next(err);
});
}
else {
throw(err);
}
});
});
The problem here is, as the records are fetched the UI doesn't get updated even when new ejs page is called. It still retains the previous page UI. But any console.log() statements in the new ejs page gets displayed.
resourcefilter.ejs: All console statements in this get printed without any issues but UI is not refreshed. Any help is much appreciated.
<% layout('layout/layout') %>
<div class="container user-form py-5">
<br>
<%if(user.role == 'Administrator'){ console.log(user.role);%>
<a href="/resourceupload" class="btn btn-outline-primary" style="float: right" ><span>Create Resource</span></a>
<%}%>
</br>
<span class="site-logo my-3">Our Resources</span>
<div class="col-12 col-lg-4 offset-lg-2" style="margin-left: 33%">
<form id="filter-resources" class="mt-5">
<div>
<select class="custom-select" name="category" id="category">
<option selected>Select a location:</option>
<option value="Pittsburgh">Pittsburgh</option>
<option value="Allegheny County">Allegheny County</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Outside Pennsylvania">Outside Pennsylvania</option>
</select>
<input class="filter" name="filter-resources" type="submit" value="Filter">
</div>
</form>
</div>
</form>
<div class="container" style="margin-top: 2%;">
<div class="row">
<% for(var i=0;i<resources.length;i++){ console.log("Hello"+resources.length); %>
<div class="col-xs-12 col-sm-6 col-md-4">
<div class="image-flip" ontouchstart="this.classList.toggle('hover');">
<div class="mainflip">
<div class="frontside">
<div class="card-custom">
<% console.log("Image"+resources[i].image);%>
<div class="card-body text-center">
<img src="<%= resources[i].image %>" alt="" class="img-resources">
<div class="card-title"><b><%= resources[i].name%></b></div>
<div id="greetings" class="card-title"><textarea readonly class="resourceDesc"><%= resources[i].description%></textarea></div>
<a href = <%= resources[i].website%> id="singlebutton" name="singlebutton" class="btn btn-primary">
Read More!</a>
<br></br> </div>
</div>
<br></br>
</div>
</div>
</div>
</div>
<% } %>
</div>
</div>
</div>
AJAX function to call to /filterresources:
function filter_resources(e) {
e.preventDefault();
var category = $('#category :selected').text();
console.log(category);
const button = this.children[this.children.length - 1];
//Form Handling with ajax
$.ajax({
url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',
});
function refreshDiv() {
document.getElementById("getelebyid").innerHTML = "Some <strong>HTML</strong> <em>string</em>" ;
}
}
Your ejs, js and html code are correct, the problem is that your AJAX function does not refresh the page's content, it only retrieves the content. There are 2 solutions: Either, in the EJS, change from "render" to "send" and then in the AJAX callback use the value returned as innerHTML for some element, or do a form submit, and not a jquery post. The form submit will cause a page reload.
If you don't have any errors from your server you can do a workaround with the front end:
$.ajax({
url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',
}).then(() => location.reload());
That will refresh your page when the request finishes.
location.reload() didn't work in this context because the filtered data needs to be passed on to the page. Hence, instead of using res.render(), i used res.send as suggested. Please find the below code:
filterresources.js
router.post('/filterresources',function(req,res,next){
var category = req.body.category;
User.find({_id: {$ne: req.user._id}},(err,user) => {
if(err) throw err;
if(user)
{
var user = req.user._id;
console.log(user);
db.findAll(Resource,{category:category})
.then(function(data){
res.send({msg: data, success: true,user: user });
})
.catch(function(err){
next(err);
});
}
else {
throw(err);
}
});
});
AJAX function:
function filter_resources(e) {
e.preventDefault();
var category = $('#category :selected').text();
console.log(category);
const button = this.children[this.children.length - 1];
//Form Handling with ajax
$.ajax({
url: '/filterresources',
type: 'post',
data: {category: category},
dataType: 'json',
success: function (response) {
if (!response.success) {
window.alert(response.msg);
}
if (response.success) {
var resource = response.msg;
var userInfo = response.user;
$('#resfilter').html(""); // reset the contents in the div
var html = `<div class="row">`;
for(var i=0;i<resource.length;i++) {
html += `<div class="col-xs-12 col-sm-6 col-md-4">
<div class="image-flip" ontouchstart="this.classList.toggle('hover');">
<div class="mainflip"> <div class="frontside"> <div class="card-custom">
<div class="card-body text-center">`;
html += `<img src="${resource[i].image}" alt="Mental Health Resource" class="img-resources">`;
html += `<div class="card-title"><b>${resource[i].name}</b></div>`;
html += `<div id="greetings" class="card-title"><textarea readonly class="resourceDesc">${resource[i].description}</textarea></div>`;
html += ``;
html += `Read More!`;
html += `<br>`;
html += `</br></div></div><br></br></div></div></div></div>`;
}
html += `</div></div></div></div>`;
}
document.querySelector('#resfilter').innerHTML = html; // add the html content to the div which was earlier reset
}
})
}