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()));
}
Related
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..
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);
}
In Livewire component i have a form inside the modal to edit the information.
When I click on the button, the modal will open and display the item information inside the inputs.
The problem is that if one or all of the inputs do not change their value and the edit button is clicked, it gives the following error that says the values are empty!!. And the inputs must be changed so that there are no errors
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'network' cannot be null (SQL: update `networks` set `network` = ?, `networkName` = ?, `address` = ?, `address_regex` = ?, `tag_memo` = ?, `tag_regex` = ?, `min_withdraw` = ?, `max_withdraw` = ?, `fee` = ?, `deposit` = inactive, `withdraw` = inactive, `networks`.`updated_at` = 2021-06-09 10:18:52 where `id` = 8)
component code:
<?php
namespace App\Http\Livewire\Backend\Currency;
use App\Models\Network;
use Livewire\Component;
class Networks extends Component
{
protected $listeners = ['refreshNetwork' => '$refresh'];
public $confirming;
public $editId;
public $networkEdit;
public $networkNameEdit;
public $address_networkEdit;
public $address_regexEdit;
public $tag_memo_networkEdit;
public $tag_regexEdit;
public $min_withdrawEdit;
public $max_withdrawEdit;
public $feeEdit;
public $depositEdit = false;
public $withdrawEdit = false;
public function editForm($id,$action)
{
if ($network = Network::where('id' , $id)->first()) {
$this->editId = $id;
$this->dispatchBrowserEvent('editNetworkModal', $networkData = [
'network' => $network->network,
'networkName' => $network->networkName,
'address_network' => $network->address,
'address_regex' => $network->address_regex,
'tag_memo_network' => $network->tag_memo_network,
'tag_memo_regex' => $network->tag_memo_regex,
'min_withdraw' => $network->min_withdraw,
'max_withdraw' => $network->max_withdraw,
'fee' => $network->fee ,
'deposit' => $network->deposit,
'withdraw' => $network->withdraw,
]);
}else{
$this->alert('warning', 'شبکه مورد نظر پیدا نشد !', [
'position' => 'center',
'timer' => 2000,
'toast' => false,
'text' => '',
'confirmButtonText' => 'خب',
'cancelButtonText' => 'خب',
'showCancelButton' => false,
'showConfirmButton' => false,
]);
}
}
public function Update($action)
{
if ($action == 'edit')
{
Network::where('id' , $this->editId)->update([
'network' => $this->networkEdit,
'networkName' => $this->networkNameEdit,
'address' => $this->address_networkEdit,
'address_regex' => $this->address_regexEdit,
'tag_memo' => $this->tag_memo_networkEdit,
'tag_regex' => $this->tag_regexEdit,
'min_withdraw' => $this->min_withdrawEdit,
'max_withdraw' => $this->max_withdrawEdit,
'fee' => $this->feeEdit,
'deposit' => $this->depositEdit == false ? 'inactive' : 'active',
'withdraw' => $this->withdrawEdit== false ? 'inactive' : 'active',
]);
$this->emit('refreshNetwork');
$this->dispatchBrowserEvent('hideEditNetworkModal');
$this->alert('success', 'شبکه با موفقیت ویرایش شد.', [
'position' => 'center',
'timer' => 2000,
'toast' => false,
'text' => '',
'confirmButtonText' => 'خب',
'cancelButtonText' => 'خب',
'showCancelButton' => false,
'showConfirmButton' => false,
]);
}
}
public function render()
{
return view('livewire.backend.currency.networks');
}
}
modal:
<div wire:key="B" class="modal fade" tabindex="-1" id="editNetworkModal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">ویرایـش شبکـه انتقال</h5>
<a href="#" class="close" data-dismiss="modal" aria-label="Close">
<em class="icon ni ni-cross"></em>
</a>
</div>
<div class="modal-body">
<form action="#" class="form-validate is-alter">
<div class="row gy-3">
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="full-name">شبکه ارز</label>
<div class="form-control-wrap">
<input wire:model.defer="networkEdit" type="text" class="form-control" placeholder="مثال : BNB" id="networkEdit" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="email-address">نام شبکه</label>
<div class="form-control-wrap">
<input wire:model="networkNameEdit" id="networkNameEdit" type="text" class="form-control" placeholder="مثال: BEP20" required>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">ادرس</label>
<div class="form-control-wrap">
<input wire:model="address_networkEdit" type="text" class="form-control" id="address_networkEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">اعتبار سنجی آدرس شبکه به وسیله عبارات منظم</label>
<div class="form-control-wrap">
<input wire:model="address_regexEdit" type="text" class="form-control" id="address_regexEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">آدرس Memo یا Tag</label>
<div class="form-control-wrap">
<input wire:model="tag_memo_networkEdit" type="text" class="form-control" id="tag_memo_networkEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="form-label" for="phone-no">اعتبار سنجی Memo شبکه به وسیله عبارات منظم</label>
<div class="form-control-wrap">
<input wire:model="tag_regexEdit" type="text" class="form-control" id="tag_regexEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">حداقل برداشت</label>
<div class="form-control-wrap">
<input wire:model="min_withdrawEdit" type="text" class="form-control" id="min_withdrawEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">حداکثر برداشت</label>
<div class="form-control-wrap">
<input wire:model="max_withdrawEdit" type="text" class="form-control" id="max_withdrawEdit">
</div>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="form-label" for="phone-no">کارمزد برداشت</label>
<div class="form-control-wrap">
<input wire:model="feeEdit" type="text" class="form-control" id="feeEdit">
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="custom-control custom-switch">
<input wire:model="depositEdit" type="checkbox" class="custom-control-input" id="depositEdit">
<label class="custom-control-label" for="deposit">واریـز به این آدرس</label>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<div class="custom-control custom-switch">
<input wire:model.defer="withdrawEdit" type="checkbox" class="custom-control-input" id="withdrawEdit">
<label class="custom-control-label" for="withdraw">برداشت به این آدرس</label>
</div>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer bg-light">
<button wire:click="Update('edit')" class="btn btn-round btn-outline-primary ">
<div wire:loading wire:target="Update">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
</div>
<span class="w-100px">ویرایـش شبکـه</span>
</button>
<button data-dismiss="modal" aria-label="Close" class="btn btn-round btn-outline-secondary w-90px"><span>بستن</span></button>
</div>
</div>
</div>
</div>
and js code to set value for inputs and open modal:
window.addEventListener('editNetworkModal', event => {
$("#editNetworkModal").modal('show');
$('#networkEdit').val(event.detail.network);
$('#networkNameEdit').val(event.detail.networkName);
$('#address_networkEdit').val(event.detail.address_network);
$('#address_regexEdit').val(event.detail.address_regex);
$('#tag_memo_networkEdit').val(event.detail.tag_memo_network);
$('#tag_regexEdit').val(event.detail.tag_regex);
$('#min_withdrawEdit').val(event.detail.min_withdraw);
$('#max_withdrawEdit').val(event.detail.max_withdraw);
$('#feeEdit').val(event.detail.fee);
$('#depositEdit').val(event.detail.deposit);
$('#withdraw').val(event.detail.withdraw);
console.log(event.detail)
});
$this->dispatchBrowserEvent('editNetworkModal', $networkData = [
'network' => $network->network,
One of the goals of Livewire, is forget about JS for this kind of things. Binding the property with wire:model you don't need at all use JS, even pass this db information through the event. With a simple method that retrieve the data from db and assign it to the public properties is enough for you get this in frontend
public function editForm($id,$action)
{
$this->getModelData($id);
$this->dispatchBrowserEvent('openEditModal');
}
public function getModelData($modelId)
{
$model = Model::find($modelId);
$this->property1 = $model->property1;
//......
}
I'm using laravel and trying to save data using post through ajax but data is not saved in database. I'm getting following error: jquery.min.js:2 POST http://localhost:8000/admin/products/attributes/add 500 (Internal Server Error). My code is as follows:
view:
<script>
$("#add_attributes_info").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success'+msg);
}
});
});
</script>
<form action="#" id="frmattributes" method="POST">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price"/>
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
Controller:
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->data);
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
You should use:
$productAttribute = ProductAttribute::create($request->all());
However you should keep in mind this is very risky without validation.
You should add input validation and then use:
$productAttribute = ProductAttribute::create($request->validated());
Use $request->all();
public function addAttribute(Request $request)
{
$productAttribute = ProductAttribute::create($request->all());
if ($productAttribute) {
return response()->json(['message' => 'Product attribute added successfully.']);
} else {
return response()->json(['message' => 'Something went wrong while submitting product attribute.']);
}
}
PS : I made some changes to get it works
Hope this help
<head>
<title></title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function submitForm() {
$.ajax({
type: "POST",
url: '../admin/products/attributes/add',
data: $('#frmattributes').serialize(),
success: function(msg) {
console.log('success' + msg);
}
});
}
</script>
</head>
<body>
<form id="frmattributes">
<h3 class="tile-title">Add Attributes To Product</h3>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label for="values">Select an value <span class="m-l-5 text-danger"> *</span></label>
<select id="attribute_values" name="value" class="form-control custom-select mt-15">
</select>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="quantity">Quantity</label>
<input class="form-control" name="quantity" type="number" id="quantity" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label" for="price">Price</label>
<input class="form-control" name="price" type="text" id="price" />
<small class="text-danger">This price will be added to the main price of product on frontend.</small>
</div>
</div>
<div class="col-md-12">
<button class="btn btn-sm btn-primary" id="add_attributes_info" type="button" onclick="submitForm()">
<i class="fa fa-plus"></i> Add
</button>
</div>
</div>
</form>
</body>
</html>
So in the controller, change the $request->data with :
$productAttribute = ProductAttribute::create($request->all());
or also check what the request contains, before creating you can check using:
dd($request->all());
what im trying to do is Im trying to upload an image to database but I dont know what is the reason why I've got an error like
Message: Undefined index: userfile
Message: Undefined variable: images
in my view. as you can see the name of the input file set as an array same as other tutorial
<!-- Bootstrap modal -->
<div class="modal fade" id="modal_form" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Person Form</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">First Name</label>
<div class="col-md-9">
<input name="firstName" placeholder="First Name" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Image</label>
<div class="col-md-9">
<input type="file" name="userfile[]" id="file" class="form-control">
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Gender</label>
<div class="col-md-9">
<select name="gender" class="form-control">
<option value="">--Select Gender--</option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Address</label>
<div class="col-md-9">
<textarea name="address" placeholder="Address" class="form-control"></textarea>
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date of Birth</label>
<div class="col-md-9">
<input name="dob" placeholder="yyyy-mm-dd" class="form-control datepicker" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- End Bootstrap modal
in my controller.
public function image()
{
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']); //this is line that has an error, the Message: Undefined index: userfile
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
}
$fileName = implode(',',$images); // the line that has an error, Message: Undefined variable: images
return $fileName;
}
public function ajax_add()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
//'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
'image' => $this->input->post($this->image()),
);
$insert = $this->person->save($data);
echo json_encode(array("status" => TRUE));
}
private function set_upload_options()
{
// upload an image options
$config = array();
$config['upload_path'] = './upload/'; //give the path to upload the image in folder
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['overwrite'] = FALSE;
return $config;
}
public function ajax_update()
{
$this->_validate();
$data = array(
'firstName' => $this->input->post('firstName'),
// 'lastName' => $this->input->post('lastName'),
'gender' => $this->input->post('gender'),
'address' => $this->input->post('address'),
'dob' => $this->input->post('dob'),
);
$this->person->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE));
}
I want to insert that image name to my database but that errors block me to do that... need help.
In your Ajax Request Please add
$("#form").submit(function(e){
e.preventDefault();
var fd = new FormData();
$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
return xhrobj;
},
data: formData,
So on....
//ajax close
});
And DOnt Forgot to use
enctype="multipart/form-data"
On form tag...And You will be fine
For Undefined variable: images
Please put
$images = array();// just before for loop.
$cpt = count($_FILES['userfile']);