My textarea input is not be empty after send message using Vue - laravel-5

I am using laravel and Vue. I have created a messenger application. Everything is done. But I am facing a problem. That is, after press enter button, message goes to the desired person. But the message still be available in the input filed until I refresh the page.
Here is my html code.
<input type="hidden" v-model="conID">
<textarea class="col-md-12 form-control" v-model="msgFrom" #keydown="inputHandler"
style="margin-top: 15px;border: none; resize: none;"></textarea>
Here is my Vue code.
inputHandler(e){
if(e.keyCode === 13 && !e.shiftkey){
e.preventDefault();
this.sendMsg();
}
},
sendMsg()
{
if(this.msgFrom){
axios.post('http://localhost:8000/sendMessage',{
conID:this.conID,
msg:this.msgFrom
})
.then(function(response){
console.log(response.data);
if(response.status===200){
app.singleMsgs = response.data;
}
})
.catch(function (error){
console.log(error);
});
}
Can anyone please help me. Just how I can make textarea empty after sending a message.
Thank's in advance.

should be as easy as clearing it once the message is sent
clear the form with: this.msgFrom = '', because you're doing it within a promise function (and without an arrow function), you need to store the this scope and pass it; usually done using var self = this
example:
inputHandler(e) {
if (e.keyCode === 13 && !e.shiftkey) {
e.preventDefault();
this.sendMsg();
}
},
sendMsg() {
var self = this; // <--- store scope 'this'
if (this.msgFrom) {
axios.post('http://localhost:8000/sendMessage', {
conID: this.conID,
msg: this.msgFrom
})
.then(function(response) {
console.log(response.data);
if (response.status === 200) {
app.singleMsgs = response.data;
self.msgFrom = ''; // <--- and then clear form
}
})
.catch(function(error) {
console.log(error);
});
}
}

Related

Showing data after hard refresh

im working with vue & laravel.i have a edit profile page with some forms in it(name,email,...)
the default value of this form not showing for the first time, but if user refresh the page everything will be work!!!
<template>
<label>Name:</label>
<input type="text" v-model="name">
<label>Email:</label>
<input type="email" v-model="email">
<template>
<script>
export default {
data () {
return {
name:'',
email:'',
}
},
mounted : function(){
this.getVueItems();
},
methods: {
getVueItems: function(){
axios.get('./api/auth/me').then(response => {
var vm = this;
vm.name = response.data.name;
vm.email = response.data.email;
});
},
getAuthUser () {
this.user = this.$store.getters.currentUser
},
updateAuthUser () {
this.submiting = true,
axios.put('./api/auth/update', {
name:this.name,
email:this.email,
})
.then(response => {
// this.submiting = false;
location.reload(true);
// success();
})
.catch(error => {
this.submiting = false;
})
},
}
}
</script>
whats is the problem?
As you are using arrow function this keyword is already accessible inside the function.
And for this you should first check in console if you are getting proper response value from api in console.
Hence change your function as below and check once.
async getVueItems() {
await axios.get('./api/auth/me').then(response => {
console.log(response);
this.name = response.data.name;
this.email = response.data.email;
});

Laravel returned error not shown in front-end

I have something like this in a Laravel API for one of the routes:
return response()->json(['message' => "Couldn't Price the car"], 500);
In the front-end, I have
try {
let data = await Axios.get("blax", {});
} catch(err) {
console.log(err.message);
}
err.message just shows default message:
request failed with status code 500
instead of showing:
Couldn't Price the car
How do I show my custom message?
try using err.response.message
try{
let data = await Axios.get("blax", {});
}catch(err){
console.log(err.response.message);
}
It seems to me that it catches perfectly:
new Vue({
el: "#demo",
data: {
response: null,
},
async created() {
try {
let data = await axios.get("https://httpstat.us/500", {});
} catch (err) {
console.log('ss', err.message);
this.response = err.message;
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<div id="demo">
Error: {{response}}
</div>
If you want to minimize your code, you can do .catch directly on the axios call, like so:
let data = axios.get("https://httpstat.us/500", {}).catch(e => e.message);
This catch also uses arrow function stripped down to the minimal. Here is an example of the same arrow function, just "normal":
let data = axios.get("https://httpstat.us/500", {}).catch((e) => {return e.message});
new Vue({
el: "#demo",
data: {
response: null,
},
async created() {
this.response = await axios.get("https://httpstat.us/500", {}).catch(e => e.message);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.0/axios.min.js"></script>
<div id="demo">
Error: {{response}}
</div>
Updated
responseJSON is not defined it's just response
try this the console.log(err.response.message) as following:
try{
let data = await Axios.get("blax", {});
}catch(err){
console.log(err.response.message);
}

jquery deferred with async calls

Please find the below code snippet:
HTML:
<div>
<span> First Name : <input type="text" id="firstName" name="First Name"/></span>
</div>
<br/>
<div>
<span>Student Id: <input type="text" id="studentId" name="studentId"/></span>
<span>Teacher Id: <input type="text" id="teacherId" name="teacherId"/></span>
</div>
<br/>
<div>
<span>Student Name : <input type="text" id="stdLastName" name="stdLastName"/></span>
<span>Student Age :<input type="text" id="stdAge" name="stdAge"/></span>
</div>
<br/>
<div>
<span>Teacher Name : <input type="text" id="tchrLastName" name="tchrLastName"/></span>
<span>Teacher Age : <input type="text" id="tchrAge" name="tchrAge"/></span>
</div>
<br/>
<input type="button" value="Submit" id="submit"/>
Javascript:
$('#firstName').focus();
var d1= new $.Deferred();
$('#firstName').blur(populatePage());
//called on blur of first name
function populatePage() {
$.when(populateStdDetails(),populateTchrDetails()).done(function(resp1, resp2){
$('#stdLastName').val(resp1[0].stdName);
$('#stdAge').val(resp1[0].age);
$('#tchrLastName').val(resp2[0].stdName);
$('#tchrAge').val(resp2[0].age);
console.log('All details populated....');
d1.resolve();
});
return d1;
}
//first ajax call
function populateStdDetails() {
if($('#firstName').val() != '' && $('#studentId').val() !='') {
return $.ajax({
url : '/someURL?studentId='+studentId+'&firstName='+firstName,
type :'GET',
contentType:'json'
});
}
}
//second ajax call
function populateTchrDetails() {
if($('#firstName').val() != '' && $('#teacherId').val() !='') {
return $.ajax({
url : '/someURL?teacherId='+teacherId+'&firstName='+firstName,
type :'GET',
contentType:'json'
});
}
}
$('#submit').click(function(e){
//wait for the ajax calls to be completed
$.when(populatePage()).done(function(e){
console.log('All done !!!!');
//Move to next page;
});
});
The First Name text field has an onblur event attached which works fine in usual scenario but when the focus is on "First Name" and "Submit" is clicked, the submit function is called instead of waiting for the onblur event to be completed.
You have placed deferred.resolve in wrong places in your timeout functions. Do it like this way:
function doSomething(deffered) {
$('#log').append('doSomething');
deferred.resolve();
return deferred;
};
function ajaxRequests1(deferred) {
setTimeout(function(){
$('#log').append('......ajaxRequests1');
deferred.resolve();
}, 1000);
return deferred;
};
function ajaxRequests2(deferred) {
setTimeout(function(){
$('#log').append('.....ajaxRequests2');
deferred.resolve();
}, 5000);
return deferred;
};
var func1 = function () {
var promise = new $.Deferred();
ajaxRequests1(promise);
return promise;
}
var func2 = function () {
var promise = new $.Deferred();
ajaxRequests2(promise);
return promise;
}
var stepFinal = function() {
var promise = new $.Deferred();
doSomething(promise);
return promise;
}
$.when(func1().promise(), func2().promise())
.done(function () {
stepFinal().done();
});
OK, if you want populatePage() to be called when focus leaves #firstname, and if the user also clicked on the submit button and you want the submit operation to wait for that blur action to finish, you can do this:
$('#firstName').blur(function(e) {
// call populatePage and set the resulting promise as a data item so
// the submit handler can get access to it
var self = $(this);
var p = populatePage();
self.data("blurPromise", p);
// when this promise is done, clear the blurPromise
p.always(function() {
self.removeData("blurPromise");
});
});
//called on blur of first name
function populatePage() {
return $.when(populateStdDetails(),populateTchrDetails()).done(function(resp1, resp2){
$('#stdLastName').val(resp1[0].stdName);
$('#stdAge').val(resp1[0].age);
$('#tchrLastName').val(resp2[0].stdName);
$('#tchrAge').val(resp2[0].age);
console.log('All details populated....');
});
}
//first ajax call
function populateStdDetails() {
if($('#firstName').val() != '' && $('#studentId').val() !='') {
return $.ajax({
url : '/someURL?studentId='+studentId+'&firstName='+firstName,
type :'GET',
contentType:'json'
});
} else {
// just return already resolved promise
return $.when();
}
}
//second ajax call
function populateTchrDetails() {
if($('#firstName').val() != '' && $('#teacherId').val() !='') {
return $.ajax({
url : '/someURL?teacherId='+teacherId+'&firstName='+firstName,
type :'GET',
contentType:'json'
});
} else {
return $.when();
}
}
$('#submit').click(function(e){
// get blur promise or dummy resolved promise
var p = $("#firstName").data("blurPromise") || $.when();
p.then(function() {
// do your submit logic here
// The onBlur handler is done now
});
});
Things I've updated in your promise handling code:
Use the $.ajax() promises directly without wrapping them in yet another promise.
Use the $.when() promises directly without wrapping them in yet another promise.
When using an if statement to decide whether or not to execute an asynchronous operation, it is usually best to also return a promise in the else arm so your function consistently always returns a promise. If there's nothing else to do in the else clause, then a shortcut for returning an already resolved promise in jQuery is to just return $.when();.
Be warned that .done() is jQuery-specific and not standard promise behavior. If you're already on jQuery 3.x or higher, then you should probably switch to .then() and then your promises will behave like the promise standard.

wait for a job finished to render component in vuejs

I have a component here, and I need first to make a request using socket.io :
<template>
<h1>Don't show me before the socket's response</h1>
</template>
<script>
export default {
beforeCreate: function() {
let sessid = this.$cookie.get('sessid')
this.$options.sockets.logout = (data) => {
if (data.redirect) {
this.$router.push(data.redirect)
} else {
console.log('here, you can render the template')
}
}
this.$socket.emit('logout', { sessid })
}
}
</script>
This code works, but it shows the template in browser for a quick moment, before the redirection happens.
I would like to know if there's a tick to wait the socket response for rendering the template.
You can use v-if, when the socket response arrives, you can set a variable which can be used with v-if to not show the HTML, something like following:
<template>
<h1 v-if="sockResp">Don't show me before the socket's response</h1>
</template>
<script>
export default {
data: function() {
return {
sockResp: false
}
},
beforeCreate: function() {
let sessid = this.$cookie.get('sessid')
this.$options.sockets.logout = (data) => {
if (data.redirect) {
this.$router.push(data.redirect)
} else {
console.log('here, you can render the template')
this.sockResp = true
}
}
this.$socket.emit('logout', { sessid })
}
}
</script>

react-flux application error - unable to find the function even if it's defined

I have a react component - coursePage.js
function getCourseInitState(){
return {
courses: CourseStore.getAllCourses()//courseStore is required in script
};
}
var Courses = React.createClass({
getInitialState: function(){
return getCourseInitState();
},
render: function () {
return (
<div>
<h1> Course </h1>
<CourseList courses={this.state.courses} />
</div>
);
}
});
Action file -courseAction
var CourseAction = {
CourseList: function(){
var courseList = CourseApi.getAllCourses();
Dispatcher.dispatch({
actionType: ActionTypes.COURSE_INITIALIZE,
courseList: courseList
});
}
Store File - courseStore
var CourseStore = assign({}, EventEmitter.prototype, {
addChangeListener: function(callback){
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback){
this.removeListener(CHANGE_EVENT, callback);
},
emitChange: function(){
this.emit(CHANGE_EVENT);
},
getAllcourses: function(){ //here is the function define
return _courses;
},
getCourseById: function(id){
return _.find(_courses, {id: id});
}
});
Dispatcher.register(function(action){
switch(action.actionType){
case ActionTypes.COURSE_INITIALIZE:
_courses = action.CourseList;
CourseStore.emitChange();
break;
}
});
module.exports = CourseStore;
in console I am getting "Uncaught TypeError: CourseStore.getAllCourses is not a function"
I don't want to call api directly in my coursePage.js so I find this way of initialising the page but it is not working.
(Please note - I am new to this) As per my recent learning Action file must always call API and send the request to State. I can load with help of componentWillMount function. But, I wanted to solve with this.If not wrong, then it is more neat and preferable way of implementing?
You have a typo -> getAllcourses in the Store and in the Component you call getAllCourses
getAllCourses: function(){ //Should be getAllCourses instead of getAllcourses
return _courses;
},

Resources