I have a problem with rendering handlebars.js template. I'm doing AJAX request to server, and servers returns me data which contains 'dishes' array with objects.Dish object contains id,price,weight,description,and array of photos. Then i render it with handlebars,and its works properly, 'html' variable containts rendered markup.
var data ;
var modalDishInfo;
var modalDishComments;
var vitrina;
function ajax(params){
$.ajax({
url: '/admin/getDishByCategory',
type: 'POST',
dataType: "json",
data: params,
success: function (result){
data = JSON.parse(result);
vitrina = Handlebars.compile( $('#vitrina_template').html() );
modalDishInfo = Handlebars.compile( $('#modalDishInfo').html() );
var html = vitrina(data.dishes);
console.log(html);
$('.foodmenucontent').empty();
$('.foodmenucontent').append(vitrina(data.dishes));
}
<script id="vitrina_template" type="text/x-handlebars-template">
{{#each this}}
<div class="col-lg-3 mealcard" >
<p class="text-center mealname">{{ dish_name }}</p>
<div class="weightandprice">
<div class="weightcontainer"><span class="mealweight pull-right">{{ dish_weight }} грамм</span></div>
<div class="pricecontainer"><span class="mealprice pull-left">{{ dish_price }} руб.</span></div>
</div>
<button class="orderbutton center-block">ЗАКАЗАТЬ</button>
</div>
{{/each}}
</script>
As you can see this code renders elements, which contains links with openModal() function.I have empty bootstrap modal window and want to render its content, according to clicked link.
function openModal(id){
var foo = id.slice(-1);
var modaldata = data.dishes;
var modaldish = $.grep(modaldata, function (element) {
return element.id == foo;
});
modaldish = modaldish[0];
console.log(modaldish);
var markup = modalDishInfo(modaldish);
$('#modalDishInfo').empty();
$('#modalDishInfo').append(markup);
$('#modalDish').modal('show');
$('.fotorama').fotorama();
};
and template
<script id="modalDishInfo" type="text/x-handlebars-template">
<div class="modalcontainer">
<div class="row">
<div class="col-lg-6">
<div class="fotorama" data-nav="thumbs" data-width="100%" data- thumbwidth="80" data-thumbheight="45"
data-transition="crossfade" data-loop="true" data-keyboard="true" data-navposition="bottom"
data-fit="cover" data-ratio="1600/900">
{{#each dish_photos}}
<img src="/uploads/gallery/{{ this.path }}" class="img-responsive" alt="">
{{/each}}
</div>
</div>
<div class="col-lg-6">
<p class="mealname">{{ dish_name}}</p>
<pre>{{ dish_description }}</pre>
<p>{{ dish_weight }}гр.</p>
<p class="mealprice">{{ dish_price }}руб.</p><br>
<button class="orderbutton ">ЗАКАЗАТЬ</button>
</div>
</div>
The problem is second template(modalDishInfo) dont want to render, console.log returns 'markup' variable completely empty. I tried different combinations of block helpers, and expressions,but none of them working. Maybe im missing something important? Or need to use specific expressions, when passing single object to template?
I found mistake that i did.My template id and container id(which is empty) are the same. So jquery selector returned me empty markup. I didn't notice that, because im using TWIG and my scripts was in {% verbatim %} tag to avoid TWIG errors, so i dont receive any errors or warning using duplicate ID's in code. Hope my answer is informative and can be helpful to someone.
Related
I am still very weak in Ajax, but they told me that this is a way out of the situation that I have developed.
I have a javascript function that filters categories. There is also alternation of lists in php.blade.
When I click on "All", all blogs are displayed and the alternation is working properly. When I select the "desired category", all blogs from this category are displayed, but alternation does not work.
I was prompted that you can is to call one ajax functional on category selection and return the HTML response on that ajax call. But I don't know how to do this, can anyone help?
JavaScript
$('.category-filter_item').click(function(){
$('.category-filter_item').removeClass('active')
$(this).addClass('active')
var dataFilter = $(this).attr('data-filter');
$('.blog-list').hide()
$(dataFilter).show()
})
php.blade
#extends('layouts.app')
#section('content')
<div class="container">
<div class="category-filter" id="filter">
<div class="category-filter_item active" data-filter="*">All</div>
#foreach($categories as $category)
<div class="category-filter_item" data-filter=".category_{{$category->id}}">{{ $category->title }}</div>
#endforeach
</div>
#foreach ($blogs as $index => $blog)
<div class="blog-list">
#if ($index % 2 === 1) //Alternation
<div class="blog blog--left" >
<h2 class="blog_title">{{ $blog->title }}</h2>
</div>
#else
<div class="blog blog--right">
<h2 class="blog_title">{{ $blog->title }}</h2>
</div>
#endif
</div>
#endforeach
</div>
#endsection
Controller
public function index()
{
$blogs = Blog::all();
$categories = Category:all();
return view('blog', compact('blogs', 'categories'));
}
Need to create new route and controller function to return only the selected category blogs and that should be in json format
Once that is done need to use the ajax call to the above route in the click function defined. Capture the response and then iterate and generate the html that should be inside the blog-list in your script. then update the html inside blog-list value.
refer this link
refer this for making ajax call link
I am trying to use handlebars templates. I used Express-handlebars for my server, and i want to use handlebars js for my client side rendering.
This is the script for the handlebars template.
<script id="some-template" type="text/x-handlebars-template">
<div class="row">
{{#each result}}
<!-- product -->
<div class="col-md-4 col-xs-6">
<a href="/product/{{_id}}"> <div class="product">
<div class="product-img">
<img src="\{{picture}}" style="height:160px;">
<div class="product-label">
{{#if percent}}
<span class="sale">{{percent}}%</span>
{{/if}}
<span class="new">NEW</span>
</div>
</div>
<div class="product-body">
<p class="product-category">{{category}}</p>
<h3 class="product-name">{{this.title}}</h3>
<h4 class="product-price">${{this.price}} <del class="product-old-price">${{this.discounted_price}}</del></h4>
{{#if this.averagerating}}
</div></a>
</div>
{{/each}}
</div>
</script>
For the client side
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.4.2/handlebars.js" integrity="sha256-hSzapznWRy/aOZkctlN03an9DxCLlN8ZCQS0lxntiHg=" crossorigin="anonymous"></script>
$('#mybutton').click(function(){
var post_url = $('#myform').attr("action");
var form_data = $('#myform').serialize();
// console.log(post_url, form_data);
var source = $("#some-template").html();
var template = Handlebars.compile(source);
$('#loader').show();
$.get( post_url, form_data, function( response ) {
$("#searchresult").html("");
console.log(response);
var data = template({result:response});
console.log(data);
$("#searchresult").html(data);
//$('#loader').hide();
});
My response is an array with an object inside, for example:[ {title:"Black Cap", price:60}].
But nothing shows on the page!!!. the data which i am supposed to send as html displays like :
:
<div class="row">
</div>
Please help. Thanks
You should make sure the data structure is correct:
try with this line in JS:
...
var data = template(response);
...
and in handlebars:
{{#each this}}
Handlebars js api, only accepts a javascript object.
if you create an object, Displayhtml with the result array as a field, like this :
Displayhtml={
results:[ {title:"Black Cap", price:60}]
}
Then you parse the object to the template: template(Displayhtml). then it works!!!
In front-end(you must but a \ before any helper in handlebars if you are also using handlebars as in server-side rendering ):
\{{# each results}}
\\do whatever you want.
\{{/each}}
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
I am working on a turn-based game where players can, but don't have to, gain ownership of certain spaces on the game board. My detail view in shows the spaces owned by each player, and I use a loop to display all owned spaces:
<small class="text-muted">Spaces Owned</small>
<div class="list-group list-group-flush">
{% for space in player.space_set.all %}
<a class="list-group-item" data-toggle="modal" data-target="#spaceModal" id="modalButton">
{{ space.name }}
</a>
{% endfor %}
</div>
I want to be able to populate a modal with all detailed information about whichever space is clicked on (hence why I'm using the anchor tag instead of a div, though I guess it might not matter as much). The modal would look something like this, though the goal is to populate it using appropriate IDs, etc using the response from the AJAX call instead of the template variables currently used as placeholders:
<div class="modal fade" id="spaceModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-body">
<div class="wrapper">
<div class="box">
<h2>{{ space.name }}</h2>
<div class="float-left">{{ space.location }}</div>
<div class="float-right">{{ space.defense_points }}</div>
<br />
<div class="float-right">{{ space.attack_points }}</div>
</div>
</div>
</div>
</div>
</div>
</div>
What I want to be able to do is use an AJAX call to populate the modal for each space as it is clicked. I have the server-side function set up okay and it is correctly returning the JSON needed when I process a simple get request (I'm using the following url pattern):
from django.urls import path
urlpatterns = [
path('<int:game>/space_data/<int:space>', get_space_data, name = 'get_space_data'),
]
with my views.py defined as:
def get_space_data(request,game,space):
game = Game.objects.get(pk=game)
space = game.space_set.get(location=space)
data = {
'name': space.name,
'location': space.location,
'defense_points': space.defense,
'attack_points': space.attack,
}
return JsonResponse(data)
Right now the JS that I'm using to test usage is the following:
<script>
$("#modalButton").click(function(){
var space = "{{ space }}"
console.log(space)
alert('Modal Button Clicked')
})
</script>
Summary
Essentially all I want to be able to do, which I can't figure out how to do, is pass the space variable to the JS code so that I can build the appropriate AJAX call within the last script code.
To touch on what Daniel wrote, what I was asking was simply how to pass Django template data to a JQuery script, which I would then use in an AJAX call. I figured it out, though, and will post my answer here instead of just deleting the question.
The modal pop-up anchor tag should look like this:
<small class="text-muted">Spaces Owned</small>
<div class="list-group list-group-flush">
{% for space in player.space_set.all %}
<a class="list-group-item" data-toggle="modal" data-target="#spaceModal" id="modalButton" data-location="{{ space.location }}">
{{ space.name }}
</a>
{% endfor %}
</div>
and the resulting JQuery code is as follows:
<script>
$("#modalButton").click(function(){
console.log($(this).data('location'))
alert('Modal Button Clicked')
})
</script>
From this I will be able to add an actual AJAX call to the script and pull the data as needed.
in this way you send the variables to the js to use them in the ajax
{% block scripts %}
<script>
var name = {{space.name}}
var location = {{space.location}}
</script>
<!-- JS Template -->
<script src="{% static 'folder/name.js' %}"></script>
{% endblock scripts %}
and your js
$.ajax({
url: url,
method: "",
data: {
"name" : name,
"location":location
},
success: function (_response) {
},
)
I'm using meteor.js and playing around with a simple application. I have a form on my page and once submitted the data is inserted into a database. I have a 'feed' of data on the left side of my page which updates when a new entry in the database is submitted, displaying the data. This is basic data at present about countries and populations etc. My question is how to mix a js variable to vary the source of an image file thats loaded in this 'feed' - hopefully explained below.
So, in code, I have this:
<template name="mainLeftCol">
<div class="col-sm-5">
{{> form}}
</div>
</template>
<template name="mainBody">
{{> mainLeftCol}}
<div class="col-sm-7">
{{#each dbEntry}}
{{> formItem}}
{{/each}}
</div>
</template>
and in a js file I have the event code for when the form is submitted:
Template.mainLeftCol.events({
'submit form': function(e) {
e.preventDefault()
var country = $(e.target).find('[id=country]').val()
prefix = country.slice(0,3);
if (prefix === 'Eng') {
console.log("Eng is for England");
}
var spot = {
country: country,
continent: $(e.target).find('[id=continent]').val(),
};
spot._id = Spots.insert(spot);
}
});
The formItems are being displayed using the following template which outputs the 'variables' that were input in the form:
<template name="formItem">
{{#Animate}}
<div class="panel panel-default spot animate">
<div class="panel-heading">
<h5 class="pull-right">{{country}}</h5>
<h4><mark><b>{{continent}}</b></mark></h4>
</div>
<div class="panel-body">
<img src="Eng.png" class="img-circle pull-right">
</div>
</div>
{{/Animate}}
</template>
As you can see in this template I have hardcoded "Eng.png" as the source for the image. What I would like to do is based on the prefix variable which slices the country field is to have the template display a different image (they're flags) based on the country on the template.
How can I mix a JS variable from my events code into the source of the image file in my template code?
Hope this makes sense!
I don't know if i got i right, but if you want to change the image (flag) according to the country try something like this:
Build a Template helper "prefix" which outputs the current country prefix.
Prefix helper:
Template.formItem.helpers({
countryPrefix: function () {
var country = $(e.target).find('[id=country]').val()
return country.slice(0,3);
}
});
In your Template you can now:
<div class="panel-body">
<img src="{{countryPrefix}}.png" class="img-circle pull-right">
</div>