Image CRUD in laravel 9 with vue Js - laravel

I have a form that and I want it to have a CRUD function, I have made the function for the text, but I have no idea how to do CRUD with images,
Here is my code :
Model
protected $fillable= [
'nama',
'alamat',
'nomor',
'email',
];
Controller :
public function index()
{
return Form::all();
}
public function store(Request $request)
{
$data = $request->all();
$response = Form::create($data);
return response()->json([
'status' => 'success',
'data' => $response
], 200);
}
The Form :
<Form #submit="saveData()">
<div class="form-row form-section" id="formParent">
<div class="col-12 mb-3">
<Field name="nama" type="text" class="form-control1" v-model="form.nama" placeholder=" Nama Lengkap" :rules="isRequired" />
<br>
<ErrorMessage name="nama" />
<br>
<Field name="alamat" type="text" class="form-control2" v-model="form.alamat" placeholder=" Alamat" :rules="isRequired" />
<br>
<ErrorMessage name="alamat" />
<br>
<Field name="nomor" type="text" class="form-control3" v-model="form.nomor" placeholder=" Nomor Telfon" :rules="isRequired" />
<br>
<ErrorMessage name="nomor" />
<br>
<Field name="nomor" type="file" class="form-control3" v-model="form.nomor" placeholder=" Nomor Telfon" :rules="isRequired" />
<Field name="email" type="text" class="form-control4" v-model="form.email" placeholder=" Email" :rules="validateEmail" />
<br>
<ErrorMessage name="email" />
</div>
<button class="btnSubmit" type="submit">
Gabung Mitra
</button>
</div>
</Form>
Script :
<script>
import axios from 'axios';
import { Form, Field, ErrorMessage} from 'vee-validate';
export default {
components: {
Form,
Field,
ErrorMessage
},
data() {
return {
form: {
nama: '',
alamat: '',
nomor: '',
email: '',
},
};
},
methods: {
isRequired(value){
if (value && value.trim()){
return true;
}
return 'This is required';
},
validateEmail(value) {
// if the field is empty
if (!value) {
return 'This field is required';
}
// if the field is not a valid email
const regex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (!regex.test(value)) {
return 'This field must be a valid email';
}
// All is good
return true;
},
saveData(){
axios.post('/form/submit', this.form).then(
response => {
console.log(response);
this.$toast.success(`Data berhasil dikirim`,{
position: "bottom",
});
}
). catch(error => {
console.log('error');
this.$toast.error(`Terjadi kegagalan`,{
position: "bottom",
});
})
}
}
};
</script>
What should I do so that the user can upload an image to the form and save it to the database. I tried to change the field type to file, but I have no idea how the function works in the controller.

For storing images with Form you need to add few lines inside contoller for handling and storing image and also you need to add enctype inside form submit.
First you need to change :
<Form #submit="saveData()" enctype="multipart/form-data">
Now you need to change image input field :
<Field name="image" type="file" class="form-control3" v-model="form.image" :rules="isRequired" />
And inside the controller you need to change code for request :
public function store(Request $request)
{
$data = $request->all();
if ($request->hasFile('image')) {
$image = $request->file('image');
$path = $image->store('public/images');
$data['image'] = $path;
}
$response = Form::create($data);
return response()->json([
'status' => 'success',
'data' => $response
], 200);
}
And finally in your model :
protected $fillable = [
'nama',
'alamat',
'nomor',
'email',
'image',
];

Related

Laravel 9 Vue js 3 multipart form, console showing full html, not only the retrieved data

I'm using a multipart form to send texts and image to database,
The data have been successfully sent to the database, but why in the console it is showing the data infull html ? not only the data that has been retrieved ?
this is my code
<template>
<div class="gabungPage">
<div class="row">
<div class="backgroundGabung" id="hrefGabung">
<div class="tulisanGabung p-5">
<div class="cardGabung">
<p class="teksGabung">Tingkatkan bisnismu sekarang dengan bergabung menjadi mitra JAI'</p>
<form #submit.prevent="submitForm">
<div class="form-group">
<label for="nama">Nama</label>
<input
type="text"
id="nama"
v-model="formulirs.nama"
class="form-control"
/>
</div>
<div class="form-group">
<label for="alamat">Alamat</label>
<input
type="text"
id="alamat"
v-model="formulirs.alamat"
class="form-control"
/>
</div>
<div class="form-group">
<label for="email">Email</label>
<input
type="text"
id="email"
v-model="formulirs.email"
class="form-control"
/>
</div>
<div class="form-group">
<label for="nomor">nomor</label>
<input
type="text"
id="nomor"
v-model="formulirs.nomor"
class="form-control"
/>
</div>
<div class="form-group">
<label for="image">Image</label>
<input
type="file"
id="image"
ref="imageInput"
#change="uploadImage"
/>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
</div>
<div class="tesss">
<h1> <span class="tulisKiri1">Gabung jadi</span> <br> <span class="tulisKiri2">mitra jahit</span></h1>
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
formulirs: {
nama: '',
alamat: '',
nomor: '',
email: '',
image: null,
},
};
},
methods: {
uploadImage() {
this.formulirs.image = this.$refs.imageInput.files[0];
},
async submitForm() {
const formData = new FormData();
formData.append('nama', this.formulirs.nama);
formData.append('alamat', this.formulirs.alamat);
formData.append('email', this.formulirs.email);
formData.append('nomor', this.formulirs.nomor);
formData.append('image', this.formulirs.image);
axios.post('/api/submit-form', formData).then(
response => {
console.log(response);
this.$toast.success(`Data berhasil dikirim`,{
position: "bottom",
});
}
). catch(error => {
console.log('error');
this.$toast.error(`Terjadi kegagalan`,{
position: "bottom",
});
})
},
},
};
</script>
the routes/web.php
Route::post('/api/submit-form', [FormulirsController::class, 'store']);
the controller
public function store(Request $request)
{
$validatedData = $request->validate([
'nama' => 'required',
'alamat' => 'required',
'nomor' => 'required',
'email' => 'required|email',
'image' => 'required|image',
]);
$formulir = new Formulirs;
$formulir->nama = $validatedData['nama'];
$formulir->alamat = $validatedData['alamat'];
$formulir->nomor = $validatedData['nomor'];
$formulir->email = $validatedData['email'];
$image = $request->file('image');
$imageName = time().$image->getClientOriginalName();
$image->storeAs('public/images', $imageName);
$formulir->image = $imageName;
$formulir->save();
return back()->with('success', 'Data berhasil dikirim');
}
I have tried to show the data only by changing to
console.log(response.data)
But it got worse, it only shows full html page in the console, what should I do so that it doesn't display the full html page?
You're making an axios request and returning back method. This is used for redirecting in a monolitic app. I recommend you return a JSON response in your controller. Something like this:
public function store(Request $request)
{
$validatedData = $request->validate([
'nama' => 'required',
'alamat' => 'required',
'nomor' => 'required',
'email' => 'required|email',
'image' => 'required|image',
]);
$formulir = new Formulirs;
$formulir->nama = $validatedData['nama'];
$formulir->alamat = $validatedData['alamat'];
$formulir->nomor = $validatedData['nomor'];
$formulir->email = $validatedData['email'];
$image = $request->file('image');
$imageName = time().$image->getClientOriginalName();
$image->storeAs('public/images', $imageName);
$formulir->image = $imageName;
$formulir->save();
return back()->with('success', 'Data berhasil dikirim'); // this is yours
return response()->json('Data berhasil dikirim'); // 200 status code is the second param by default. You can change for whatever you want.
}

Vue 3 checkbox component does not work in laravel as checkbox (Accept terms) situation

I'm working on a laravel 9 project that uses vue 3. For each form input has been made field components.Everything works fine except registration checkbox (Accept terms). If the checkbox is used normally in vue, it works fine. as soon as a component is made of it, it no longer works. By clicking the chackbox on and off I get the message that the accept terms is required!
I hope you can help me with this
-Vue Registration Form componetnt
<template>
<form class="text-left" method="post" #submit.prevent="submit()">
<div class="alert alert-success mb-1" v-if="success" v-html="successMessage"></div>
<div class="alert alert-danger mb-1" v-if="errors.message" v-html="errors.message"></div>
<InputFieldWithoutIcon ref="email" type="email" name="email" label="E-mail" :errors="errors" #update:field="fields.email=$event"/>
<InputFieldWithoutIcon ref="password" type="password" name="password" label="Password" :errors="errors" #update:field="fields.password=$event"/>
<InputFieldWithoutIcon ref="password_confirmation" type="password" name="password_confirmation" label="Password Confirmation" :errors="errors" #update:field="fields.password_confirmation=$event"/>
<Checkbox :text="newsletter_text" name="newsletter" type="checkbox" :errors="errors" #update:field="fields.newsletter=$event"/>
<Checkbox :text="policy_text" name="policy_accepted" type="checkbox" :errors="errors" #update:field="fields.policy_accepted=$event"/>
<SubmitButtonWithoutIcon name="create account" type="submit" custom_btn_class="btn-block btn-primary" custom_div_class=""/>
</form>
</template>
<script>
import InputFieldWithoutIcon from "../components/InputFieldWithoutIcon";
import SubmitButtonWithoutIcon from "../components/SubmitButtonWithoutIcon";
import Checkbox from "../components/Checkbox";
export default {
name: "RegistrationUser",
components: {
InputFieldWithoutIcon,
SubmitButtonWithoutIcon,
Checkbox
},
data() {
return {
fields: {
email: '',
password: '',
password_confirmation: '',
policy_accepted: '',
newsletter: '',
},
errors: {},
success: false,
successMessage: '',
newsletter_text: 'I want to receive newsletters',
policy_text: 'I accept <a class="text-bold text-underline" href="" target="_blank" title="privacy policy">the policy</a>',
}
},
methods: {
submit() {
axios.post('/api/registration', this.fields)
.then(response => {
if (response.status === 200) {
this.$refs.email.value = null;
this.$refs.password.value = null;
this.$refs.password_confirmation.value = null;
this.fields = {
email: '',
password: '',
password_confirmation: '',
policy_accepted: '',
newsletter: '',
};
this.errors = {};
this.success = true;
this.successMessage = response.data.message;
}
}).catch(errors => {
if (errors.response.status === 422 || errors.response.status === 401) {
this.errors = errors.response.data.errors;
}
});
}
}
}
</script>
-Vue Checkbox component
<template>
<div class="custom-control custom-checkbox">
<input class="custom-control-input"
:id="name"
:name="name"
:type="type"
v-model="value"
#input="updateField()"
>
<label class="custom-control-label" :for="name">
{{ text }}
</label>
<div class="invalid-feedback" v-text="errorMessage()"></div>
</div>
</template>
<script>
export default {
name: "Checkbox",
props: [
'name',
'type',
'text',
'errors'
],
data: function () {
return {
value: false
}
},
computed: {
hasError: function () {
return this.errors && this.errors[this.name] && this.errors[this.name].length > 0;
}
},
methods: {
updateField: function () {
this.clearErrors(this.name);
this.$emit('update:field', this.value)
},
errorMessage: function () {
if (this.errors && this.errors[this.name]) {
return this.errors[this.name][0];
}
},
clearErrors: function () {
if (this.hasError) {
this.errors[this.name] = null;
}
}
}
}
</script>
-Laravel Registration request
public function rules(): array
{
return [
'email' => 'required|email|unique:users',
'password' => 'required|confirmed|min:8',
'newsletter' => 'nullable|boolean',
'policy_accepted' => 'accepted'
];
}
I've found the solution.
In the checkbox template instead of using #input="updateField()" I replaced that with #change="updateField()"
That's all!

Error when pass FormData from vue to laravel controller

i'm working on an laravel vuejs spa.
I try to update a post from the admin. I send the form datas on creating a new FromData who are sending with and axios request.
But the controller send me the error:
message: "The given data was invalid."
errors: {name: ["The name field is required."], description: ["The description field is required."]}
Here is the post/edit.vue
<template>
<div class="post-edit">
<form id="form" #submit.prevent="createPost">
<!-- Title -->
<div class="form-group">
<label for="title" class="form-label">Title</label>
<input id="title" v-model="post.title" :title="post.title" type="text"
name="title" class="form-control"
>
</div>
<!-- Category -->
<div class="form-group">
<label for="category" class="form-label">Category</label>
<select id="category" v-model="post.category" :value="post.category" :category="post.category"
name="category" class="form-control"
>
<option disabled :value="post.category">
Choisir une catégorie
</option>
<option v-for="(category) in categories" :key="category.id" :value="post.category">
{{ category.name }}
</option>
</select>
</div>
<div class="post-edit-image">
<img :src="path + post.image" alt="">
</div>
<!-- Image -->
<div class="form-group post-edit-select-image">
<label for="content" class="form-label">Image</label>
<input type="file" name="image" class="form-control" #change="selectedImage">
</div>
<!-- Content -->
<div class="form-group">
<label for="content" class="form-label">Content</label>
<editor
id="content"
v-model="post.content"
api-key="the-api-key"
:init="{
height: 500,
menubar: false,
plugins: [
'advlist autolink lists link image charmap print preview anchor',
'searchreplace visualblocks code fullscreen',
'insertdatetime media table paste code help wordcount'
],
toolbar:
'undo redo | formatselect | bold italic backcolor | \
alignleft aligncenter alignright alignjustify | \
bullist numlist outdent indent | removeformat | help'
}"
name="content"
:content="post.content"
/>
</div>
<!-- Submit Button -->
<button type="submit" class="btn btn-primary">
Sauvegarder
</button>
</form>
</div>
</template>
<script>
import axios from 'axios'
import { mapGetters } from 'vuex'
import Editor from '#tinymce/tinymce-vue'
export default {
middleware: 'auth',
components: {
'editor': Editor
},
props: ['id'],
data () {
return {
post: {
id: '',
user_id: '',
title: '',
category: '',
image: null,
content: ''
},
path: '/images/post/thumbnail/'
}
},
computed: {
...mapGetters({
user: 'auth/user',
categories: 'categories/categories'
})
},
beforeCreate () {
this.$store.dispatch('categories/fetchCategories')
},
created () {
this.getPostById(this.$route.params.id)
},
methods: {
selectedImage (event) {
this.post.image = event.target.files[0]
},
getPostById (id) {
axios.get('/api/posts/edit/' + id)
.then((response) => {
this.post.id = response.data.id
this.post.user_id = response.data.user_id
this.post.title = response.data.title
this.post.category = response.data.category
this.post.image = response.data.image
this.post.content = response.data.content
})
.catch((error) => {
console.log(error)
})
},
createPost (e) {
this.post.userId = this.user.id
let formData = new FormData(e.target)
let id = this.post.id
formData.append('title', this.post.title)
formData.append('category', this.post.category)
formData.append('image', this.post.image)
formData.append('content', this.post.content)
axios.patch('/api/posts/update/' + id, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then((response) => {
console.log(response)
this.$store.dispatch('posts/fetchPosts')
})
.catch((error) => {
console.log(error)
})
this.$router.push({ name: 'admin' })
}
}
}
</script>
And here the laravel controller PostController#update method
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(PostUpdateRequest $request, $id)
{
$post = Post::findOrFail($id);
$post->update($request->getValidRequest());
return response()->json($request, 200);
}
And the custom validator PostUpdateRequest.php
/**
* 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
*/
public function rules()
{
return [
'title' => 'required|max:250|unique:posts,title',
'category' => 'required',
'image' => 'mimes:jpg,jpeg,png,bmp',
'content' => 'required'
];
}
public function getValidRequest()
{
$image = $this->file('image');
$slug = Str::slug($this->input('title'));
if (isset($image)) {
$imageExt = $image->getClientOriginalExtension();
$currentDate = Carbon::now()->toDateString();
$imageName = $slug . '-' . $currentDate . '-' . uniqid() . '.' . $imageExt;
if (!Storage::disk('public')->exists('post')) {
Storage::disk('public')->makeDirectory('post');
}
if (!Storage::disk('public')->exists('post/thumbnail')) {
Storage::disk('public')->makeDirectory('post/thumbnail');
}
$path = "images/";
$postImage = Image::make($image)->resize(null, 1060, function ($constraint){
$constraint->aspectRatio();
})->save(public_path($path).'post/'.$imageName);
$thumbnail = Image::make($image)->fit(550, 550)
->save(public_path($path).'post/thumbnail/'.$imageName);
}
return [
'user_id' => Auth::user()->getAuthIdentifier(),
'category_id' => $this->input('category'),
'title' => $this->input('title'),
'slug' => $slug,
'content' => $this->input('content'),
'image' => $imageName,
'is_published' => $this->input('is_published') ?? false,
];
}
The api route in laravel
Route::patch('/update/{id}', 'Backend\PostController#update');
I use practically the same things to store a post, and it work's fine, the only difference is here i pass an id for the post to update and i not use the post method but patch for axios and the route (and i try with put, it's the same error).
thank's for your time !
append '_method' field with value 'PATCH' to formData
formData.append('_method', 'PATCH')
and send axios request post request to update data
axios.post('/api/posts/update/' + id, formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})

How to display validation errors?

Router
Route::get('/contact',['uses'=>'Admin\ContactController#show','as'=>'contact']);
Route::post('/contact',['uses'=>'Admin\ContactController#store']);
Controller
<?php
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Requests\ContactRequest;
use App\Http\Controllers\Controller;
use Validator;
class ContactController extends Controller
{
public function store(Request $request,$id=FALSE) {
if($request->isMethod('post')) {
$messages = [
'name.required' => 'ПОЛЕ :attribute обязательно к заполнению!!!!',
'email.max' => 'Максимально допустимое количество символов - :max',
];
$validator = Validator::make($request->all(),[
'name'=>'required',
/*'email'=>'required'*/
],$messages);
$validator->sometimes(['email','site'],'required',function($input) {
/*dump($input);
exit();*/
return strlen($input->name) >= 10;
});
$validator->after(function($validator) {
$validator->errors()->add('name','ДОполнительное сообщение');
});
if($validator->fails()) {
$messages = $validator->errors();
//dump ($messages->first());
dump($validator->failed());
exit();
return redirect()->route('contact')->withErrors($validator)->withInput();
}
}
return view('default.contact',['title'=>'Contacts']);
}
public function show() {
return view('default.contact',['title'=>'Contacts']);
}
}
Template
extends('default.layouts.layout')
#section('content')
<div class="col-md-9">
<div class="">
<h2>Contact us!</h2>
</div>
<p>
This is a template for a simple marketing or informational website. It includes a large callout called a jumbotron and three supporting pieces of content. Use it as a starting point to create something more unique.
</p>
{{ count($errors)}}
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{{ $error}}</li>
#endforeach
</ul>
</div>
#endif
<form method="post" action="{{ route('contact') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}" placeholder="Jane Doe">
</div>
<div class="form-group">
<label for="email">Email address</label>
<input type="email" class="form-control" id="email" value="{{ old('email') }}" name="email" placeholder="Email">
</div>
<div class="form-group">
<label for="site">Site</label>
<input type="text" class="form-control" id="site" value="{{ old('site') }}" name="site" placeholder="Site">
</div>
<div class="form-group">
<label for="text">Text</label>
<textarea class="form-control" id="text" name="text" rows="3">{{ old('text') }}</textarea>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
#endsection
The problem is that I have not displayed validation error and the message "further message". Although the validation is successful. The problem is. I don't want to display $messages I tried to walk on it with foreach, but laravel says that it found the $messages. Although the controller $messages displayed. The pattern also shows that the errors I have 0, but in the controller I have shows validation errors.
What's the problem?
try this:i hope it will work for you.
//controller
if ($request->method() == 'POST') {
$rules = [
'name' => 'required',
'email' => 'required'
];
$validator = Validator::make($request->all(), $rules);
if (!$validator->fails()) {
}
else{
//validation_error();
}
}
and use js for validation
$(function () {
$("#form_id").validate({
errorElement: 'small', errorClass: 'invalid-feedback',
rules: {
name: {
required: true,
},
email: {
required: true,
}
},
messages: {
name: {
required: "Name Field Is Required.",
},
email: {
required: "Email Field Is Required.",
}
},
highlight: function (element) {
$(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
$(element).closest('.form-group').removeClass('has-error');
},
success: function (element) {
$(element).closest('.form-group').removeClass('has-error');
$(element).closest('.form-group').children('small.invalid-feedback').remove();
},
errorPlacement: function (error, element) {
error.appendTo(element.closest('.form-group'));
},
submitHandler: function (form) {
$(window).block({
'message': '<i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i>',
'css': {
border: '0',
padding: '0',
backgroundColor: 'none',
marginTop: '5%',
zIndex: '10600'
},
overlayCSS: {backgroundColor: '#555', opacity: 0.3, cursor: 'wait', zIndex: '10600'},
});
$.post('', $("#form_id").serialize(), function (data) {
if (data.code == '1') {
swal({
title: "",
text: data.message,
type: "success"
}, function () {
document.location.href = base_url + '/listing_page';
});
} else if (data === '0') {
swal("", "Something wrong while save building information.", "warning");
} else {
swal("", data, "error");
}
$(window).unblock();
});
}
});
$('select').change(function () {
$("#form_id").validate().element($(this));
});
});

How to AJAX work

I am new in AJAX. but I am trying to learn How this is working.
I am using symfony2 with fos user bundle and I want implement AJAX to my login form.
so I was doing this :
login.html.twig
<script>
$('#_submit').click(function(e){
e.preventDefault();
$.ajax({
type : $('form').attr( 'method' ),
url : $('form').attr( 'action' ),
data : $('form').serialize(),
success : function(data, status, object) {
if (data.sucess == false) {
$('.tab-1').prepend('<div />').html(data.message);
} else {
window.location.href = data.targetUrl;
}
}
});
</script>
<div id="tab-1" class="login_form">
<form action="{{ path("fos_user_security_check") }}" role="form" method="post">
<label for="username"><strong>User Name / Email Address</strong>
<input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
</label>
<label for="password"><strong>Password</strong>
<input type="password" id="password" name="_password" required="required" />
</label>
<label for="password"><strong>Remember Me</strong>
<input type="checkbox" id="remember_me" name="_remember_me" value="on" />
</label>
<input type="submit" class="submitBut" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans({}, 'FOSUserBundle') }}" />
</form>
</div>
And when submit then go this file :-
<?php
namespace XXXX\UserBundle\Handler;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
protected $router;
protected $security;
protected $userManager;
protected $service_container;
public function __construct(RouterInterface $router, SecurityContext $security, $userManager, $service_container)
{
$this->router = $router;
$this->security = $security;
$this->userManager = $userManager;
$this->service_container = $service_container;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
if ($request->isXmlHttpRequest()) {
$result = array('success' => true);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
else {
// Create a flash message with the authentication error message
$request->getSession()->getFlashBag()->set('error', $exception->getMessage());
$url = $this->router->generate('fos_user_security_login');
return new RedirectResponse($url);
}
return new RedirectResponse($this->router->generate('anag_new'));
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
$translator = new Translator('fr_FR');
//$result = array(
// 'success' => false,
// 'function' => 'onAuthenticationFailure',
// 'error' => true,
// 'message' => $this->translator->trans($exception->getMessage(), array(), 'FOSUserBundle')
//);
$result = array('success' => false);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
When submit the form then show me in login_check url:
{"success":false}
But I want when result false then return same form where I was trying to login(I mean same popup div)?
What's wrong my code ajax or action return ?
Or I am return correct ?
window.location will reload the entire page. That's not the desired result I suppose since you are using AJAX ( the hole point of AJAX is to not reload the page) instead you could display an error message if the login is not successful.
I suggest you add an error div in your html form
<div class='error' style="display:none" > ooups an erro occured </div>
and then in the ajax call just show it or add a significant message error :
if (data.sucess == false) {
$('.tab-1').prepend('<div />').html(data.message);
} else {
$('.error').show();
}

Resources