AlpineJS and WebSocket: Alpine Expression Error - websocket

I'm unable to send JSON data. Here is the code:
<div
x-data="{
socket:'',
initSocket() {
var wsHero = new WebSocket('ws://' +
window.location.host +
'/ws/api/section/'
);
wsHero.onmessage = function(e) {
console.log(e);
};
this.socket = wsHero;
this.retrieveHero();
},
retrieveHero() {
const data = {'action': 'retrieve','pk': '{{ pk }}', 'parameters': {'receive': true, 'send': false} }
this.socket.send(data);
console.log('Done...');
}
}"
x-init="initSocket()">
</div>
Alpine doesn't seem to like the data variable:
Alpine Expression Error: An attempt was made to use an object that is not, or is no longer, usable
I've checked the JSON syntax but nothing does it.

Related

Marker variable is undefined after get in Axios, VUE JS + LEAFLET + Axios

The Axios response.data is okay. But when I use the markers variable in rendering the markers is undefined. I am a newbie and badly need your help for our project.
I am trying to render the markers from the link described in the code, but some I placed the axios request in the created, and in the mounted is the rendering of the leaflet map.
Screenshot of the code
<script>
/** Script Vue JS **/
new Vue({
el: '#view-map',
data: {
map,
map_link:'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
markerOption: {
clickable: true,
draggable: false
},
mapOptions: {
center: [7.3087, 125.6841],
zoom:8
},
markers:[], //[{"image":"GMS-4-0112018-467_1527086274.jpg","derivation_code":"GMS-4-0112018-467","sample_description":"test 1 test is a test that test will be tested in test","latitude":"6.428152","longitude":"125.317857"},{"image":"GMS-1-0112018-963_1527134301.jpg","derivation_code":"GMS-1-0112018-963","sample_description":"nalaya lang","latitude":"7.311647","longitude":"125.636461"}],
selectedSample: [],
},
methods: {
getMarkers: function (){
axios.get('http://127.0.0.1:8000/marker').then(response => {
this.markers = response.data;
}).catch(error =>( console.log(error) ));
},
renderMarker: function(){
for ( i = 0; i < this.markers.length; i++){
console.log(this.markers[i]);
var marker = new L.Marker([this.markers[i].latitude, this.markers[i].longitude], this.markerOption);
marker.addTo(this.map);
marker.bindPopup(`
<h6 class="display-6">${this.markers[i].derivation_code}</h6>
<img src="storage/images/${this.markers[i].image}" style="height:100%;width:100%">
`);
}
},
markerClicked: function(mrkr_data){
this.selectedSample = mrkr_data.derivation_code;
console.log(this.selectedSample);
}
},
created: function(){
this.getMarkers();
},
mounted: function(){
this.map = new L.map('map', this.mapOptions);
this.map.addLayer(new L.TileLayer(this.map_link));
console.log(this.markers);
this.renderMarker();
}
});
</script>
I solved my problem. I treated the fetching of data in Axios get property as a Synchronous but it is an Asynchronous. Base in my previous code, I accessed the data when it is not updated so the value is blank.
/** Script Vue JS **/
new Vue({
el: '#view-map',
data: {
map,
map_link:'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
markerOption: {
clickable: true,
draggable: false
},
mapOptions: {
center: [7.3087, 125.6841],
zoom:8
},
markers:[], //[{"image":"GMS-4-0112018-467_1527086274.jpg","derivation_code":"GMS-4-0112018-467","sample_description":"test 1 test is a test that test will be tested in test","latitude":"6.428152","longitude":"125.317857"},{"image":"GMS-1-0112018-963_1527134301.jpg","derivation_code":"GMS-1-0112018-963","sample_description":"nalaya lang","latitude":"7.311647","longitude":"125.636461"}],
selectedSample: [],
},
created: function(){
this.getMarkers();
},
mounted: function(){
this.map = new L.map('map', this.mapOptions);
this.map.addLayer(new L.TileLayer(this.map_link));
},
watch: {
markers: function(){
this.renderMarker();
}
},
methods: {
getMarkers: function (){
axios.get('http://127.0.0.1:8000/marker').then(response => {
this.markers = response.data;
console.log(this.markers);
}).catch(error =>( console.log(error) ));
console.log(this.markers);
},
renderMarker: function(){
for ( i = 0; i < this.markers.length; i++){
console.log(this.markers[i]);
var marker = new L.Marker([this.markers[i].latitude, this.markers[i].longitude], this.markerOption);
marker.addTo(this.map);
marker.bindPopup(`
<h6 class="display-6">${this.markers[i].derivation_code}</h6>
<img src="storage/images/${this.markers[i].image}" style="height:100%;width:100%">
`);
}
},
markerClicked: function(mrkr_data){
this.selectedSample = mrkr_data.derivation_code;
console.log(this.selectedSample);
}
},
});

Using Select2 autocomplete with Django project does not work while fetching the data

In my Django project, I have a Search field. I used Select2 autocomplete with it. I needed to fetch the product_list from my Product model. So I created a rest API that returns the product in json formats.
Here is my rest API code:
serializer.py:
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = ProductList
fields = ('product_id', 'product_name', 'product_image', 'product_available',
'product_description')
views.py:
class JSONResponse(HttpResponse):
def __init__(self, data, **kwargs):
content = JSONRenderer().render(data)
kwargs['content_type'] = 'application/json'
super(JSONResponse, self).__init__(content, **kwargs)
def list(request):
if request.method == 'GET':
products = ProductList.objects.filter(product_name__icontains=request.GET.get('q'))
serializer = ProductSerializer(products, many=True)
serializer_data = serializer.data
customData = {'results': serializer_data}
return JSONResponse(customData)
Now in my html, in the javascript portion I used this code mentioned in this Select2 doc. The code I used, looks like this:
base.html:
<script type="text/javascript">
$(document).ready(function() {
$('.js-data-example-ajax').select2({
ajax: {
url: "/api.alif-marine.com/search/products",
dataType: 'json',
delay: 250,
type: 'GET',
data: function (params) {
return{
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.results,
};
},
cache: true
},
placeholder: 'Search for a product',
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo (repo) {
if (repo.loading) {
return repo.text;
}
var markup = "<div class='select2-result-repository clearfix'>" +
{# "<div class='select2-result-repository__avatar'><img src='" + repo.owner.avatar_url + "' /></div>" +#}
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + repo.product_name + "</div>";
if (repo.product_description) {
markup += "<div class='select2-result-repository__description'>" + repo.product_description + "</div>";
}
return markup;
}
function formatRepoSelection (repo) {
return repo.product_name || repo.text;
}
});
</script>
When I used Postman to check if the rest API works or not, it worked perfectly. For my query in the Postman like these:
localhost:8000/api.alif-marine.com/search/products?q=t
or
localhost:8000/api.alif-marine.com/search/products?q=tho
or
localhost:8000/api.alif-marine.com/search/products?q=thomas
The retrieved json data is given below for query localhost:8000/api.alif-marine.com/search/products?q=t :
{
"results":[
{
"product_id":9,
"product_name":"thomas",
"product_image":"/media/media/tom_dushtu.jpg",
"product_available":"available",
"product_description":"jah dushtu"
},
{
"product_id":8,
"product_name":"ami dissapointed",
"product_image":"/media/media/dissapointment.jpg",
"product_available":"available",
"product_description":"I ma kinda dissapointed, you know.................."
}
]
}
Now with all those, I couldn't make it work. The autocomplete is not working. Nothing is shown when I press one key or write the name of the whole product.
. It always has shown Searching.... I tried reading the issues on the Github repo and some other things but couldn't solve it.
What am I doing wrong?
This is how the select2 library is handled:
views.py:
class BurdenTypeAutocomplete(autocomplete.Select2QuerySetView):
def get_result_label(self, obj):
return format_html(" {} / {}", obj.arabic_name,obj.englsh_name)
def get_queryset(self):
qs = BurdenTypeSales.objects.filter(effect_type="2")
if self.q:
qs = qs.filter(
Q(arabic_name__icontains=self.q)
| Q(account__number__icontains=self.q)
| Q(englsh_name__icontains=self.q)
)
return qs[:10]
Url.py:
url(r'^burden_type_autocomplete/$',views.BurdenTypeAutocomplete.as_view(),name='burden_type_autocomplete'),
form.py:
burden_type_sales = forms.ModelChoiceField(queryset=BurdenTypeSales.objects.filter(effect_type='2'),
widget=autocomplete.ModelSelect2(url='burden_type_autocomplete',attrs={'required':'required'}))

How to set image src as a string in vue component?

I've created two components to send an image in base-64 encoded format to a server. When the parent component is mounted it's supposed to set the child reference to file.
Vue.component('some-form', {
template: '#some-form',
data: function() {
return {
logoImage: '',
coverImage: ''
}
},
methods: {
onSubmit: function(event) {
var dataForm = {};
var that = this;
dataForm['logo-image'] = this.logoImage;
dataForm['cover-image'] = this.coverImage;
// AJAX REQUEST HERE with posting data
},
},
mounted: function(){
var $this = this;
// AJAX REQUEST HERE with getting data
}
});
Vue.component('upload-photo', {
template: '#upload-photo',
data: function () {
return {
image: {
body: '',
'content-type': '',
'content-length': '',
url: ''
},
imageBody: ''
}
},
props: ['logoImage', 'title', 'description'],
watch: {
'image': function() {
this.$emit('input', this.image);
}
},
created: function(){
this.image = this.logoImage;
},
mounted: function () {
var that = this;
//AJAX REQUEST HERE to get data
},
methods: {
onFileChange: function(e) {
var files = e.target.files || e.dataTransfer.files;
if (!files.length)
return;
this.createImage(files[0]);
},
createImage: function(file){
var image = new Image();
var reader = new FileReader();
var vm = this;
vm.image = {};
reader.onload = function(e) {
vm.image.body = e.target.result;
vm.imageBody = e.target.result;
};
vm.$set(vm.image, 'content-type', file.type);
vm.$set(vm.image, 'content-length', file.size);
reader.readAsDataURL(file);
},
removeImage: function (e) {
this.image = '';
}
}
});
var app = new Vue({
el: '#app',
data: function() {
},
methods: {
},
mounted: function() {
}
});
Full example https://codepen.io/anon/pen/ZvzwzO
How can it be implemented?
P.S. I have no idea how to implement it in the same component. I send data as a string with two more property, however get as a string to, however it's link.
P.S.S. need just way to search.
It is difficult to tell exactly what you are asking but it sounds like you want to pass data from the parent component to the child. If you haven't already, read about Composing components and Dynamic Props for passing properties from a parent component to a child component.
One way to do this is to make the imageBody a property of the upload-photo component instead of part of the data.
props: ['logoImage', 'title', 'description', 'imageBody'],
Then have the parent supply a value for that property:
<upload-photo v-model="logoImage" title="TITLE 1" description="description_1" v-bind:image-body="imageBody">
Take a look at this phpfiddle. When the form is mounted, it sends an AJAX call back to the server to retrieve a URL, then sets the property on that first upload-photo child element to the URL sent back from the server in the AJAX response. Note that the upload-photo template was changed to show the image if imageBody is truthy instead of image.

react prevent children render ( ajax loader waiting for response )

Im trying to write simple ajax loader and I wondering that i can prevent props.children render in parent container. The problem is that children want to render, no matter that Loader want to show it or not, and if render is based on ajax data that cousing errors.
Example: https://jsfiddle.net/j8dvsq39/
Example2:
This example will produce error couse this.state.data.user is undefined before ajax request.
Loader:
import React from 'react'
export default React.createClass({
getDefaultProps() {
return { text: "Loading", loaded: false };
},
render() {
if(this.props.loaded == false)
return <div>{this.props.text}</div>;
else
return <div>{this.props.children}</div>;
}
})
Class using Loader
import React from 'react'
import Loader from '../helpers/Loader';
import {comm} from '../Comm';
export default React.createClass({
getInitialState() {
return {loaded: false, data: null};
},
componentWillMount(){
comm.get("/xxx/xxx", {json: 1}, (back) => {
console.log(back);
this.setState({loaded: true, data: back});
});
},
render(){
return <Loader loaded={this.state.loaded}>{this.state.data.user.name}</Loader>
});
Reason is, initially you defined data=null and before the ajax call you are using this.state.data.user.name, it will throw the error:
Cannot read property 'name' of undefined
Simple solution is you need to put the check on data until you didn't get the ajax response, Check this:
var Loader = React.createClass({
getDefaultProps() {
return { text: "Loading", loaded: false };
},
render() {
if(this.props.loaded == false)
return <div>{this.props.text}</div>;
else
return <div>{this.props.children}</div>;
}
});
var Hello = React.createClass({
getInitialState() {
return {loaded: false, data: null};
},
componentWillMount(){
setTimeout(()=>{
this.setState({loaded: true, data: {user:{name: "login"}}});
}, 1000);
},
render: function() {
var user = null;
return <Loader loaded={this.state.loaded}>
<div>
Hello {this.state.data ? this.state.data.user.name : null}
</div>
</Loader>;
}
});
ReactDOM.render(
<Hello name="World" />,
document.getElementById('container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='container'/>

Removing a subdoc using AJAX & Mongoose

How do you properly delete a subdoc (a task in this case) with AJAX in Mongoose?
Everything seems to be working up until the ajax in the file that's loaded into the page. Or could the problem be in the controller? I have read that you can't perform a .remove on a child element and I'm unclear on how to handle a delete.
Here is the schema:
//new user model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
// Task schema
var taskSchema = mongoose.Schema({
clientEasyTask : { type: String },
clientHardTask : { type: String },
clientStupidTask : { type: String }
});
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true },
password: String,
task : [taskSchema]
});
module.exports = mongoose.model('Task', taskSchema);
module.exports = mongoose.model('User', userSchema);
The JS loaded into the page:
// Delete
$(document).ready(function() {
console.log('called del function');
var $alert = $('.alert');
$alert.hide();
$alert.on('error', function(event, data){
$alert.html(data)
$alert.addClass('alert-danger');
$alert.show();
});
$alert.on('success', function(event, data) {
$alert.html(data);
$alert.addClass('alert-info');
$alert.show();
})
$('.task-delete').click(function(event) {
console.log('click event occurred');
$target = $(event.target)
$.ajax({
type: 'DELETE',
url: apiDeleteTask + $target.attr('data-task-id'),
success: function(response) {
$target.parent.children.id(id).remove();
$alert.trigger('success', 'Task was removed.');
},
error: function(error) {
$alert.trigger('error', error);
}
})
});
})
Routes, which matches the working update route:
var tasks = require('./controllers/tasks-controller'),
var User = require('./models/user');
var Task = require('./models/user');
module.exports = function (app, passport) {
// Delete Task
app.delete('/api/tasks/:id', tasks.del);
};
And the tasks-controller.js
var User = require('../models/user');
var Task = require('../models/user');
exports.del = function(req, res, next) {
return User.update({ 'task._id': req.params.id }, { $set: { 'task.$.clientEasyTask': req.body.clientEasyTask }},
(function(err, user) {
if(!user) {
res.statusCode = 404;
return res.send({ error: 'Not phound' });
}
if(!err) {
console.log("Updated Existing Task with ID: " + req.params.id + " to read: " + req.body.clientEasyTask ),
res.redirect('/dashboard');
} else {
res.statusCode = 500;
console.log('Internal error(%d): %s', res.statusCode, err.message);
return res.send({ error: 'Server error' });
}
})
);
};
And last but not least I'm getting this error, that gives the task_id string & line 0:
[Error] Failed to load resource: the server responded with a status of 404 (Not Found) (54c55ac0443873db1eb8c00c, line 0)
In order to remove an entire field from the child array (tasks) the solution is to use $unset. I was wanting to use $set to update the field with a null value, but this is exactly what $unset does.
Here is the line in question that now works:
return User.update({ 'task._id': req.params.id }, { $unset: { 'task.$.clientEasyTask': req.body.clientEasyTask }},
Read more about field operators here: http://docs.mongodb.org/manual/reference/operator/update-field/
$pull would work if you want to remove the array elements without leaving behind a null value, but you must have a specific, matching query. Read about $pull and other array update options here:
http://docs.mongodb.org/manual/reference/operator/update-array/
Also, if you are struggling with a problem I can't stress how important it is to read the documentation. I can guarantee you that everyone on here that is answering problems is doing this, or has learned from someone who does.
Do the work. You'll figure it out. Don't give up.

Resources