In the code below I have two Canvas layers one text and one image, the issue I'm having is controlling which layer draws first. When the page is loaded the text may draw above or blow the image, it seems pretty random. Is there a way I can control this behavior?
My attempt:
{% extends "layout.html" %}
{% block body %}
<script>
window.onload = function(){
$("canvas").addLayer({
method: "drawImage",
source: '{{ url_for('static', filename='100MV-Floor-Plan.png') }}',
x: 700, y: 300,
})
$("canvas").addLayer({
method: "drawText",
strokeStyle: "C35817",
x:{{ room.xPos }}, y: {{ room.yPos }},
text: '{{ room.room_id }}',
align: "center",
baseline: "middle"
})
$("canvas").getLayer(0);
$("canvas").getLayer(1);
$("canvas").drawLayers();
};
</script>
<canvas width="1397" height="711"></canvas>
<h1>{{ room.current_user }}</h1>
<form method=POST>
Room ID: <input type="text" name="room_id"/><br />
<input type="submit" value="Click" class="button">
</form>
{% endblock %}
After going back and looking over the jcanvas doc's again I found a solution. By using drawImage()'s "load" call back function I'm able to call drawText() after the image has been loaded.
Updated Code:
1 {% extends "layout.html" %}
2 {% block body %}
3 <script>
4 window.onload = function(){
5 $("canvas").drawImage({
6 source: '{{ url_for('static', filename='100MV-Floor-Plan.png') }}',
7 x: 700, y: 300,
8 load: displayText
9 })
10
11 function displayText() {
12 $("canvas").drawText({
13 strokeStyle: "C35817",
14 x:{{ room.xPos }}, y: {{ room.yPos }},
15 text: '{{ room.room_id }}',
16 align: "center",
17 baseline: "middle"
18 });
19 };
20 };
21 </script>
22 <canvas width="1397" height="711"></canvas>
23 <h1>{{ room.current_user }}</h1>
24 <form method=POST>
25 Room ID: <input type="text" name="room_id"/><br />
26 <input type="submit" value="Click" class="button">
27 </form>
28 {% endblock %}
Related
Im building a simple app to practise Nuxt and axios with the CocktailDB API https://www.thecocktaildb.com/api.php. I have troubble getting the images to show rather than just the links. In console.log the links also shows. How do I get the images from the API to show in the list, and not only the link? Thanks in advance!
<template>
<div>
<div>
<SearchDrink/>
</div>
<div>
<div v-for="drink in drinks" :key="drink.id">
<div class="drink">
<p> {{ drink.strDrink
}} </p>
<img src="" alt=""/> {{ drink.strDrinkThumb
}}
<p>Instructions:</p>
<p> {{ drink.strInstructions }} </p>
<div class="ing"> Ingridients:
<p> {{ drink.strIngredient1 }} </p>
<p> {{ drink.strIngredient2 }} </p>
<p> {{ drink.strIngredient3 }} </p>
<p> {{ drink.strIngredient4 }} </p>
<p> {{ drink.strIngredient5 }} </p>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import SearchDrink from '../../components/SearchDrink.vue'
import axios from 'axios'
export default {
components:{
SearchDrink,
},
data(){
return {
drinks: [],
}
},
methods: {
getAllDrinks(){
axios.get('https://thecocktaildb.com/api/json/v1/1/search.php?s=')
.then((response) => {
this.drinks = response.data.drinks
const myDrink = response.data.drinks
console.log(myDrink)
console.log(myDrink.strDrinkThumb)
})
.catch((error) =>{
console.log(error)
})
},
},
created(){
this.getAllDrinks()
},
// methods: {
// searchDrink(){
// if(!this.search){
// return this.drinks
// }else{
// return this.drinks.filter(drink =>
// drink.text.toLowerCase().includes(this.search.
// toLowerCase()))
// }
// }
// },
head(){
return {
title: 'Drinks App',
meta: [
{
hid: 'description',
name: 'description',
content: 'Best place to search a Drink'
}
]
}
}
}
</script>
you're not putting the image inside the src tag.
This can be done using the v-bind directive as
v-bind:src="..." or :src=".."
Example :
new Vue({
el: "#app",
data: () => ({
drinks: []
}),
mounted(){
axios.get('https://thecocktaildb.com/api/json/v1/1/search.php?s=')
.then((response) => {
this.drinks = response.data.drinks
})
}
})
img {
height: 200px;
width: 200px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.1/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<ul>
<li v-for="drink of drinks">
<img :src="drink.strDrinkThumb"/>
</li>
</ul>
</div>
I'm new to using Ajax calls with Django. Im trying to implement a simple Display or not display depending on the type of get called by Ajax:
Views:
def dynamic(request):
context = {}
if request.method == 'GET':
if 'backtest_type' in request.GET:
context['display_details'] = False
print ('Im not displaying')
elif 'change_val' in request.GET:
context['display_details'] = True
print ('Im displaying')
else:
context['display_details'] = False
return render(request, "demo/dynamic.html", context)
In my template:
{% extends 'demo/base.html' %}
{% block body %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link rel="stylesheet" href="{% static 'css/dynamic.css' %}">
<script>
$(document).on('click','#id_backtest_type', function () {
console.log( $(this).val() );
$.ajax({
type: 'get',
data: {'backtest_type': 1},
success: function (data) {
console.log('data sent ' + data);
},
failure: function(data) {
alert('Got an error dude');
}
});
});
$(document).on('click','#btnClick', function () {
// console.log( $(this).val() );
$.ajax({
type: 'get',
data: {'change_val': 1},
success: function (data) {
console.log('data sent ' + data);
failure: function(data) {
alert('Got an error dude');
}
});
});
</script>
<div>
{% if display_details %}
<h1>I'm diplaying</h1>
{% endif %}
</div>
<div id="btnClick" class="col-sm-4">
<div class="btn-group btn-group-justified" role="group">
<div class="btn-group" role="group">
<button class="btn btn-secondary" type="button">Don't Display</button>
</div>
</div>
</div>
<div id="id_backtest_type" class="col-sm-4">
<div class="btn-group btn-group-justified" role="group">
<div class="btn-group" role="group">
<button class="btn btn-secondary" type="button">Display!</button>
</div>
</div>
</div>
{% endblock %}
From the console I'm sure that the get requests are being correctly sent using ajax (the get requests are being sent and the console prints the statements:
[09/Feb/2019 20:00:56] "GET /dynamic/?backtest_type=1 HTTP/1.1" 200
6530
Im displaying
However, even if the ajax call works correctly, the template doesn't end up rendering <h1>I'm diplaying</h1>. Am I misunderstanding anything about Ajax?
Thanks in advance!
Need help with Vuejs, as I'm very new to it.
I have form selector, and depends on selected item I should display information from selected item below the form and send id of this item to my form request.
Visual understand:
I have tried v-bind:value="post.id" make like v-bind:value="post"
and I can easy display #{{post.goal}}, but it sends {object Object} to my request.
Please help who have more skill.
My selector:
<div class="uk-form-controls" id="equity-name">
<select name="share_id" v-model="post">
<option v-for='post in posts' v-bind:value="post.id">#{{post.title}}</option>
</select>
{{-- Here I need help --}}
<div v-if="post">
selected post:
#{{post.goal}} {{-- HOW TO DISPLAY GOAL IN DOM? --}}
</div>
And my Vue:
<script type="text/javascript">
new Vue({
el: "#equity-name",
data: function() {
return {
posts: [
#foreach($company->equities as $equity)
{title: "{{ $equity->name }}", id: '{{ $equity->id }}', goal: '{{ $equity->goal() }}' },
#endforeach
],
post: null
}
},
})
</script>
Cheers, love!:)
Make a method getPostGoal to get goal of selected index
new Vue({
el:"#app",
data:{
posts:[
{id:1,title:'test1',goal:'goal1'},
{id:2,title:'test2',goal:'goal2'},
{id:3,title:'test3',goal:'goal3'},
],
post:1
},
methods:{
getPostGoal:function(id=null){
if(id){
var index = this.posts.map(e=>e.id).indexOf(id);
return this.posts[index].goal;
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<div class="uk-form-controls" id="equity-name">
<select name="share_id" v-model="post">
<option v-for='p in posts' v-bind:value="p.id">{{p.title}}</option>
</select>
<div v-if="post">
selected post:
{{getPostGoal(post)}}
</div>
</div>
</div>
</div>
Another solution is, set object as value
new Vue({
el:"#app",
data:{
posts:[
{id:1,title:'test1',goal:'goal1'},
{id:2,title:'test2',goal:'goal2'},
{id:3,title:'test3',goal:'goal3'},
],
post:{goal:'NA'}
},
mounted(){
if(this.posts.length){
this.post = this.posts[0];
}
},
methods:{
getPostGoal:function(id=null){
if(id){
var index = this.posts.map(e=>e.id).indexOf(id);
return this.posts[index].goal;
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div>
<div class="uk-form-controls" id="equity-name">
<select name="share_id" v-model="post">
<option v-for='p in posts' v-bind:value="p">{{p.title}}</option>
</select>
<div v-if="post">
selected post:
{{post.goal}}
</div>
</div>
</div>
</div>
Hi I've run into a problem where I am trying to make it so when a button is clicked an object can be made. I can't get it to work as for some reason it will not validate, however if I change input type to submit it works fine.
But the problem is when I use it as submit the page redirects which defeats the purpose of using AJAX.
I can't seem to find a good tutorial for what I'd like to do, any help or links would really be appreciated!
Models
class MemberRole(models.Model,get_fields):
name = models.CharField(max_length = 20)
Form
class MemberRoleForm(forms.ModelForm):
class Meta:
model = MemberRole
Views
This view builds the form for the memberrole model
def add_member(request):
model_url = 'member-add'
rform = MemberRoleForm(instance=MemberRole())
return render_to_response('create_model.html', {'role_form': rform,'model_url': model_url,},context_instance=RequestContext(request))
This ajax called view
#require_POST
def ajax(request):
data = request.POST.get("rolename","")
if request.method == 'POST':
rform = MemberRoleForm(request.POST, instance=MemberRole())
if rform.is_valid():
new_role = rform.save()
new_role.name = data
return HttpResponse("SuccessFully Saved")
else:
return HttpResponse("Error in saving")
Template
<div id="addRoleOnMemberForm">
<form id = "addrole" onsubmit= "return false;" method="POST">
{% csrf_token %}
{% for field in role_form %}
{{ field.errors }}
{{ field.label_tag }} {{ field }} //#id_name is in here
{% endfor %}
<input id="addrolebutton" type="button" onclick = "createit()" value="Add New Role"/>
</div>
{% for x in role_list %}
<div>
<p> This shows a role was made </p>
</div>
{% endfor %}
Script
<script>
function createit(){
$.ajax({
type: "POST",
url:"ajax",
dataType:"json",
async: true,
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
rolename: $('#id_name').val()
},
});
}
</script>
I've finally managed to get it to work. :)
I have an add_member view which allows the creation of a memberrole object if it is not available in the member.role dropdown field. The memberrole object on creation will be added without a page reload to the dropdown field so it can be selected immediatly.
I'm not entirely sure if this would be the correct way of coding it, I've included all the source and hopefully it helps someone like me. Comments would be appreciated!
Models
class MemberRole(models.Model,get_fields):
name = models.CharField(max_length = 20)
class Member(models.Model,get_fields):
first_name = models.CharField(max_length = 20)
last_name = models.CharField(max_length = 20)
role = models.ForeignKey(MemberRole, null = True, blank = True)
Forms
class MemberForm(forms.ModelForm):
class Meta:
model = Member
Script
<script>
function createit(){
$.ajax({
type: "POST",
url:"addrole",
dataType:"json",
async: true,
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
rolename: $('#role_name').val()
},
success: function (json,rolename){
$('#output').html(json.message); // Prints a message to say that the MemberRole object was created
$('#roleExistsMemberForm').load(document.URL + ' #roleExistsMemberForm'); //Refreshes the dropdown box so that the newly created MemberRole can be selected
}
});
}
</script>
Views
def add_role(request):
model_url = 'role-add'
new_role = request.POST.get("rolename","")
role_list = MemberRole.objects.all()
response_data= {}
if new_role:
x = MemberRole()
x.name = new_role
x.save()
response_data['message'] = new_role + " was created"
else:
response_data['message'] = 'Nothing created'
return HttpResponse(json.dumps(response_data),content_type="application/json")
def add_member(request):
model_url = 'member-add'
if request.method == "POST":
mform = MemberForm(request.POST, instance=Member())
if mform.is_valid():
new_member = mform.save(commit=False)
new_member.save()
return HttpResponseRedirect('members')
else:
mform = MemberForm(instance=Member())
return render_to_response('create_model.html', {'member_form': mform, 'model_url': model_url,},context_instance=RequestContext(request))
create_model.html
{% for field in member_form %}
{% if field.label == 'Role' %}
<div id="roleExistsMemberForm">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% else %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
</div>
{% endif %}
{% endfor %}
<div id="addRoleOnMemberForm">
<form onsubmit="return false;">
{% csrf_token %}
<input id= "role_name" type="text"/>
<input id="addrolebut" type="button" onclick = "createit()" value="Add New Role"/>
</div>
<div id="output">
<p>Nothing here</p>
</div>
my new.html.twig code is given below. How do I clear the form fields after the form submission?
{% extends '::base.html.twig' %}
{% block body -%}
<h1>Proposals creation</h1>
<form action="{{ path('proposals_create') }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form) }}
<p>
<button type="submit">Create</button>
</p>
</form>
<ul class="record_actions">
<li>
<a href="{{ path('proposals') }}">
Back to the list
</a>
</li>
</ul>
<div id="result"></div>
{% endblock %}
{% block javascripts %}
<script src="{{ asset('js/jquery-1.10.2.js') }}" type="text/javascript"></script>
<script type="text/javascript">
$().ready(function() {
$("form").submit(function(e) {
e.preventDefault();
var $url = $(this).attr('action');
var $data = $(this).serialize();
$.ajax({
type: "POST",
url: $url,
data: $data
}).done(function( result ) {
if(result.success) {
$('#result').html('<span>Monetary expense correctly saved!<br/> The data are:<br/>id: '+ result.id +'<br/>descrition: '+ result.description +'<br/>proposalname: '+ result.proposalname +'<br/>status: '+ result.status +'</span>');
}
});
});
});
</script>
{% endblock %}
Use HTMLFormElement.reset() to revert all <form> fields to their defaults.
$("form").submit(function(e) {
e.preventDefault();
var $url = $(this).attr('action');
var $data = $(this).serialize();
$.ajax({
type: "POST",
url: $url,
data: $data
}).done(function( result ) {
if(result.success) {
$('#result').html('<span> ... </span>');
}
});
this.reset(); // formElement.reset()
});
reset() resets the form to its initial state. This method does the same thing as clicking the form's reset button. If a form control (such as a reset button) has a name or id of reset it will mask the form's reset method.