I dont see the issue with the setInterval - forms

In this code, I would like to clear the message after I successfully sent a message via the form I set up a setInterval but it does not work on the specified code but work when I try it in the console. log.
here is the code the component success-message have the message saying that the message has been sent successfully but won't update with the setInterval.
<template>
<success-message v-if="!successMessage" ></success-message>
<!-- <div v-show="successMessage"> -->
<form #submit.prevent="submitForm" >
<div class="form-control">
<label for='name'>Your Name</label>
<input type="name" id="name" v-model.trim="name"/>
</div>
<div class="form-control">
<label for='email'>Your email</label>
<input type="email" id="email" v-model.trim="email"/>
</div>
<div>
<label for='message'>Your message</label>
<textarea row="5" id="message" v-model.trim="message"></textarea>
</div>
<p class="errors" v-if="!formIsValid">Please you enter all requested informations.</p>
<div class="actions">
<button>Send Message</button>
</div>
</form>
<!-- </div> -->
</template>
<script>
export default {
data(){
return {
name: '',
email: '',
message: '',
successMessage: true,
formIsValid: true,
}
},
methods: {
submitForm(){
this.formIsValid = true;
if (this.name === '' || this.email === '' || !this.email.includes('#') || this.message === '') {
this.formIsValid = false;
return;
} else {
fetch("https://vue-http-demo-8aa03.firebaseio.com/stone.json", {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({name: this.name,
email: this.email,
message: this.message}),
}).then((data)=>{
if (data.status === 200) {
this.successMessage = false;
this.name ='';
this.email ='';
this.message ='';
setInterval(function(){ this.successMessage=true;}, 3000);
setInterval(function(){ console.log(this.successMessage=true);}, 3000);
}
});
}
},
},
}
</script>

If you want to access valid scope for this, you need to use arrow function for setInterval:
setInterval(() => {
this.successMessage = true;
}, 3000);

Related

Vue3: How to get error messages with Bootstrap and VeeValidate 4?

I want to use vue3 together with bootstrap 4/5 with veevalidate 4.
<template>
<Form as="form" #submit.prevent="onFormSubmit" class="needs-validation" :class="{ 'was-validated': wasValidated }">
<div class="form-group">
<label for="firstNameId">First Name *</label>
<Field name="firstname" as="input" id="firstNameId" type="text" rules="required|firstname" class="form-control" placeholder="First Name" v-model="firstName" aria-describedby="input-true input-false input-help" aria-invalid="true" />
<ErrorMessage as="div" name="firstname" v-slot="{ message }">
{{ message }}
<div class="invalid-feedback">
{{ message }}
</div>
</ErrorMessage>
<div class="valid-feedback">Good!</div>
</div>
<Form>
</template>
<script>
import { Field, Form, ErrorMessage, defineRule } from 'vee-validate';
defineRule('required', value => {
if (!value || !value.length) {
return 'This field is required.';
}
return true;
});
defineRule("firstname", (value) => {
if (!/^[a-zA-Z0-9( ),'.:/-]+$/i.test(value)) {
return "Please use only letters, numbers and the following special characters: ( ),'.:/-";
}
return true;
});
export default {
components: {
Form,
Field,
ErrorMessage
},
data () {
return {
firstName: "",
wasValidated: false,
},
methods: {
onFormSubmit(values) {
alert(JSON.stringify(values, null, 2));
console.log("Submitted");
console.log(values);
var forms = document.getElementsByClassName('needs-validation');
// Loop over them and prevent submission
var validation = Array.prototype.filter.call(forms, function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
this.wasValidated = true;
}, false);
});
},
},
};
</script>
The problem is that I can't activate the div with the class invalid-feedback or valid-feedback.
I could add the class was-validated to the <form>-tag, but I get feedback first after the second click on the submit button.
<template>
<Form as="form"
#submit="onFormSubmit"
class="needs-validation"
:validation-schema="schema"
v-slot="{ errors }"
>
<div class="form-group">
<label for="firstNameId">First Name *</label>
<Field
name="firstName"
type="text"
placeholder="First Name"
v-model="firstName"
aria-describedby="input-true input-false input-help"
aria-invalid="true"
v-slot="{ meta, field }"
>
<input
v-bind="field"
name="firstName"
type="text"
class="form-control"
:class="{
'is-valid': meta.valid && meta.touched,
'is-invalid': !meta.valid && meta.touched,
}"
/>
</Field>
<ErrorMessage as="div" name="firstname" v-slot="{ message }" class="invalid-feedback">
{{ message }}
</ErrorMessage>
<Form>
</template>
<script setup>
import { markRaw } from 'vue';
import { Field, Form, ErrorMessage} from 'vee-validate';
import * as yup from 'yup';
</script>
<script>
export default {
components: {
Form,
Field,
ErrorMessage
},
data () {
return {
schema: markRaw(yup.object().shape({
firstName: yup.string().min(0).max(20).label('First Name'),
})),
};
},
methods: {
onFormSubmit(values) {
console.log(JSON.stringify(values, null, 2));
},
},
};
</script>

Handlebars Form no run Mongodb delete function - typeError gfs.deleteOne

The form below sends images/files to Mongodb using the handlelebars (.hbs) engine and multer-gridfs-storage (Mongodb FIles), but by clicking delete it generates the following error:
TypeError: gfs.deleteOne is not a function
Also, it does not load the thumbnail of the attached photo
Ps: I think the error is in HBS form.
Full code :
https://github.com/rebek/upFileHBS
<form action="/upload" method="POST" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" name="file" id="file" class="custom-file-input">
<label for="file" class="custom-file-label">Choose File</label>
</div>
<input type="submit" value="Submit" class="btn btn-primary btn-block">
</form>
<hr>
{{#each files}}
<div class="card card-body mb-3">
{{#if file.isImage}}
<img src="image/{{this.filename}}" alt="">
{{else}}
{{this.filename}}
<form method="POST" action="/files/{{this._id}}?_method=DELETE">
<button class="btn btn-danger btn-block mt-4">Delete</button>
</form>
</div>
{{/if}}
{{/each}}
</div>
</div>
</div>
app.get('/', (req, res) => {
gfs.files.find().toArray((err, files) => {
// Check if files
if (!files || files.length === 0) {
res.render('index', { files: false });
} else {
files.map(file => {
if (
file.contentType === 'image/jpeg' ||
file.contentType === 'image/png'
) {
file.isImage = true;
} else {
file.isImage = false;
}
});
res.render('index', { files: files });
}
});
});
...
app.delete('/files/:id', (req, res) => {
gfs.deleteOne({ _id: req.params.id, root: 'uploads' }, (err, GridFSBucket) => {
if (err) {
return res.status(404).json({ err: err });
}
res.redirect('/');
});
});
gfs.files.deleteOne({ filename: req.params.filename}, (err) => {
if (err) return res.status(500).json({ success: false })
return res.json({ success: true });
})
using the above will delete the file

How to create mysql table entry on form submission in CodeIgniter

I just need to insert data to table on form submission with the entered inputs.
my Controller,
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$this->model_wishes->createWish($data);
}
model,
function createWish($data) {
$sql = "INSERT INTO wishes (user_name, user_email, user_wish) VALUES (".$data.user_name.", ".$data.user_email.", ".$data.user_message.")";
$this->db->query($sql);
echo $this->db->affected_rows();
}
view,
<form method="post" action="<?php echo base_url() . "index.php/Welcome/create_wish"?>">
<div class="row">
<div class="form-group col-md-6">
<label for="post-name">Name</label>
<input autocomplete='name' type="text" class="form-control" id="uname" name="uname" required />
</div>
<div class="form-group col-md-6">
<label for="post-email">Email</label>
<input autocomplete='email' type="email" class="form-control" id="uemail" name="uemail" required/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 margin-b-2">
<label for="post-message">Message</label>
<textarea class="form-control" id="umessage" rows="5" name="umessage"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 text-left mb-0">
<button id="btn-create" type="submit" class="button-medium btn btn-default fill-btn">Post Wish</button>
</div>
</div>
</form>
Ajax,
$(document).ready(function () {
$('form').submit(function (event) {
var formData = {
'user_name': $('input[name=uname]').val(),
'user_email': $('input[name=uemail]').val(),
'user_wish': $('input[name=umessage]').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost/CodeIgniterProj/index.php/create_wish',
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
execution of above codes displays an error in console
POST http://localhost/CodeIgniterProj/index.php/create_wish 404 (Not Found)
XHR failed loading: POST "http://localhost/CodeIgniterProj/sender.php".
I tried to fix this and failed. Someone please let me know how to fix this issue, help me on this.
Your URL is missing the controller segment
you should call index.php/[controller]/[method]. Regarding the sender.php i cannot see any call to it. Maybe there are other forms in the markup.
Besides that, the model will not work as expected. Since you are dealing with an array you should change:
... VALUES (".$data.user_name.", ...)
to
...(VALUES (".$data["user_name"].", ...)
If you don't want to use the active record class, you should escape the values in your query.
https://www.codeigniter.com/user_guide/database/queries.html#escaping-queries
I hope it helps.
Use site_url in your ajax url , should be like this
$(document).ready(function () {
$('form').submit(function (event) {
var formData = $(this).serialize();
alert(formData);
$.ajax({
type: 'POST',
url: '<?=site_url('Welcome/create_wish');?>',
data: formData,
dataType: 'json',
}).done(function (data) {
console.log(data.id);
});
event.preventDefault();
});
});
Your controller should be like this :
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$insert_id = $this->model_wishes->createWish($data);
if($insert_id)
{
$response = array('status' => 'success');
}
else
{
$response = array('status' => 'error');
}
echo json_encode($response);
exit;
}
Your model method createWish should be like this ;
function createWish($data)
{
$this->db->insert('wishes', $data);
return $this->db->insert_id();
}

PHPMailer and Ionic with Gmail

I'm attempting to create a contact form for my app using PHPMailer and Ionic with Gmail.
The page receives (Failed.) result message when it triggers the script but I never get the email from the form. Here is my code:
template.html
<label class="item item-input" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</label>
<div class="padding">
<button type="submit" class="btn btn-default" ng-disabled="submitButtonDisabled">Send Message</button>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
app.js
.controller('ContactCtrl', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage;
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
if (contactform.$valid) {
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param($scope.formData), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = 'Failed.';
$scope.result='bg-danger';
}
}
});
PHP
<?php
require_once 'phpmailer/PHPMailerAutoload.php';
if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputSubject']) && isset($_POST['inputMessage'])) {
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress('my#emailaddress.com'); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
$mail->isSMTP();
$mail->Host = gethostbyname('smtp.gmail.com');
$mail->Port = 587;
$mail->SMTPSecure = "tls";
$mail->SMTPAuth = true;
$mail->Username = "mygmailusername#gmail.com";
$mail->Password = "passwordform";
$mail->setFrom('mygmailusername#gmail.com', 'Contact Form');
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
You need to initialize $scope.formData = {} so that it can hold the values you are expecting. Right now, its trying to bind values to a scope variable that is undefined.
Edit - It looks like you have no ng-click handler in your button to register the click to the submit. Please add this to your button. Additionally, $valid only works if your input values are enclosed in a .
template.html
<form name="myForm">
<label class="item item-input" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
<input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Your Email" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputSubject.$invalid && submitted }">
<input ng-model="formData.inputSubject" type="text" class="form-control" id="inputSubject" name="inputSubject" placeholder="Subject Message" required>
</label>
<label class="item item-input" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
<textarea ng-model="formData.inputMessage" class="form-control" rows="4" id="inputMessage" name="inputMessage" placeholder="Your message..." required></textarea>
</label>
<div class="padding">
<button type="submit" class="btn btn-default"
ng-disabled="myForm.$invalid || submitButtonDisabled == true"
ng-click=submit(formData)>Send Message</button>
</div>
</form>
<p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
What this is doing is its registering the $scope.submit the button, and in the HTML you're passing in formData as a parameter. The now has a name and its required values are checked in ng-disabled of the button which refers to the same name and disables if the I've cleaned up your app.js so that you're getting the params correctly.
.controller('ContactCtrl', function ($scope, $http) {
$scope.result = 'hidden'
$scope.resultMessage = '';
$scope.formData; //formData is an object holding the name, email, subject, and message
$scope.submitButtonDisabled = false;
$scope.submitted = false; //used so that form errors are shown only after the form has been submitted
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param(contactform), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
}
});

how send Post request with ajax in ember.js?

I want to send a POST (not GET) request to the server with ember.js. I don't know which function I need at "which function here", but I want to send it to the server for a login request.
App.LoginController = Ember.ObjectController.extend({
actions: {
userLogin: function(user) {
// which function here?
?? ("http://siteurl/api/authentication/login/&username=" + user.username + "&password=" + user.password + "");
this.transitionTo('cat');
},
cancelLogin: function() {
this.transitionTo('menu');
}
}
});
App.UserFormComponent = Ember.Component.extend({
actions: {
submit: function() {
this.sendAction('submit', {
username: this.get('username'),
password: this.get('password')
});
},
cancel: function() {
this.sendAction('cancel');
}
}
});
down here template code
<script type="text/x-handlebars" data-template-name="login">
<header class="bar bar-nav">
<h1 class="title">inloggen</h1>
{{#link-to 'menu' class="icon icon icon-bars pull-right"}}{{/link-to}}
</header>
<!-- SHOW LOADER -->
<div class="content">
<div class="content-padded">
{{user-form submit="userLogin" cancel="cancelLogin" submitTitle="login"}}
</div>
</script>
<script type="text/x-handlebars" data-template-name="components/user-form">
<form {{action "submit" on="submit"}}>
<p><label>gebruikersnaam {{input type="text" value=username}}</label></p>
<p><label>wachtwoord {{input type="password" value=password}}</label></p>
<input type="submit" class="btn btn-primary btn-block" {{bindAttr value=submitTitle}}>
<button class="btn btn-negative btn-block" {{action "cancel"}}>Cancel</button>
</form>
</script>
Ember doesn't have any built in communication layer, you can use jquery for such calls.
App.LoginController = Ember.ObjectController.extend({
actions: {
userLogin: function(user) {
$.ajax({
type: "POST",
url: "http://siteurl/api/authentication/login/&username=" + user.username + "&password=" + user.password,
data: { name: "John", location: "Boston" }
})
this.transitionTo('cat');
},
cancelLogin: function() {
this.transitionTo('menu');
}
}
});