When i try to submit a record to my SQL from vue component with laravel API nothing happens. I have compared my code to other working code but nothing seem to work.
Here is my register method:
register() {
axios
.post('/api/register', this.user)
.then(res => {
console.log(user)
})
.catch(err => {
console.log(err.message)
})
},
Here is the register form:
<template>
<form>
<div class="form-group">
<input
type="text"
v-model="user.name"
name="username"
class="form-control"
id="name"
placeholder="Email or username"
/>
<div class="validation"></div>
</div>
<div class="form-group">
<input
v-model="user.email"
type="email"
class="form-control"
name="email"
id="password"
placeholder="Your Email"
/>
<div class="validation"></div>
</div>
<div class="form-group">
<input
v-model="user.password"
type="password"
class="form-control"
name="password"
placeholder="Your Password"
data-rule="password"
/>
<div class="validation"></div>
</div>
<div id="errormessage"></div>
<div class="text-center">
<button type="submit" title="Register" v-on:click="register">Login</button>
</div>
</form>
</template>
My laravel page:
<section id="pricing" class="wow fadeInUp section-bg">
<div class="container">
<header class="section-header">
<h3>Register</h3>
<p>Come prepared!!</p>
</header>
<div class="row flex-items-xs-middle flex-items-xs-center">
<div class="col-xs-12 col-lg-6">
<div class="card">
<div class="card-header">
<div id="app">
<register></register>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
Here is my controller:
if ($v->fails())
{
return response()->json([
'status' => 'error',
'errors' => $v->errors()
], 422);
}
$user = new User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = Hash::make($request->password);
$user->save();
return response()->json(['status' => 'success'], 200);
}
The record should post successfully, however nothing happens. I only see the parameters on my url like so, and I don't get any error on console.
You'll need to prevent the default form submission behavior first, then trigger your own register method.
<form #submit.prevent="register">
Related
I have a problem displaying errors message in update modal form. I'm using laravel request for validation and AJAX to submit form inside a modal. I would like to see the error message for each field that are inputted incorrectly. However, I'm getting this error:
The Given data is invalid
I checked the network tab, and I'm seeing the errors there but I can't figure out why this is not showing in my fields.
Here is my script's
function updatePassword(e, t)
{
e.preventDefault();
const url = BASE_URL + '/admin/organizations/operators/updatePassword/' + $(updatePasswordForm).find("input[name='id']").val();
var form_data = $(t).serialize();
// loading('show');
axios.post(url, form_data)
.then(response => {
notify(response.data.message, 'success');
$(updatePasswordModal).modal('hide');
// roleTable.ajax.reload()
})
.catch(error => {
const response = error.response;
if (response) {
if (response.status === 422)
validationForm(updatePasswordForm, response.data.errors);
else if(response.status === 404)
notify('Not found', 'error');
else
notify(response.data.message, 'error');
}
})
.finally(() => {
// loading('hide');
});
}
Here is my Blade file
<form id="updatePasswordForm" onsubmit="updatePassword(event, this)">
<input type="hidden" name="id" value="">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"> {{ __('Update Password') }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-group row">
<label class="col-sm-4 col-form-label required">{{ __('New Password') }}</label>
<div class="col-sm-8">
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password') error #enderror">
<input type="password" class="form-control" id="password" name="user[password]" placeholder="{{ __('Password') }}" required>
</div>
</div>
</div>
#error('user.password')
<p class="error-message">{{ $message }}</p>
#enderror
</div>
</div>
<div class="form-group row">
<label class="col-sm-4 col-form-label required">{{ __('Confirm Password') }}</label>
<div class="col-sm-8">
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password_confirmation') error #enderror">
<input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
</div>
</div>
</div>
#error('user.password_confirmation')
<p class="error-message">{{ $message }}</p>
#enderror
</div>
</div>
</div>
<div class="modal-footer justify-content-center">
<button type="button" class="btn btn-secondary mr-3" data-dismiss="modal">{{ __('Close') }}</button>
<button type="submit" class="btn btn-primary">{{ __('Save') }} </button>
</div>
</div>
</form>
Here is My Controller:
<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\Organization\Operator\UpdatePasswordRequest;
use App\Models\OrganizationOperator;
use Illuminate\Http\Request;
use App\Services\Response;
use Exception;
use Illuminate\Support\Facades\Log;
class OrganizationController extends Controller
{
public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request)
{
try {
$data = $request->validated();
$user = $data['user'];
// dd($user['password']);
$operator->update([
'password' => bcrypt($user['password']),
]);
return Response::success(__('Successfully updated'));
} catch (Exception $e) {
Log::error($e->getMessage());
return Response::error(__('Unable to update'), [], 500);
}
}
}
Here is my Request Validation Class:
<?php
namespace App\Http\Requests\Admin\Organization\Operator;
use Illuminate\Foundation\Http\FormRequest;
class UpdatePasswordRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array<string, mixed>
*/
public function rules()
{
return [
'id' => ['required', 'integer', 'exists:organization_operators,id'],
'user.password' => ['required', 'string', 'min:8', 'confirmed'],
];
}
}
First, I think this issue is because you send the request from the client side (which is is ajax/axios). The validation work when you submit to the server side (without ajax/axios) then response validation will display to the blade/html.
In this case, you must set error to the html manually (with innerHTML or .html() in jquery) using class/id.
for example this response from the server/api :
{ "error" : {
"user.password" : ["invalid password"],
...
}
}
in client side, you need to put that message to html tag in that case with p tag.
<p id="error-password" ></p>
$('#error-password').html(error["user.password"])
// or
$('#error-password').text(error["user.password"])
Finally I solved this problem.
1. I change my controller
public function updateOperatorPassword(OrganizationOperator $operator, UpdatePasswordRequest $request)
TO
public function updateOperatorPasswordApi(User $user, UpdatePasswordRequest $request)
AND
try {
$data = $request->validated();
$user = $data['user'];
// dd($user['password']);
$operator->update([
'password' => bcrypt($user['password']),
]);
return Response::success(__('Successfully updated'));
}
TO
try {
$data = $request->validated();
$user->update([
'password' => bcrypt($data['password']),
]);
return Response::success(__('Successfully created'));
}
2. I change my blade file
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password_confirmation') error #enderror">
<input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
</div>
</div>
</div>
#error('user.password_confirmation')
<p class="error-message">{{ $message }}</p>
#enderror
TO
<div class="form-group">
<label for="">{{ __('Password') }}</label>
<input name="password" type="password" class="form-control" id="password" aria-describedby="emailHelp" placeholder="{{ __('Password') }}" required>
<small class="form-text error-message"></small>
</div>
AND
<div class="row">
<div class="col-sm-12">
<div class="form-group #error('user.password_confirmation') error #enderror">
<input type="password" class="form-control" id="confirmPassword" name="user[password_confirmation]" placeholder="{{ __('Confirm Password') }}">
</div>
</div>
</div>
#error('user.password_confirmation')
<p class="error-message">{{ $message }}</p>
#enderror
TO
<div class="form-group">
<label for="">{{ __('Confirm Password') }}</label>
<input name="password_confirmation" type="password" class="form-control" id="password_confirmation" aria-describedby="emailHelp" placeholder="{{ __('Confirm Password') }}" required>
<small class="form-text error-message"></small>
</div>
I'm trying to display a simple ReCaptcha. However, it appears if I delete onloadCallback function and then re-add it. Then it disappears until I do this again.
I will attach the code that I use. Also, I add localhost as a domain and I install the package using npm. I will write hidden instead of the site key that I use. Also, I want to hide my submit form button if the ReCaptcha is not verified, for this, I use useState hooks.
import React, { useState, useEffect } from 'react';
import ReCAPTCHA from "react-google-recaptcha";
import firebase from 'firebase/compat/app';
import 'firebase/compat/firestore';
import { collection, addDoc } from "firebase/firestore";
import {db} from "./firebase.js"
export default function Contact(){
const [captcha, setCaptcha] = useState(true);
const [formData, setFormData] = useState({
name: "",
phone: "",
subject: "",
message: ""
})
function handleOnChange(value){
setCaptcha(false);
console.log("recaptcha ", value);
}
function recaptchaLoaded() {
console.log('capcha successfully loaded');
}
function handleOnChange(value){
console.log("captcha value:" , value);
}
function handleChange(event){
const {name, phone, subject, message} = event.target
setFormData(prevFormData => ({
...prevFormData,
[event.target.name]: event.target.value
}))
}
function handleSubmit(event){
event.preventDefault();
try {
console.log(formData);
const docRef = addDoc(collection(db, "mesaje"), { formData });
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
}
return(
<section id="contact" class="contact">
<div class="container">
<div class="section-title" data-aos="zoom-out">
<h2>Contact</h2>
<p>Date de contact</p>
</div>
<div class="row mt-5">
<div class="col-lg-4" data-aos="fade-right">
<div class="info">
<div class="address">
<i class="bi bi-geo-alt"></i>
<h4>Locatie:</h4>
<p>Galati</p>
</div>
<div class="email">
<i class="bi bi-envelope"></i>
<h4>Email:</h4>
<p>carageamarian72#yahoo.com</p>
</div>
<div class="phone">
<i class="bi bi-phone"></i>
<h4>Telefon:</h4>
<p>0744635351</p>
</div>
</div>
</div>
<div class="col-lg-8 mt-5 mt-lg-0" data-aos="fade-left">
<form onSubmit={handleSubmit} class="php-email-form" >
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Nume" required onChange={handleChange}
value={formData.name}/>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="tel" class="form-control" name="phone" id="phone" placeholder="Telefon" required onChange={handleChange}
value={formData.phone} pattern="[0-9]{10}"/>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="subject" id="subject" placeholder="Subiect" required onChange={handleChange}
value={formData.subject}/>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="message" rows="5" placeholder="Mesaj" required onChange={handleChange}
value={formData.message}></textarea>
</div>
<div class="my-3">
<div class="loading">Loading</div>
<div class="error-message">Eroare, mesajul nu a fost trimis!</div>
<div class="sent-message">Mesajul a fost trimis, te vom contacta imediat!</div>
</div>
<ReCAPTCHA
sitekey="hidden"
onChange={handleOnChange}
onloadCallback={recaptchaLoaded}
/>
<div class="text-center"><button type="submit" disabled={captcha}>Trimite mesaj</button></div>
</form>
</div>
</div>
</div>
</section>
);
}
i found the problem. I had 2 different types of recaptcha in my html folder. They were in conflict.
I also delete the onloadCallback props.
I have created a contact form for users to email through a web app. The fields on the form are Name, Company, Contact Number and Message. When I tested the app the email sends but it only sends the data from the message input and the remain blank.
app.js file
let mailOptions = {
from: '"Nodemailer Contact" <**********>', // sender address
to: '*************', // list of receivers
subject: 'TW Contact Request', // Subject line
Name: req.body.Name,
Company: req.body.Company,
Phone: req.body.Phone,
message: req.body.Body, // plain text body
html: req.body.body // html body
};
index.ejs file
<form action="/send-email" method="post">
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="Name">Name:</label>
<input type="text" class="form-control" name="Name">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="Company">Company:</label>
<input type="text" class="form-control" name="Company">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="Phone">Contact Number:</label>
<input type="text" class="form-control" name="Phone">
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<label for="body">Message:</label>
<textarea cols="5" rows="5"class="form-control" name="body"></textarea>
</div>
</div>
<div class="row">
<div class="col-md-4"></div>
<div class="form-group col-md-4">
<button type="submit" class="btn btn-success">Send</button>
</div>
</div>
</form>
I cant see why it is not pulling all the data.
Please use following code for getting request data
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
There is a form on angular 8
my-form.component.html
<div class="container">
<form novalidate [formGroup]="registrationForm">
<div class="form-group">
<label for="firstName">Имя:</label>
<input #spy required pattern=[A-Za-zА-Яа-яЁё]{2,} name="firstName" id="firstName" type="text" class="form-control" formControlName="firstName">
</div>
<div class="form-group">
<label for="lastName">Фамилия:</label>
<input #spy required pattern=[A-Za-zА-Яа-яЁё]{2,} name="lastName" id="lastName" type="text" class="form-control" formControlName="lastName">
</div>
<div class="form-group">
<label for="email">E-mail:</label>
<input #spy required email name="email" id="email" type="email" class="form-control" formControlName="email">
</div>
<!--{{ spy.className }}-->
<button type="submit" class="btn btn-succes" (click)="submit(myForm)">Отправить</button>
</form>
When the user writes data, the submit button should send data to the API using the POST method.
If you need any code, leave a comment
ts code:
import { FormGroup, FormControl } from '#angular/forms';
import {HttpClient} from '#angular/common/http';
#Component({
selector: 'app-my-form',
templateUrl: './my-form.component.html',
styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {
registrationForm: FormGroup;
constructor() { }
ngOnInit() {
this.registrationForm = new FormGroup({
firstName: new FormControl(),
lastName: new FormControl(),
email: new FormControl()
});
}
}```
i have simple example for you....
reference
----html----
<header class="masthead">
<div class="container h-100">
<div class="row h-100 align-items-center justify-content-center">
<div class="col-6">
<div class="text-center">
<hello name="{{ name }}"></hello>
<hr>
</div>
<form #send="ngForm" (ngSubmit)="sendFRMData(send.value)">
<div class="form-group">
<label for="title" class="text-muted">Title</label>
<input type="text" class="form-control" id="title"
name="titlefrm" ngModel #title='ngModel' required>
<span class="help-block text-danger" *ngIf="!title.valid &&
title.touched">Please give Title!!</span>
</div>
<div class="form-group">
<label for="body" class="text-muted">Body</label>
<input type="text" class="form-control" id="body" name="bodyfrm" ngModel
#body='ngModel' required>
<span class="help-block text-danger" *ngIf="!body.valid &&
body.touched">Please
give Body!!</span>
</div>
<div class="form-group">
<label for="userId" class="text-muted">UserID</label>
<input type="text" class="form-control" id="userId" name="userIdfrm" ngModel
#userid='ngModel' required>
<span class="help-block text-danger" *ngIf="!userid.valid &&
userid.touched">Please give UserID!!</span>
</div>
<div class="row">
<div class="col-sm-6">
<input class="form-control btn btn-success" type="submit"
[disabled]='!send.valid'>
</div>
<div class="col-sm-6">
<input class="form-control btn btn-info" type="button" value="EDIT"
(click) = 'onEdit()'>
</div>
</div>
</form>
</div>
</div>
</div>
</header>
----ts----
import { NgForm } from '#angular/forms';
#ViewChild('send') send: NgForm;
constructor(private sendData: HttpService) {
}
sendFRMData(data: any) {
const payload = {
title: data.titlefrm,
body: data.bodyfrm,
userId: data.userIdfrm
}
this.sendData.try(payload).subscribe(
(data: any) => {
this.respondedData = JSON.stringify(data);
this.alert = true;
}
);
}
----service----
try(data){
return
this.http.post('https://jsonplaceholder.typicode.com/posts',data,{
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
}
hope you get your answer...
Seems like you are not able to get form values in your submit function.
change your click event from (click)="submit(myForm)" to (click)="submit(myForm.value)" then in your submit function you can call post method
submit(formValueObject) {
console.log(formValueObject);
this.httpService.post(url, formValueObject).subscribe((res:any)=> {
//your response
})
}
I hope it helps
I'm authenticating users registered in my firebase database and i want to redirect the user after successful authentication
const txtEmail = document.getElementById('email');
const txtPass = document.getElementById('password');
const loginBtn= document.getElementById('reg');
loginBtn.addEventListener('click', e => {
const mail = txtEmail.value;
const pass = txtPass.value;
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(mail, pass);
if(promise){
window.location = "{{ route('users') }}";
console.log("{{ route('users') }}");
}else{
}
});
the log is successfully printed but the redirection fails may someone help
this is my form i don't know but maybe there is something wrong in it
<form class="form-horizontal m-t-20" method="post">
{{ csrf_field() }}
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" type="text" required="" id="email" placeholder="email">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" type="password" id="password" required="" name="password" placeholder="Password">
</div>
</div>
<div class="form-group ">
<div class="col-xs-12">
<div class="checkbox checkbox-custom">
<input id="checkbox-signup" type="checkbox">
<label for="checkbox-signup">
Remember me
</label>
</div>
</div>
</div>
<div class="form-group text-center m-t-30">
<div class="col-xs-12">
<button class="btn btn-custom btn-bordred btn-block waves-effect waves-light" class="reg" id="reg">
Login
</button>
</div>
</div>
<div class="form-group m-t-30 m-b-0">
<div class="col-sm-12">
<i class="fa fa-lock m-r-5"></i> Forgot your password?
</div>
</div>
</form>