I am stuck with some issue while using vue and laravel. From the vue JS I am clonning the fields like address or cities to multiple clone. I am trying to submit the form without filling those fields It should show the errors under each box (validation error).
here is the code I am using ---
in the .vue file ---
<template>
<div class="container">
<h2 class="text-center">Add User</h2>
<div class="row">
<div class="col-md-12">
<router-link :to="{ name: 'Users' }" class="btn btn-primary btn-sm float-right mb-3">Back</router-link>
</div>
</div>
<div class="row">
<div class="col-md-12">
<ul>
<li v-for="(error, key) in errors" :key="key">
{{ error }}
</li>
</ul>
<form>
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" v-model="user.name">
<span class="text-danger">{{ errors.name }}</span>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" class="form-control" v-model="user.email">
<span class="text-danger">{{ errors.email }}</span>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" class="form-control" v-model="user.password">
<span class="text-danger">{{ errors.password }}</span>
</div>
<button type="button" class="btn btn-primary btn-sm float-right mb-3" #click="addMoreAddress()">Add More</button>
<template v-for="(addressNo, index) in addresses">
<h5>Address ({{addressNo}}) </h5>
<div class="form-group">
<label>Address</label>
<textarea type="text" rows="5" class="form-control" v-model="user.addresses[index].address"></textarea>
<span class="text-danger">{{ errors.addresses }}</span>
</div>
<div class="form-group">
<label>City</label>
<input type="text" class="form-control" v-model="user.addresses[index].cities">
<span class="text-danger">{{ errors.addresses }}</span>
</div>
</template>
<button type="button" class="btn btn-primary" #click="createUser()">Create</button>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
user: {
name: '',
email: '',
password: '',
addresses: [
{
address: '',
cities : ''
}
]
},
errors: {},
addresses: 1
}
},
methods: {
createUser() {
let vm = this;
axios.post('api/users', vm.user)
.then(({data}) => {
// vm.$router.push('/users');
})
.catch((error) => {
let errorsMessages = error.response.data;
console.log(errorsMessages);
const errors = {};
if (Object.keys(errorsMessages).length) {
Object.keys(errorsMessages.errors).forEach((key) => {
errors[key] = errorsMessages.errors[key][0];
});
}
vm.errors = errors;
});
},
addMoreAddress() {
this.user.addresses.push({address:'',cities:''});
this.addresses++;
}
}
}
</script>
and in the laravel I am using the following code (for validation)---
$data = Validator::make($request->all(), [
'name' => 'required|string',
'email' => 'required|string|email|unique:users',
'password' => 'required|string|min:8',
'addresses.*.address' => 'required',
'addresses.*.cities' => 'required',
]);
$errors = $data->errors();
if ($data->fails()) {
return response()->json([
'errors' => $errors
], 422);
}
When I try to submit the form without filling the record. from the api it returing like ---
But I am not able to show the error under each field for address and city. If i print the response it works fine and for name as well. I want the same error message view like showing under name field.
Thanks in advance for helping hands..
Related
i use select2 in livewire. When adding data, it worked. But when editing the data, and not changing the data in the select option, the previously selected trainer data is all lost.
Here is the code I made.
Edit.php
<?php
namespace App\Http\Livewire\Admin\Courses;
use App\Models\Course;
use App\Models\Trainer;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\WithFileUploads;
use \Cviebrock\EloquentSluggable\Services\SlugService;
class Edit extends Component
{
use LivewireAlert;
use WithFileUploads;
public $title, $slug, $cover, $video, $link, $method, $format, $duration, $price, $description, $isActive, $meta_keywords, $meta_description, $addon_styles, $addon_scripts, $courseId;
public $trainer_id;
public function mount($id)
{
$course = Course::findOrFail($id);
if ($course) {
$this->courseId = $course->id;
$this->trainer_id = $course->trainer_id;
$this->title = $course->title;
$this->slug = $course->slug;
$this->link = $course->link;
$this->method = $course->method;
$this->format = $course->format;
$this->duration = $course->duration;
$this->price = $course->price;
$this->description = $course->description;
$this->isActive = $course->isActive;
$this->meta_keywords = $course->meta_keywords;
$this->meta_description = $course->meta_description;
$this->addon_styles = $course->addon_styles;
$this->addon_scripts = $course->addon_scripts;
}
}
public function updatedTitle()
{
$this->slug = SlugService::createSlug(Course::class, 'slug', $this->title);
}
public function update()
{
$course = Course::where('id',$this->courseId)->first();
$this->validate([
'title' => 'required',
'cover' => $this->cover ? 'required|image|mimes:png,jpg,webp,jpeg' : '',
'description' => 'required',
]);
if ($this->cover) {
\Storage::delete('public/'.$course->cover);
$fileName = time().'_'.$this->cover->getClientOriginalName();
$filePath = $this->cover->storeAs('images/courses', $fileName, 'public');
} else {
$filePath = $course->cover ?? null;
}
if ($this->video) {
\Storage::delete('public/'.$course->video);
$fileName = time().'_'.$this->video->getClientOriginalName();
$video = $this->cover->storeAs('images/courses', $fileName, 'public');
} else {
$video = $course->video ?? null;
}
$course->update([
'title' => $this->title,
'slug' => $this->slug,
'cover' => $filePath,
'video' => $this->video ? $video : null,
'link' => $this->link,
'method' => $this->method,
'format' => $this->format,
'duration' => $this->duration,
'price' => $this->price,
'description' => $this->description,
'isActive' => $this->isActive,
'meta_keywords' => $this->meta_keywords,
'meta_description' => $this->meta_description,
'addon_styles' => $this->addon_styles,
'addon_scripts' => $this->addon_scripts
]);
$course->trainers()->sync($this->trainer_id);
$this->alert('success', 'Data updated successfully.');
return redirect()->route('courses.index');
}
public function render()
{
return view('livewire.admin.courses.edit',[
'trainers' => Trainer::where('isActive',true)->get(),
'course' => Course::find($this->courseId)
])
->extends('layouts.app')
->section('content');
}
}
edit.blade.php
<div>
#section('title', 'Edit Course')
#section('styles')
<script src="{{ asset('vendor/tinymce/tinymce.min.js') }}"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<style>
span .selection {
display: block;
}
</style>
#endsection
<!-- ========== title-wrapper start ========== -->
<div class="title-wrapper pt-30">
<div class="row align-items-center">
<div class="col-md-6">
<div class="title mb-30">
<h2>Edit Course</h2>
</div>
</div>
<!-- end col -->
<div class="col-md-6">
<div class="breadcrumb-wrapper mb-30">
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb-item">
Dashboard
</li>
<li class="breadcrumb-item">
Courses
</li>
<li class="breadcrumb-item active" aria-current="page">
Edit Course
</li>
</ol>
</nav>
</div>
</div>
<!-- end col -->
</div>
<!-- end row -->
</div>
<div class="row">
<div class="col-lg-12">
<div class="card-style mb-3">
<form wire:submit.prevent="update" class="row g-3">
<input type="hidden" wire:model="courseId">
<div class="col-12">
<div class="mb-3">
<label for="cover" class="form-label">Cover</label><br>
#if ($cover)
Cover Preview:
<div class="card mb-3">
<img src="{{ $cover->temporaryUrl() }}" class="w-15 rounded-3">
</div>
#else
<div class="card mb-3">
<img src="{{ asset('storage/'.$course->cover) }}" class="w-15 rounded-3 img-fluid">
</div>
#endif
<input type="file" wire:model="cover" class="form-control #error('cover') is-invalid #enderror" id="cover">
#error('cover')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="title" class="form-label">Title</label>
<input type="text" wire:model="title" class="form-control #error('title') is-invalid #enderror" id="title" placeholder="Course Title">
#error('title')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="mb-3">
<label for="slug" class="form-label">Slug</label>
<input type="text" wire:model="slug" class="form-control #error('slug') is-invalid #enderror" id="slug" placeholder="course-slug">
#error('slug')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="mb-3" wire:ignore>
<label for="description" class="form-label">Description</label>
<textarea wire:model="description" class="form-control #error('description') is-invalid #enderror" id="description" rows="15"></textarea>
#error('description')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
</div>
<div class="col-md-6">
<div class="mb-3">
<label for="video" class="form-label">Video</label>
<input type="file" wire:model="video" class="form-control" id="video">
</div>
<div class="mb-3">
<label for="link" class="form-label">Link</label>
<input type="url" wire:model="link" class="form-control" id="link" placeholder="Youtube link">
</div>
<div class="mb-3">
<label for="method" class="form-label">Method</label>
<input type="text" wire:model="method" class="form-control" id="method" placeholder="Example: online, hybrid">
</div>
<div class="mb-3">
<label for="format" class="form-label">Format</label>
<input type="text" wire:model="format" class="form-control" id="format" placeholder="Eg: HD Video, Live Concultation">
</div>
<div class="mb-3">
<label for="duration" class="form-label">Duration</label>
<input type="text" wire:model="duration" class="form-control" id="duration" placeholder="Eg: 3 mounts">
</div>
<div class="mb-3">
<label for="price" class="form-label">Price</label>
<input type="number" wire:model="price" class="form-control #error('price') is-invalid #enderror" id="price" placeholder="Eg: 250000">
#error('price')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
<div class="mb-3" wire:ignore>
<label for="trainer" class="form-label">Trainer</label>
<select multiple="multiple" id="trainer" class="form-select #error('trainer_id') is-invalid #enderror" multiple>
#foreach ($trainers as $trainer)
<option {{ $course->trainers()->find($trainer->id) ? 'selected' : '' }} value="{{ $trainer->id }}">{{ $trainer->name }}</option>
#endforeach
</select>
#error('trainer_id')
<div class="invalid-feedback">
{{ $message }}
</div>
#enderror
</div>
</div>
<div class="col-12">
<div class="mb-3">
<label for="meta_keywords" class="form-label">Meta Keywords</label>
<input type="text" wire:model="meta_keywords" class="form-control" id="meta_keywords" placeholder="keyword1, keyword2, keyword3">
</div>
</div>
<div class="col-12">
<div class="mb-3">
<label for="meta_description" class="form-label">Meta Description</label>
<input type="text" wire:model="meta_description" class="form-control" id="meta_description" placeholder="Meta description">
</div>
</div>
<div class="col-12">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="gridCheck" wire:model="isActive">
<label class="form-check-label" for="gridCheck">
Set active
</label>
</div>
</div>
<button type="submit" class="w-100 main-btn primary-btn btn-hover btn-sm" wire:target="update" wire:loading.class="deactive-btn">
<span wire:loading.remove wire:target="update">
Update
</span>
<span wire:loading wire:target="update" class="text-center">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Loading...
</span>
</button>
</form>
</div>
</div>
</div>
</div>
#push('scripts')
<script src="//cdn.jsdelivr.net/npm/sweetalert2#11"></script>
<x-livewire-alert::scripts />
<script>
tinymce.init({
selector: 'textarea',
menubar: 'file edit view insert format tools table help',
plugins: [
"advlist autolink autosave codesample lists link image charmap print preview hr anchor pagebreak",
"searchreplace wordcount visualblocks visualchars code fullscreen",
"insertdatetime media nonbreaking save table toc directionality",
"emoticons template paste textpattern"
],
toolbar: "restoredraft insertfile undo redo | styleselect fontselect fontsizeselect | bold italic | alignleft aligncenter alignright alignjustify codesample | bullist numlist outdent indent toc| link image media",
setup: function(editor) {
editor.on('change', function(e) {
console.log('the content ', editor.getContent());
#this.set('description', editor.getContent());
});
}
});
</script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function () {
$('#trainer').select2();
$('#trainer').on('change', function (e) {
var data = $('#trainer').select2("val");
#this.set('trainer_id', data);
});
});
</script>
#endpush
How to solve this problem? so that, when I edit the data and without changing the data in select2, the data will not be deleted.
Thank you
This worked for me.
when editing my modal i load my data to my array as follows;
public $selectedOn = [];
public function edit($id){
$foos = Foo::where('other_id',$id)->get();
foreach($foos as $foo){
array_push($this->selectedOn, $foo->id);
}
$this->emit('selectLoadOk');
}
in my js I do the following;
window.livewire.on('selectLoadOk', () =>{
$('#selectChecklist').trigger('change');
});
I want to validate all field. But It is validating only first field. Append field is not validating
multiple fields validation using livewire? name.0.required is working but name.*.required is not working.
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Test extends Component
{
public $name;
public $inputs = [];
public $i = 1;
public function add($i)
{
$i = $i + 1;
$this->i = $i;
array_push($this->inputs ,$i);
}
public function remove($i)
{
unset($this->inputs[$i]);
}
public function store()
{
$validatedDate = $this->validate([
'name.0' => 'required',
'name.*' => 'required',
],
[
'name.0.required' => 'name field is required',
'name.*.required' => 'name field is required',
]
);
session()->flash('message', 'Name Has Been Created Successfully.');
}
public function render()
{
return view('livewire.test');
}
}
<div>
<form class="offset-md-3">
#if (session()->has('message'))
<div class="alert alert-success">
{{ session('message') }}
</div>
#endif
<div class="add-input">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Name" wire:model="name.0">
#error('name.0') <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>
<div class="col-md-2">
<button class="btn text-white btn-info btn-sm" wire:click.prevent="add({{$i}})">Add</button>
</div>
</div>
</div>
#foreach($inputs as $key => $value)
<div class=" add-input">
<div class="row">
<div class="col-md-5">
<div class="form-group">
<input type="text" class="form-control" placeholder="Enter Name" wire:model="name.{{ $value }}">
#error('name.'.$value) <span class="text-danger error">{{ $message }}</span>#enderror
</div>
</div>
<div class="col-md-2">
<button class="btn btn-danger btn-sm" wire:click.prevent="remove({{$key}})">remove</button>
</div>
</div>
</div>
#endforeach
<div class="row">
<div class="col-md-12">
<button type="button" wire:click.prevent="store()" class="btn btn-success btn-sm">Save</button>
</div>
</div>
</form>
</div>
This is my full code use to create multi field using livewire. I am not able to validate appended field so I need help to solve this problem. This validate first field name.0 other append field name.* does not validate.
You should use $key instead $value.
Like this:
wire:model="name.{{ $key }}"
I am getting a continuous validation error despite the data being valid. I originally had this forming working, at the time I was only storing one email at a time. When I added the "addNewRow" function, I was unable to post the data. Each time I get a validation error, I am quite new to Vue, and I'm not sure where I am going wrong with either the post method or my validation.
Here is my controller:
public function notifyTeam(Request $request, Agency $id)
{
$request->validate([
'email' => 'unique:users|required|email|max:255|unique:agency_emails',
]);
$user = Auth::user();
$agency = Agency::where('id', $user->agency_id)->first();
$subdomain = $agency->subdomain;
$emails = json_decode($request->getContent('emailArray'), true);
foreach($emails as $email){
$authorizedEmails = new AgencyEmail;
$authorizedEmails->email = $request->email;
$authorizedEmails->agency_id = $agency->id;
$authorizedEmails->save();
}
// Generate Link
// /{subdomain}/register
// Email the link to specified users
// vue component
return redirect()->route('dashboard');
}
And here is my Vue Component:
<template>
<div class="row justify-content-center">
<div class="col-md-4">
<div class="row justify-content-center">
</div>
<h1 class="agency_h1 mt-5 mb-5">ASSEMBLE THE TROOPS</h1>
<form method="POST" #submit.prevent="submit">
<input type="hidden" name="_token" :value="csrf">
<label for="email">E-mail Address</label>
<div class="form-group row" v-for="(field, k) in fields" :key="k">
<div class="input-group">
<input id="email" type="email" class="form-control" name="email[]" v-model="field.email"
required placeholder="Add An Email Address">
</div>
<div class="col">
<div class="alert alert-success alert-dismissible fade show sticky-top mt-2" role="alert"
v-show="success">
Emails Have Been Seent
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="alert alert-danger alert-dismissible fade show sticky-top mt-2" role="alert"
v-if="errors && errors.email">
{{ errors.email[0] }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</div>
</div>
<button type="submit" class="btn btn-success mb-2" #click="addNewRow">Add Row +</button>
<button type="submit" class="btn btn-primary btn-block mb-5" >Create Your Agency</button>
</form>
</div>
</div>
</template>
<script>
export default {
data() {
return {
fields: [{
email: '',
}],
errors: {},
success: false,
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content')
}
},
methods: {
addNewRow() {
this.fields.push({
email: '',
});
},
submit() {
axios.post('/create-team', {
emailArray: this.fields
})
.then(response => {
this.fields = {};
this.success = true;
this.errors = {};
})
.catch(error => {
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
console.log('Still not saved');
});
},
},
}
</script>
I am getting this error "Access to XMLHttpRequest at 'http://localhost/api/auth/register' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
<template>
<div class="container mt-2">
<form autocomplete="off" #submit.prevent="register" method="post">
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.email }">
<label for="email">E-mail</label>
<input type="email" id="email" class="form-control bg-light border-0 small" placeholder="user#example.com" v-model="email">
<span class="help-block" v-if="has_error && errors.email">{{ errors.email }}</span>
</div>
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.password }">
<label for="password">Password</label>
<input type="password" id="password" class="form-control bg-light border-0 small" v-model="password">
<span class="help-block" v-if="has_error && errors.password">{{ errors.password }}</span>
</div>
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.password }">
<label for="password_confirmation">Conform Password</label>
<input type="password" id="password_confirmation" class="form-control bg-light border-0 small" v-model="password_confirmation">
</div>
<div class="alert alert-danger" v-if="has_error && !success">
<p v-if="error == 'registration_validation_error'">Validation error</p>
<p v-else>Please fill all the fields to get registered</p>
</div>
<input type="hidden" name="_token" :value="csrf">
<div class="text-center pb-3">
<button type="submit" class="btn btn-success btn-sm" style="background-color:#00A7F5;border:none;">Register</button>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
email: '',
password: '',
password_confirmation: '',
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
has_error: false,
error: '',
errors: {},
success: false
}
},
methods: {
register() {
var app = this
this.$auth.register({
data: {
email: app.email,
password: app.password,
password_confirmation: app.password_confirmation
},
success: function () {
app.success = true
},
error: function (res) {
app.has_error = true
app.error = res.response.error
app.errors = res.response.errors || {}
}
})
}
}
}
</script>
if fails, response from controller
$a = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
]);
if ($a->fails())
{
return response()->json([
'status' => 'error',
'errors' => $a->errors()
], 422);
}
if everything ok then
return response()->json(['status' => 'success'], 200);
Please let me know whats wrong with this and is there any better way to handle error. Please share link then, i am not able to handle error correctly.
All helps are appreciated.
CORS policy checks strictly on domain plus port. So make both the same will be the solution.
You need to add CORS Service Provider to your project, like this: https://github.com/barryvdh/laravel-cors
I have an AJAX request to add form fields in a database, but got issues while appending the new entry in my select list.
Here's the HTML
<select id="jform_proprietaire" name="jform[proprietaire]">
<option value="8">Hello World</option>
<option value="35">Jon Jon</option>
<option value="9">Jack Jonhson</option>
</select>
The Form in modal :
<div id="myModal" class="modal hide fade in" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="false" style="display: block;">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Ajouter un proprietaire</h3>
</div>
<div class="modal-body">
<form method="post" name="adminForm" id="propritaire-form">
<fieldset class="adminform">
<div class="resultats"></div>
<div class="control-group">
<div class="control-label"><label id="nom-lbl" for="nom" aria-invalid="false">
Nom</label>
</div>
<div class="controls"><input type="text" name="nom" id="nom" value=""></div>
</div>
<div class="control-group">
<div class="control-label"><label id="prenom-lbl" for="prenom" aria-invalid="false">
Prénom</label>
</div>
<div class="controls"><input type="text" name="prenom" id="prenom" value=""></div>
</div>
<div class="control-group">
<div class="control-label"><label id="societe-lbl" for="societe" aria-invalid="false">
Société</label>
</div>
<div class="controls"><input type="text" name="societe" id="societe" value=""></div>
<div class="control-group">
<div class="control-label"><label id="email-lbl" for="email" aria-invalid="false">
Email</label>
</div>
<div class="controls"><input type="email" name="email" class="validate-email" id="email" value=""></div>
</div>
</fieldset>
<input type="hidden" name="6f179ffa2a28133151f3cfe1553978e3" value="1">
</form>
</div>
<div class="modal-footer">
<a id="enregistrerproprio" class="btn btn-primary">Enregistrer</a>
</div>
</div>
And the script :
jQuery(document).ready(function(){
jQuery('#myModal').on('shown', function () {
jQuery('#enregistrerproprio').click(function(){
form=jQuery('#propritaire-form')
jQuery('#propritaire-form .resultats').html('<div class=\"progress progress-striped\"><div class=\"bar\" style=\"width: 30%;\"></div></div>');
jQuery.ajax({
type: 'POST',
url: 'index.php?option=com_visites&task=ajax.ajouteProprietaire&format=raw',
data: form.serializeArray(),
dataType: 'json',
success: function(data) {
jQuery('#propritaire-form .resultats').empty();
if(data.succes==1){
jQuery('#myModal').modal('hide');
jQuery('#jform_proprietaire').append('<option selected=\"true\" value=\"'+data.proprietaire.id+'\">'+data.proprietaire.nom+' '+data.proprietaire.prenom+'</option>');
} else {
jQuery('#propritaire-form .resultats').html('<div class=\"alert alert-error\"></div>');
for (i=0;i<data.retour.length;i++){
jQuery('#propritaire-form .resultats .alert').append('<p>'+data.retour[i].message+'</p>')
}
}
}
});
})
})
})
My data is well imported to the database but I have in console :
Uncaught TypeError: Cannot read property 'id' of null
at Object.success (index.php?option=com_jea&view=property&layout=edit&id=344:60)
at i (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:2)
at Object.fireWith [as resolveWith] (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:2)
at y (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:4)
at XMLHttpRequest.c (jquery.min.js?7c0336fabba01bb5fea27139dbdfd8c1:4)
For this line :
jQuery('#jform_proprietaire').append('<option selected=\"true\" value=\"'+data.proprietaire.id+'\">'+data.proprietaire.nom+' '+data.proprietaire.prenom+'</option>');
If someone could help would be great!!
Thanks in advance !
PS : I ommited to show the php ajouteproprietairefunction :
class VisitesControllerAjax extends JControllerAdmin
{
public function ajouteProprietaire(){
require_once JPATH_ADMINISTRATOR.'/components/com_visites/models/propritaire.php';
$input = JFactory::getApplication()->input;
$data=$input->getArray(array('nom' => '', 'prenom' => '', 'societe' => '','email' => '', 'telephone' => '', 'mobile' => '','adresse' => '', 'codepostal' => '', 'ville' => '', 'notes' => ''));
$data["state"]=1;
$model=new VisitesModelPropritaire();
$reussite=$model->save($data);
if ($reussite) {
$db= JFactory::getDbo();
$query=$db->getQuery(true);
$query->select('*')
->from('#__visites_proprio')
->where('id='.$db->insertid());
$db->setQuery($query);
$proprietaire=$db->loadObject();
echo json_encode(array('succes'=>1, 'proprietaire'=>$proprietaire));
} else {
echo json_encode(array('succes'=>0, 'retour'=>JFactory::getApplication()->getMessageQueue()));
}
}
}
Ok found the solution....
In the latest version of MySql the Last Insert ID isn't working very well.
So I changed my function to check on the email field since It's Unique for each user, Here's the updated code :
if ($reussite) {
$db= JFactory::getDbo();
$query=$db->getQuery(true);
$query->select('*');
$query->from('#__visites_proprio');
$query->where('email = \''.$data['email'].'\'');
$db->setQuery($query);
$proprietaire=$db->loadObject();
echo json_encode(array('succes'=>1, 'proprietaire'=>$proprietaire));
} else {
echo json_encode(array('succes'=>0, 'retour'=>JFactory::getApplication()->getMessageQueue()));
}