Use JsonResponse variable from Django in Html via ajax - javascript

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),
]

Related

How do I get the values of a BeginCollectionItem in javascript

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

Load list objects in ajax response and create dynmic list divs with this data

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 !!!

Using AJAX in Node js and displaying data using Handlebars

I am using AJAX and Handlebars to get data from my MongoDB without refreshing the page and represent it in an easier manner.
I have created a div with a search button where a user places his/her inputs. These inputs need to passed to my routes and then the results from my DB should be sent back from my routes, to the handlebar which will help me display the products.
index.hbs
<div id="search-form">
....
<input id="bhkInput" name="bmin" type="number">
<input id="priceMin" name="pf" type="number">
<input id="priceMax" name="pt" type="number">
<input type="submit" class="btn searchButton" id="submit" value="Search" onclick="showResults()">
</div>
<div class="row col-sm-12 searchResults" id="sr">
//Results need to be displayed here
</div>
<script id = "result-template" type="text/x-handlebars-template">
{{#each searchResults }}
<div class="row">
{{#each this }}
<div class="col-sm-6 col-md-4">
...
<img src="{{this.imagePath}}" alt="..." class=" card-img-top">
<div class="card-body">
<h4>Flat No: {{this.flatNo}}</h4>
...
<p class="description">
{{this.description}}
</p>
...
...
</div>
</div>
</div>
</div>
{{/each}}
</div>
{{/each}}
</script>
<script>
function showResults(){
let bmin = document.getElementById('bhkInput').value;
let pf = document.getElementById('priceMin').value;
let pt = document.getElementById('priceMax').value;
$.ajax({
type: 'GET',
data: {
bmin: bmin,
pf: pf,
pt: pt
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
url: "/results",
success: function(data){
let source = $('#result-template').html();
let template = Handlebars.compile(source);
let html = template(data);
$(".searchResults").innerHTML = html;
}
});
}
The issue that I am facing:
When I send back the results from my DB, I am unable to display it using Handlebars.
How do I handle the data after success function is called. I want the results to be appended in the 'searchResults' div. I went through this link, however I am yet not able to see the data of my results.
Update
I took dummy data from the Handlebars Docs and used it for my template and yet there is no data being appended in the html
The console.log(html) returns the template without the new data items
index.hbs
<script id="entry-template" type="text/x-handlebars-template">
<div class="entry">
<h1>{{title}}</h1>
<div class="body">
{{body}}
</div>
</div>
</script>
<script>
....
$.ajax({
....
success: function(data){
var source = document.getElementById("entry-template").innerHTML;
var template = Handlebars.compile(source);
var context = {title: "My New Post", body: "This is my first post!"};
var html = template(context);
console.log(html);
....
</script>
Output for console.log(html)
<div class="entry">
<h1></h1>
<div class="body">
</div>
</div>
For the first issue. Your method is GET so I think you can get it by req.query.productId.
For the second issue. You should append your data in ajax success callback function, because ajax is asynchronous. For example:
$.ajax({
type: 'GET',
data: encodeURIComponent(searchObject),
url: "/results",
success: function(data){
console.log(data);
let sr = document.getElementById('sr');
$(sr).append();
}
});
How to get "data" from JQuery Ajax requests

Bind Multi Line HTML content from JQuery Ajax response

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>

display data in bootstrap card from web service call

I'm interested in dsiplaying data from web service call in the bootstrap card. Most of the example i see are using hard coded data, I have a simple UI to display web service data using bootstrapTable and bootstrap card.
<div class="card" id="card-data">
<div class="front">
<h1 id="front-label">{data.number}</h1>
<p>
<span ><span class="card-front">Name :</span> {data.name}</span><br/>
<span ><span class="card-front">Type :</span> {data.type} </span><br/>
<span ><span class="card-front">Updated :</span> {data.date} </span><br/>
<p>
</div>
</div>
script logic
var data;
$(function () {
$.getJSON("http://localhost:8080/xxxxxx/getData", function(json){
data = json;
/*perhaps load data by id */
.......
});
});
I could have done this in angular or react by expressions on $scope or 'props` but we are not using any framework for this UI.
Not the cleanest way but I was able to retrieve the JSON data and display it on the card.
<div class="card" id="card-data">
<div class="front">
<h1 id="data_number"></h1>
</div>
</div>
empty value will be replaced with value in <h1 id="data_number"></h1>
script
$(document).ready( function () {
var data = $.getJSON("http://localhost:8080/xxxxxxx/getData", function(data) {
$("#data_number").html(data[0].number);
});
});

Categories

Resources