Jquery total noob import inquiry relating to where to put files - javascript

I downloaded the Jquery Raty plugin: https://github.com/wbotelhos/raty
Then I installed this folder structure into my {{static_url}}js folder and named it Raty.
Then I imported it into my template as follows and put the path as the location of where its images are stored.
<script type="text/javascript" charset="utf-8" src="{{ STATIC_URL }}js/raty/js/jquery.raty.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('.thingrating').each(function(index){
$(this).raty({
readOnly: false,
path: "{{ STATIC_URL }}js/raty/img/",
start: $(this).children("span:first").text(),
click: function(score, evt) {
var vote_url = "rate/" + this.attr('id').substring(2) + "/" + score + "/";
$.ajax({
url: vote_url,
success: function(){
alert('vote successful');
}
});
}
});
});
});
</script>
Is this correct? I'm not seeing that it is working in my template, so want to make sure this process of storing the script and importing it into my template is correct before I continue to decipher what is wrong...
Here's the rest of my template:
{% block body %}
<h2>Things</h2>
<div class="block" id="block-tables">
<div class="content">
<p></p>
<div class="inner">
<table class="table">
<tr>
<th class="first">Name</th>
<th class="last">Rating</th>
</tr>
<tr class="odd">
<td>{{ item.modelname }}</td>
<td><div class="thingrating" id="t_{{ item.id }}"><span style="display:none;">{{ score }}</span></div></td>
</tr>
</table>
<div class="actions-bar wat-cf">
</div>
</div>
</div>
</div>
{% endblock %}

Take a look at this jsfiddle demo. It works fine (well, except that looks like start should be changed to score as I understand that way you want to define initial score). Incorrect path to images will not break it at all. Browser will simply show default icon for not available image if path to images is wrong. Not sure what is in {{static_url}} variable. If it contains something like 'http://example.com/static' - you must add a slash after it.
Possible problems - script tag for raty appears before jQuery. Or results of template processing are not available on page when $(document).ready event happens.

Related

my select2 jquery only work for the first form

i want to use select2.min.js to auto-complete the choices (ForeignKey values) , but it only work for my first form , i used django formset for duplicate forms
this is my snippet
<tbody class="tbody tb1 " id="form_set">
{% for item in items.forms %}
<tr class="p-0 col-12">
<td class="">
<div class="col-12 p-0 mt-3 inp">
<input class="col-12 0qarz qarz" type="number" name="" placeholder="qarz">
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.price | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.quantity | add_class:'col-12 '}}
</div>
</td>
<td class="">
<div class="col-12 p-0 mt-3 inp">
{{item.model | add_class:'col-12 0model model' | attr:'id:model'}}
</div>
</td>
</tr>
{% endfor %}
</tbody>
<script type="text/javascript">
$(function(){
$('.tb1 tr:last').formset({
prefix:'{{items.prefix}}',
addText:'add',
deleteText:'remove',
addCssClass:'btn btn-success',
});
})
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#model").select2()
})
</script>
but the select2 only work for my first form then doesnt have any effect on other forms ! and how to set number of forms to add_class it will help to solve maybe?
thanks
First of all I would love to see a little bit more, for example how you actually define your formset. It is not also clear to me what are you trying to do here. Please paste more data.
I would suggest that you think about using django-select2 module that helps a lot with handling select2 stuff in django.
I am also not sure what you mean by "how to set number of forms", maybe you wish to include some incremental counter that can be done with {{ forloop }} inside for/endfor loop?
Please paste more stuff and answer will be better.
The selector you are using to initialize select2 #model is for element ids, which should be unique for each element in the DOM.
In most browsers the effect will be that only the first instance of an element id will be recognized, and the rest ignored as if they don't exist.
In this instance you want to use a class selector: .model. This will ensure select2 is initialized for all elements that have the class "model". So the code to initialize select2 would be:
<script type="text/javascript">
$(document).ready(function(){
$(".model").select2()
})
</script>
You have to reinitialize(like this way: $("#model").select2();) the select2 for other pages when they appear.
You should need separately initialize with different ids.
for example:
<script type="text/javascript">
$(document).ready(function(){
$("#id_1").select2();
$("#id_2").select2();
})
</script>
the way I found is sending the number of forms through context then apply for loop in the template.
views.py
get_context_data()
context.update({
"accessoryNum": len(StoreRequestAccessory.objects.filter(storeRequestId=self.object.pk)),
"oneDimensionalItemNum":len(StoreRequestOneDimensionalItem.objects.filter(storeRequestId=self.object.pk)),
"twoDimensionalItemNum":len(StoreRequestTwoDimensionalItem.objects.filter(storeRequestId=self.object.pk)),
})
template.html
{% block javascripts %}
<script>
{% comment %} get accessoryNum from context {% endcomment %}
var accessoryNum = {{accessoryNum}};
$(document).ready(function(){
for(let i = 0; i <=accessoryNum; i++){
$(`#id_storereq_accessory_form-${i}-accessoryId`).select2({
placeholder: "Select a Item",
allowClear: true
});
}
});
</script>
{% endblock javascripts %}

Django Template Value Passed to Javascript

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) {
},
)

convert from PHP to JSON file to to draw chart wirth JS

i want to extract data from the database and send as JSON file to the front-end and then try to draw graph. i have three tables notification where the website url is saved, status that has status and speed( google page speed) and a pivot table where all data related to a website is stored as values. i have model, and inside the model, i have a function that makes many to many relations between notifications and status table.
i have a controller called chart controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ChartController extends Controller
{
public static function speedHistory(){
$o_status = Status::where('name','speed')->first();
$o_response = $this->statuses()->where('status_id', $o_status->id)
->select('values AS value', 'created_at AS timestamp')->orderBy('created_at','DESC')->get();
if($o_response){
return response()->json($o_response);
}
// return an empty json array instead of false
//return false;
return response()->json(array());
}
}
and a front end page called app.js
document.addEventListener('DOMContentLoaded', function(){
$.getJSON("/json", function (result) {
alert(result)
}
and a route
Route::get('json','ChartController#speedHistory');
i use alert to see,if the data is going to app.js but it doesnt work. i would apperciate nay kind of help and suggestions?
this is the view file
extends('layout')
#section('header')
<a class="logout" href="<?php echo 'login'?>">Logout</a>
<a href="{{ URL::to('/') }}">
<img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/Crystal_button_cancel.svg/32px-Crystal_button_cancel.svg.png" alt="Submit" width="48" height="48">
</a>
#stop
#section('content')
<script src="app.js"></script>
<table class="table">
<thead>
<h3>{{ $notification->website_url }}</h3>
<tr>
<th>date</th>
<th>status</th>
</tr>
</thead>
<tbody>
<?php $notificationHealth = $notification->history('health'); ?>
#foreach($notificationHealth as $status)
<tr>
<td>{{ $status['timestamp'] }}</td>
<td> {{ $status['value'] }}</td>.
</tr>
#endforeach
</tbody>
</table>
<canvas id="pageSpeedHistoryChart" width="200" height="50"></canvas>
#stop
#section('footer')
#stop
Can you add more details?
With /json you are calling a page under the same domain. Is this right?
You can use developer tools of chrome. Under network tab you can see the response of the call that you have done.

Handlebars.js returns empty markup

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.

Javascript Template Engine Use with jQuery

All,
I'm trying to use the jQuery File Upload Demo:
http://blueimp.github.com/jQuery-File-Upload/
My question is that it says in the Documentation that it uses the Javascript Template Engine (https://github.com/blueimp/jQuery-File-Upload/wiki/Template-Engine)
However, I'm not familiar with this process. I'm trying to integrate this into my Wordpress blog to allow file uploads this way. Within the index.html it has the following Template defined:
<script id="template-upload" type="text/x-tmpl">
{% for (var i=0, file; file=o.files[i]; i++) { %}
<tr class="template-upload fade">
<td class="preview"><span class="fade"></span></td>
<td class="name">{%=file.name%}</td>
<td class="size">{%=o.formatFileSize(file.size)%}</td>
{% if (file.error) { %}
<td class="error" colspan="2"><span class="label label-important">{%=locale.fileupload.error%}</span> {%=locale.fileupload.errors[file.error] || file.error%}</td>
{% } else if (o.files.valid && !i) { %}
<td>
<div class="progress progress-success progress-striped active"><div class="bar" style="width:0%;"></div></div>
</td>
<td class="start">{% if (!o.options.autoUpload) { %}
<button class="btn btn-primary">
<i class="icon-upload icon-white"></i> {%=locale.fileupload.start%}
</button>
{% } %}</td>
{% } else { %}
<td colspan="2"></td>
{% } %}
<td class="cancel">{% if (!i) { %}
<button class="btn btn-warning">
<i class="icon-ban-circle icon-white"></i> {%=locale.fileupload.cancel%}
</button>
{% } %}</td>
</tr>
{% } %}
</script>
I'm using the jQuery Tmpl code (https://github.com/jquery/jquery-tmpl) and when I try and create this in my Wordpress blog I get some errors in my jquery.fileupload-ui.js file on these lines:
_initTemplates: function () {
var options = this.options;
options.templateContainer = document.createElement(
this._files.prop('nodeName')
);
options.uploadTemplate = tmpl(options.uploadTemplateId);
options.downloadTemplate = tmpl(options.downloadTemplateId);
},
Earlier in this file this is defined as this: uploadTemplateId: 'template-upload',
I'm confused why this wouldn't work or even how to use my own javascript template to do this? When I try and copy these files into my Wordpress blog it always fails and the only thing I don't think I copy is the package.JSON and the .gitignore files in the initial download. What significance do these files play? Just trying to understand what this template is and how to use it?
Anything you can point me to in advance is greatly appreciated! Thanks for the help!
.gitignore is a source control file and not relevant to the scripts - see http://help.github.com/ignore-files/ for more info.
package.JSON is a metadata file for jquery plugins for use by the new jquery plugin site and is nothing to do with the functioning of the plugin you are trying to use - see https://github.com/jquery/plugins.jquery.com#readme for more info.
My best guess for the error is a clash of script files between the plugin and what you already have on wordpress.
Could you post the actual error message(s)?

Categories

Resources