How to use AJAX function in Total js? - total.js

I have a User form and I am trying to do a POST. Earlier code with schemas work. I am fitting in AJAX just now and I dont have a clue why it is not working. There is no error.
Below is code snippet from users.html file
</div>
<div class="btn" role="group">
<button type="button" name="submit" id="Submit" class="btn btn-primary" onclick="onSubmit()">Submit</button>
</div>
<div class="btn" role="group">
<input class="btn btn-warning" type="reset" value="Reset">
</div>
</form>
<script type="text/javascript">
function onSubmit() {
console.log("Ajax Testing");
AJAX('POST /users', function (value, err, response) {
if (err) { throw err };
console.log(value);
console.log(response);
});
};
</script>
Here is the routing part from default.js file
exports.install = function () {
ROUTE('GET /', displayHome);
ROUTE('GET /{userId} *userSchema --> #query');
ROUTE('GET /homepage', displayHome);
ROUTE('POST /users *userSchema --> #insert');
Below is the schema for Insert operation
schema.setInsert(function ($) {
var userDB = DATABASE('users');
userObj = {
name: $.controller.body.name,
age: $.controller.body.age,
height: $.controller.body.height,
email: $.controller.body.email,
gender: $.controller.body.gender,
cities: $.controller.body.cities,
landline: $.controller.body.telephone,
about: $.controller.body.aboutMe
};
userDB.insertOne(userObj, function (err, result) {
if (err) throw err;
console.log("Created New user using Schema Definition" + result);
$.controller.view('homepage');
}.bind($.controller));
});
Can you please let me know what is the error?

You forgot to send a data:
AJAX('POST /users/', YOUR_DATA, function (value) {
console.log(value);
});
BTW: the code is not good in your schema. You need to work with fields defined in the schema and then everything is much simpler:
schema.setInsert(function ($) {
DB('users').insertOne($.clean(), $.callback);
});
Learn from examples:
https://github.com/totaljs/emptyproject-jcomponent/
https://github.com/totaljs/emptyproject-restservice/
https://github.com/totaljs/examples/

Related

Why my page gets refresh while deleting image on 'product edit page'?

VIEW FILE
<div class="col-sm-4">
<label>Other Images</label>
<div class="input-group control-group img_div form-group" >
<input type="file" name="image[]" class="form-control">
<div class="input-group-btn">
<button class="btn btn-success btn-add-more" type="button">Add</button>
</div>
</div>
</div>
<div>#foreach($image as $image)
<p><img src="{{asset('/files/'.$image->images)}}" height="50px" id="{{$image->id}}" class="photo"/>
<button class="removeimg" data-id="{{$image->id}}" data-token="{{ csrf_token() }}">Remove</button></p>
#endforeach
</div>
AJAX
$(document).ready( function () {
$(document).on('click', '.removeimg',function(){
var confirmation = confirm("are you sure to remove this record?");
if (confirmation) {
var id = $(this).data("id");
// console.log(id)
var token = $(this).data("token");
var $obj = $(this);
$.ajax(
{
url: "{{ url('image/delete') }}/"+id,
type: 'post',
dataType: "JSON",
data: {
"id": id,
"_token": token,
},
success: function (res)
{
// $(this).parents('.photo').remove();
$obj.parents('.photo').remove();
console.log("it Work", res);
}
});
console.log("It failed");
}
});
});
CONTROLLER
public function imgdelete($id){
Image::find($id)->delete($id);
return response()->json([
'success'=> 'Image deleted successfully!'
]);
}
When I delete the image, page gets redirected to product listing. Page should not get refresh when I delete the image. Can you please help me with correction?? NOTE: This process takes place on editproduct page.
You can prevent the default event for the button:
$(document).on('click', '.removeimg',function(event){
event.preventDefault();
.....
});

"TypeError: Cannot read property 'title' of undefined" in form

An error is returned when I try to post the form.
The form is in a component, and the same structure is used in another component but does not generate any error.
I tried to find the mistake by myself but impossible to find the solution.
<template>
<div class="card" style="width: 18rem;margin:0 0 1rem 1rem;">
<div class="card-body">
<h4 class="mt-3 text-center" style="cursor:pointer;" #click="show=!show" >Add list</h4>
<form v-show="show" #submit.prevent="submitList">
<div class="form-group">
<label>Title</label>
<input type="text" class="form-control" :class="{'is-invalid':errors.title}" v-model="form.title"/>
<p class="text-danger" v-if="errors.title" v-text="errors.title[0]"></p>
</div>
<button type="submit" class="btn btn-lg btn-success mb-4">Submit</button>
</form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
show : false,
form: {
title: '',
},
errors: {}
}
},
methods: {
submitList() {
axios.post('/list', this.form)
.then(({data}) => {
this.$emit('newList', data),
this.form.title = '',
this.show = false,
this.errors = {}
})
.catch(error => {
this.errors = error.response.data.errors
})
}
}
}
</script>
Error in render: "TypeError: Cannot read property 'title' of undefined"
Reference this at the start of the method submitList and then use the reference in the axios response.
let that = this;
then that.form.title;
submitList () {
let that = this;
axios.post('/list', this.form)
.then(({ data }) => {
that.$emit('newList', data),
that.form.title = '',
that.show = false,
that.errors = {}
})
.catch(error => {
that.errors = error.response.data.errors
})
}
There's not really enough information here to answer the question. Since it's a render issue my guess is that it's one of these lines:
<input type="text" class="form-control" :class="{'is-invalid':errors.title}" v-model="form.title"/>
<p class="text-danger" v-if="errors.title" v-text="errors.title[0]"></p>
The question is what you get from the backend in your catch method. You should probably log that value and check that it's formated the way you think it is.
A nice tool for debugging Vue is the browser extension, maybe it will help with clearing up the problem.
If this does not solve your problem you need to provide more info:
When does the error occur
What is the value of the data-properties when it occurs
Maybe a screenshot of a more thorough error-message

Ajax submit and replace submit button with checkmark after success

First, I'm not having luck with ajax submitting at all in cakephp 1.3 environment. Once I successfully submit, I'm hoping user stays on page and submit button hidden or replaced with a checkmark. I've tried a few things... controller without $action and then .click function instead of on submit. I'm also not versed in debugging js to see where it might be wrong so any suggestions are welcome.
Maybe "update_a" is the $action within my dashboard controller
"function applications($action) {" instead?
dashboard controller
function update_a($action) {
...
switch ($action) {
case 'save':
if (!empty($this->data)) {
// update fields in database table matching model
$this->data['Model']['submitted'] = $_POST['submitted'];
$this->data['Model']['locked'] = $_POST['locked'];
if ($this->Model->save($this->data)) {
// save form fields to other models
$this->OtherModel->saveField('form_status_id',$_POST['form_status_id']);
$this->OtherModel->saveField('form_status',$_POST['form_status']);
}
}
}
break;
default:
//$this->redirect("admin/index");
$this->render("dashboard/applications");
break;
} //case
} // end function
html
<body>
<form id='update_a' action='save'>
<div class='form-group'>
<input type='hidden' class='hidden' name='locked' id='locked' value='1'>
<input type='hidden' class='hidden' name='form_status' id='form_status' value='Locked'>
<input type='hidden' class='hidden' name='form_status_id' id='form_status_id' value='3'>
<input type='hidden' class='hidden' name='submitted' id='submitted' value='<?php echo date("Y-m-d G:i:s") ?>'>
</div>
<div class='text-center'>
<input name='submit' type='button' class='btn btn-default' value='Submit Form A'>
</div>
</form>
</body>
<script>
$(document).ready(function () {
$('#update_a').on('submit', function (e) {
//$('#update_a').click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/dashboard/update_a',
data: $('#update_a').serialize(),
success: function () {
alert('Form A has been submitted and locked for editing');
$('#update_a').hide();
},
error : function() {
alert("Error");
}
});
return false;
});
});
</script>

vue js how to instant search result empty

please see my code that I'am not sure what I'm doing wrong? when the search input is empty then it shows all data from db how to fix, vue lenght doesnt work??
var app = new Vue({
el: '#newsearch',
data: {
qry: '',
bUrl: 'http://localhost:8000',
results: [],
},
methods: {
autoComplete(){
this.results=[];
axios.post(this.bUrl + '/search', {
qry: this.qry
})
.then ( (response) => {
app.results = response.data;
})
}
}
});
html
<p class="control is-expanded has-icons-right">
<input class="input" v-model="qry" v-on:Keyup="autoComplete" type="text" placeholder=">.<"/>
</p>
<p class="control">
<a class="button is-dark">
<i class="fa fa-search"></i>
</a>
</p>
<div v-show="results.length">
<p v-for="result in results">
#{{result.anime_name}}
</p>
</div>
</div>
Send axios request only when qry isn't empty.
methods: {
autoComplete(){
this.results=[];
if(this.qry !== '') {
axios
.post(this.bUrl + '/search', {
qry: this.qry
})
.then ( (response) => {
app.results = response.data;
})
}
}
}

Meteor: Error: {{#each}} currently only accepts arrays, cursors or falsey values

I keep getting this error message when I click on the send button. Im trying to create a Instant Messenger app where online users can chat one on one. I am a beginner and I would really appreciate any help. Here is my error message, again it appears in the console once I click the Send button.
Exception from Tracker recompute function: meteor.js:862 Error:
{{#each}} currently only accepts arrays, cursors or falsey values.
at badSequenceError (observe-sequence.js:148)
at observe-sequence.js:113
at Object.Tracker.nonreactive (tracker.js:597)
at observe-sequence.js:90
at Tracker.Computation._compute (tracker.js:331)
at Tracker.Computation._recompute (tracker.js:350)
at Object.Tracker._runFlush (tracker.js:489)
at onGlobalMessage (meteor.js:347)
Here is my HTML
<template name="chat_page">
<h2>Type in the box below to send a message!</h2>
<div class="row">
<div class="col-md-12">
<div class="well well-lg">
{{#each messages}}
{{> chat_message}}
{{/each}}
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<form class="js-send-chat">
<input class="input" type="text" name="chat" placeholder="type a message here...">
<input type="submit" value="Send">
</form>
</div>
</div>
</template>
<!-- simple template that displays a message -->
<template name="chat_message">
<div class = "container">
<div class = "row">
<img src="/{{profile.avatar}}" class="avatar_img">
{{username}} said: {{text}}
</div>
</div>
<br>
</template>
Client Side
Template.chat_page.helpers({
messages: function () {
var chat = Chats.findOne({ _id: Session.get("chatId") });
return chat.messages;
},
other_user: function () {
return "";
}
});
Template.chat_page.events({
'submit .js-send-chat': function (event) {
console.log(event);
event.preventDefault();
var chat = Chats.findOne({ _id: Session.get("chatId") });
if (chat) {
var msgs = chat.messages;
if (! msgs) {
msgs = [];
}
msgs.push({ text: event.target.chat.value });
event.target.chat.value = "";
chat.messages = msgs;
Chats.update({ _id: chat._id }, { $set : { messages: chat } });
Meteor.call("sendMessage", chat);
}
}
});
Parts of the server side
Meteor.publish("chats", function () {
return Chats.find();
});
Meteor.publish("userStatus", function () {
return Meteor.users.find({ "status.online": true });
});
Meteor.publish("userData", function () {
if (this.userId) {
return Meteor.users.find({ _id: this.userId },{ fields: { 'other': 1, 'things': 1 } });
} else {
this.ready();
}
return Meteor.users.find({ "status.online": true });
});
Meteor.publish("users", function () {
return Meteor.users.find({ "status.online": true });
});
Chats.allow({
insert: function () { return true; },
update: function () { return true; },
remove: function () { return true; }
});
Meteor.methods({
sendMessage: function (chat) {
Chats.insert({
chat: chat,
createdAt: new Date(),
username: Meteor.user().profile.username,
avatar: Meteor.user().profile.avatar,
});
}
});
Chances are your subscriptions aren't ready. This means that Chats.findOne() will return nothing, meaning that Chats.findOne().messages will be undefined.
Try the following:
{{ #if Template.subscriptionsReady }}
{{#each messages}}
{{/each}}
{{/else}}
Alternatively, use a find() on chats, then {{#each}} on the messages within that chat. For example:
Template['Chat'].helpers({
chats: function () {
return Chats.find(Session.get('chatId')); // _id is unique, so this should only ever have one result.
}
});
Then in template:
{{#each chats}}
{{#each messages}}
{{>chat_message}}
{{/each}}
{{/each}}
I think there might be a logical error in this line
Chats.update({ _id : chat._id }, { $set : { messages : chat } });
You are setting the value of the field messages to chat. But chat is an object. So in your helper when you are returning Chats.findOne().messages to the {{#each}} block, you are actually returning an object which is not a valid value to be sent to an {{#each}} block and hence the error.
I think what you mean to do is
Chats.update({ _id : chat._id }, { $set : { messages : msgs } });

Resources