Why i am getting 'No Access-Control-Allow-Origin' - laravel

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

Related

Validation on clonned fields in vue js and laravel

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..

Array to String conversion error while trying to do a single file upload in Laraver using AJAX

I'm having form which submits one file and certain texts through AJAX, only problem is with the file upload through AJAX. The form dats is being submitted through FormData instance but getting an Array to String conversion error while trying to save the file.
I'm attaching the scripts below.
Controller:
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'contact_number' => 'required|numeric',
'email' => 'required',
'total_exp' => 'required|numeric',
'skillsets' => 'required',
'current_organization' => '',
'remarks' => '',
'file_name' => 'required|max:2048'
],
[
'name' => 'This field is mandatory',
'contact_number' => 'This field is mandatory',
'email' => 'This field is mandatory',
'total_exp' => 'This field is mandatory',
'skillsets' => 'This field is mandatory',
'total_exp.numeric' => 'Only numberic values allowed',
'contact_number.numeric' => 'Only numberic values allowed'
]);
//try{
$career = CareerForm::updateOrCreate([
'name'=>$request->name,
'contact_number'=>$request->contact_number,
'email'=>$request->email,
'total_exp'=>$request->total_exp,
'skillsets'=>$request->skillsets,
'current_organization'=>$request->current_organization,
'remarks'=>$request->remarks,
'file_name' => $request->file_name,
]);
//if(request()->hasFile('file_name')){
$file=$request->file('file_name');
$fname = rand().'.'.$file('file_name')->getClientOriginalName().'.'.$file('file_name')->getClientOriginalExtension();
$file->move(public_path('documents'),$fname);
//$file->move(public_path('uploads'), $fname);
//$request->file->move(public_path('uploads'), $fileName);*/
/*$file = $request->file('file_name')->store('public/documents');
Storage::disk('local')->put($request->file($request->file)->getClientOriginalName(), 'Contents');*/
//}catch(Exception $e1){echo $e1;}
return response()->json([
"success" => true,
]);
View:
#extends('layouts.app')
#section('content')
<h2>Career Form using AJAX</h2>
<form class="form-signin" id="form_todo" enctype="multipart/form-data">
<h1 class="h3 mb-3 font-weight-normal">Career Form</h1>
<label for="inputEmail" class="sr-only">Name</label>
<input name="name" type="text" id="inputName" class="form-control" placeholder="Name" required="" autofocus="">
#error('name')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Contact Number</label>
<input name="contact_number" type="" id="c_n" class="form-control" placeholder="Contact Number" required="" autofocus="">
#error('contact_number')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Email</label>
<input name="email" type="text" id="eml" class="form-control" placeholder="Email" required="" autofocus="">
#error('email')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Total Experience</label>
<input name="total_exp" type="" id="exp" class="form-control" placeholder="Total Experience" required="" autofocus="">
#error('total_experience')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Skillsets</label>
<input name="skillsets" type="text" id="skl" class="form-control" placeholder="Skillsets" required="" autofocus="">
#error('skillsets')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Curent Organization</label>
<input name="current_organization" type="text" id="c_o" class="form-control" placeholder="Current Organizations (Optional)" autofocus="">
#error('current_organization')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<label for="" class="sr-only">Remarks</label>
<input name="remarks" type="text" id="rem" class="form-control" placeholder="Remarks (Optional)" autofocus="">
#error('remarks')
<div class="text-red-500 mt-2 text-sm">
{{$message}}
</div>
#enderror
<input type="file" id="file_id" name="file_name[]" class="form-control">
<!--<button type="button" id="btnFile" class="btn btn-primary">Submit File</button>-->
<button class="btn btn-primary btn-block" id="career_btn" type="submit">Submit</button>
</form>
<p class="mt-5 mb-3 text-muted">Done by Debajyoti Das</p>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
$("#form_todo").on('submit',function(e) {
//$("#career_btn").click(function(e) {
e.preventDefault();
//var formData = new FormData($(this)[0]);
//var files = $("#file_id")[0].files;
var formData = new FormData(this);
//formData.append('file_id',files[0]);
$.ajax({
type: 'POST',
url: "career/store",
data: formData,
datatype: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function(data) {
}
});
});
</script>
#endsection
JSON error message: Array to string conversion
Any help will be appreciated.
On your server You have accepted an array of files.
$files=$request->file('file_name');
foreach ($files as file) {
$fname = rand().'.'.$file->getClientOriginalName().'.'.$file->getClientOriginalExtension();
$file->move(public_path('documents'),$fname);
}

Laravel & Vue.js Form Validation Errors

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>

How to update more table rows at once using Laravel and Vuejs?

I have settings table with 3 columns (id, property, content).
I have seeded some data into settings table and I want to update this table. I am filling some form where each input is presenting one row of the table settings. After submitting that form, I want my table to be updated...
For example, some of my property-content pairs (some of my inputs in this form) are:
background_image - 'image.jpg'
header - 'this is the header'
I am confused because I don't really know what should I send to backend and also I am not sure what should endpoint be...
I hope some of you can help me. If you need more questions, be free to ask me. Thanks in advance, and here is my code:
SettingsController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Requests\UpdateSettings;
use App\Http\Resources\SettingResource;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Setting;
class SettingController extends Controller
{
public function index()
{
$settings = Setting::all();
return SettingResource::collection($settings);
}
public function store(Request $request)
{
//
}
public function show($id)
{
//
}
public function update(UpdateSettings $request, Setting $setting)
{
$setting->where('property', $request->property)
->update([ 'content' => $request->content ]);
return new SettingResource($setting);
}
public function destroy($id)
{
//
}
}
Settings.vue
<template>
<div class="ml-4 container">
<button #click="submit" id="saveBtn" class="btn btn-primary mt-2">Save Admin Settings</button>
<div class="custom-file mt-3">
<label for="backgroundImage" class="custom-file-label input">Add Background Image</label>
<input id="backgroundImage" #input="errors.clear('background_image')" #change="uploadImageName" type="file" class="custom-file-input btn btn-primary"
style="background: #1d68a7">
<span class="text-danger" v-if="errors.get('background_image')">{{ errors.get('background_image') }}</span>
</div>
<div class="form-group mt-3">
<label for="header">Header</label>
<input :class="{'is-invalid' : errors.get('header')}" #input="errors.clear('header')" v-model="form.header" type="text" class="form-control input" id="header">
<span class="text-danger" v-if="errors.get('header')">{{ errors.get('header') }}</span>
</div>
<div class="form-group mt-3">
<label for="videoOne">Video one</label>
<textarea :class="{'is-invalid' : errors.get('video')}" #input="errors.clear('video')" v-model="form.video" type="text" class="form-control videoBox input" id="videoOne"></textarea>
<span class="text-danger" v-if="errors.get('video')">{{ errors.get('video') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_video"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="mt-3">
<label for="sectionOneText">Section One Text</label>
<editor
#input="errors.clear('section_one')"
v-model="form.section_one"
type="text"
class="form-control"
id="sectionOneText"
>
</editor>
<span class="text-danger" v-if="errors.get('section_one')">{{ errors.get('section_one') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_section_one"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="mt-3">
<label for="editableBoxContainer">Editable Box Container</label>
<editor
#input="errors.clear('editable_box')"
v-model="form.editable_box"
type="text"
class="form-control"
id="editableBoxContainer"
>
</editor>
<span class="text-danger" v-if="errors.get('editable_box')">{{ errors.get('editable_box') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_editable_box"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="mt-3">
<label for="sectionTwoText">Section Two Text</label>
<editor
#input="errors.clear('section_two')"
v-model="form.section_two"
type="text"
class="form-control"
id="sectionTwoText"
>
</editor>
<span class="text-danger" v-if="errors.get('section_two')">{{ errors.get('section_two') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_section_two"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="mt-3">
<label for="sectionThreeText">Section Three Text</label>
<editor
#input="errors.clear('section_three')"
v-model="form.section_three"
type="text"
class="form-control"
id="sectionThreeText"
>
</editor>
<span class="text-danger" v-if="errors.get('section_three')">{{ errors.get('section_three') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_section_three"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="form-group mt-3">
<label for="videoTwo">Video two</label>
<textarea :class="{'is-invalid' : errors.get('video_two')}" #input="errors.clear('video_two')" v-model="form.video_two" type="text" class="form-control videoBox input" id="videoTwo"></textarea>
<span class="text-danger" v-if="errors.get('video_two')">{{ errors.get('video_two') }}</span>
<div class="d-flex">
<toggle-button class="mt-2 toggleButton"
#click="toggleBtn()"
v-model="form.active_video_two"
color="#82C7EB"
:sync="true"
:labels="{checked: 'Active', unchecked: 'Deactive'}"
/>
</div>
</div>
<div class="form-group mt-3">
<label for="linkOne">Link One</label>
<input :class="{'is-invalid' : errors.get('link_one')}" #input="errors.clear('link_one')" v-model="form.link_one" type="text" class="form-control input" id="linkOne">
<span class="text-danger" v-if="errors.get('link_one')">{{ errors.get('link_one') }}</span>
</div>
<div class="form-group mt-3">
<label for="linkTwo">Link Two</label>
<input :class="{'is-invalid' : errors.get('link_two')}" #input="errors.clear('link_two')" v-model="form.link_two" type="text" class="form-control input" id="linkTwo">
<span class="text-danger" v-if="errors.get('link_two')">{{ errors.get('link_two') }}</span>
</div>
</div>
</template>
<script>
import Editor from '#tinymce/tinymce-vue'
import {ToggleButton} from 'vue-js-toggle-button'
import Errors from "../helpers/Errors";
Vue.component('ToggleButton', ToggleButton)
export default {
name: "Settings",
components: {Editor},
data() {
return {
errors: new Errors(),
form: {
background_image: '',
header: '',
video: '',
active_video: null,
section_one: '',
active_section_one: null,
editable_box: '',
active_editable_box: null,
section_two: '',
active_section_two: null,
section_three: '',
active_section_three: null,
video_two: '',
active_video_two: null,
link_one: '',
link_two: '',
},
}
},
mounted() {
},
methods: {
toggleBtn() {
if (this.sectionTwotext) {
this.sectionTwotext = false;
} else {
this.sectionTwotext = true;
}
},
async submit() {
try {
const form = Object.assign({}, this.form);
console.log(form);
let result = Object.keys(form).map(function (key) {
return [key, form[key]];
});
console.log(result[0])
result._method = 'PUT';
for(let i=0; i<=15; i++) {
let objectResult = Object.assign({}, result[i]);
console.log('objectResult')
console.log(objectResult)
objectResult._method = 'PUT';
const {data} = await axios.post(`/api/setting/${i}`, objectResult);
}
} catch (error) {
console.log(error.response.data.errors);
this.errors.record(error.response.data.errors);
}
},
uploadImageName() {
let image = document.getElementById("backgroundImage");
this.form.background_image = image.files[0].name;
console.log(image.files[0].name);
},
}
}
</script>
<style scoped>
#saveBtn {
border-radius: 0;
}
.input {
border-radius: 0;
}
.videoBox {
height: 300px;
}
.toggleButton {
margin-left: auto;
}
</style>
My async Submit function is not OK, I was just trying something...
Thanks in advance!
I would consider having a single endpoint on your api where you submit the entire form.
api.php
Create a route that we can submit our axios request to:
Route::put('/settings', 'Api\SettingController#update')->name('api.settings.update');
Note that I have namespaced the controller as you will likely have a web and api version of this controller. Mixing your api and web actions in a single controller is not advisable.
web.php
This is a standard web route which will display a blade view containing the vue component. We pass through the settings which will then be passed to the Settings.vue component as a prop.
Route::get('/settings', 'SettingController#edit')->name('settings.edit');
edit.blade.php
<settings :settings="{{ $settings }}"></settings>
Settings.vue
axios.put('/api/settings', {
header: this.form.header,
background_image: this.form.background_image
... other fields to be submitted
})
.then(success => {
console.log(success);
})
.catch(error => {
console.log(error);
});
SettingController.php
public function edit()
{
return view('settings.edit', ['settings' => Setting::all()]);
}
Api\SettingController.php
public function update(Request $request)
{
$validator = Validator::make(
$request->all(),
[
'header' => ['required', 'string'],
'background_image' => ['required', 'string']
... other fields to be validated
]
);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()], 422);
}
foreach ($validator->validated() as $property => $content) {
Setting::where('property', $property)->update(['content' => $content]);
}
return response()->json(['success' => true], 200);
}
You might want to consider splitting settings into groups and submitting groups rather than the entire form, or submitting each setting individually (where it makes sense to do so).

AJAX response issue in modal

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()));
}

Resources