My form is like this
I'm working on a project and I would like to know which is the best way to showing the data after having to insert a record on the database having a complex structure HTML between using the structure in Laravel or jQuery.
I'm building a system of jobs. When the user writes the post and publishes it a call ajax triggers the function Laravel and it inserts the information on the database. until here all OK, but then I have to display the message insert on the wall of the user, so did not work.
<form id="job-store" method="post">
<input type="hidden" value="{{ route('job.store') }}" name="url" />
#csrf
<div class="row">
<div class="col-md-6 mb-3">
<label for="employment_type">نوع استخدام</label>
<select class="form-control selectpicker" title="چیزی انتخاب نشده است" id="employment_type" name="employment_type">
<option value="حق التدریس">حق التدریس</option>
<option value="رسمی">رسمی</option>
<option value="پیمانی">پیمانی</option>
<option value="قراردادی">قراردادی</option>
</select>
</div>
<div class="col-md-6 mb-3">
<label for="job_type">عنوان شغلی</label>
<select class="form-control selectpicker" title="چیزی انتخاب نشده است" id="job_type" name="job_type">
<option value="مربی درون سازمانی">مربی درون سازمانی</option>
<option value="مربی حق التدریس">مربی حق التدریس</option>
<option value="صنعتکار">صنعتکار</option>
<option value="مدرس دانشگاه">مدرس دانشگاه</option>
<option value="استادکار مهارتی">استادکار مهارتی</option>
<option value="سایر">سایر</option>
</select>
</div>
<div class="col-md-6 mb-3">
<label for="history">سابقه (سال)</label>
<input type="text" class="form-control" id="history" name="history">
</div>
<div class="col-md-6 mb-3">
<label for="post_title">عنوان پست</label>
<input type="text" class="form-control" id="post_title" name="post_title">
</div>
<div class="col-md-6 mb-3">
<label for="state">استان محل خدمت</label>
<input type="text" class="form-control" id="state" name="state">
</div>
<div class="col-md-6 mb-3">
<label for="city">شهر محل خدمت</label>
<input type="text" class="form-control" id="city" name="city">
</div>
<div class="col-md-6 mb-3">
<label for="start_date">تاریخ شروع به كار</label>
<date-picker type="date" id="start_date" name="start_date"></date-picker>
</div>
<div class="col-md-6 mb-3">
<label for="end_date">تاریخ خاتمه كار</label>
<date-picker type="date" id="end_date" name="end_date"></date-picker>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<button type="submit" class="btn btn-success job-store"><i class="fas fa-plus fa-xs"></i> افزودن</button>
</div>
</div>
</form>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>ردیف</th>
<th>نوع استخدام</th>
<th>تاریخ شروع کار</th>
<th>تاریخ خاتمه کار</th>
<th>استان محل خدمت</th>
<th>شهر محل خدمت</th>
<th>اکشن</th>
</tr>
</thead>
<tbody id="showJobs">
</tbody>
</table>
</div>
#section('script')
<script>
$(document).ready(function (e) {
$('.job-store').on('click',(function(e) {
e.preventDefault();
var formData = new FormData($('#job-store')[0]);
let url = $('#job-store :input')[0].getAttribute('value');
$.ajax({
type:'POST',
url,
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
showJobs(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
function showJobs(data) {
let html = '';
$.each(data, function (key, val) {
$('#data').append("<tr>"+
"<td>"+val.id+"</td>"+
"<td>"+val.employment_type+"</td>"+
"<td>"+val.start_date+"</td>"+
"<td>"+val.end_date+"</td>"+
"<td>"+val.state+"</td>"+
"<td>"+val.city+"</td>"+
"<td>"+
'<form action="{{ route('job.destroy',+'val.id') }}" method="post">'+
'#csrf'+
'#method('DELETE')'+
'<div class="btn-group">'+
'Edit'+
'<button type="submit" class="btn btn-danger btn-sm">Delete</button>'+
'</div>'+
'</form>'+
"</td>"+
"</tr>"
)});
$('#showJobs').append(html);
}
});
</script>
#endsection
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Requests\JobRequest;
use App\Job;
use Illuminate\Http\Request;
class JobController extends Controller
{
public function store(Request $request)
{
Job::create([
'user_id' => auth()->id(),
'employment_type' => $request->employment_type,
'job_type' => $request->job_type,
'post_title' => $request->post_title,
'history' => $request->history,
'state' => $request->state,
'city' => $request->city,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
]);
return redirect()->back();
}
public function edit(Job $job)
{
return view('Home.edits.job', compact('job'));
}
public function update(Request $request, Job $job)
{
$data = [
'employment_type' => $request->employment_type,
'job_type' => $request->job_type,
'post_title' => $request->post_title,
'history' => $request->history,
'state' => $request->state,
'city' => $request->city,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
];
$job->update($data);
return redirect()->route('home');
}
public function destroy(Job $job)
{
$job->delete();
return redirect()->back();
}
}
It is my console
I get this error
Instead of appending in javascript better create view for that file and return view from controller
First controller must return view or json but it returning redirect back.
public function store(Request $request)
{
Job::create([
'user_id' => auth()->id(),
'employment_type' => $request->employment_type,
'job_type' => $request->job_type,
'post_title' => $request->post_title,
'history' => $request->history,
'state' => $request->state,
'city' => $request->city,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
]);
$jobs= Job::get();
return view('jobdetail',compact('jobs'));
}
and jobdetail blade
#foreach($jobsas $key=>$value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value->employment_type}}</td>
<td>{{$value->start_date}}</td>
<td>{{$value->end_date}}</td>
<td>{{$value->state}}</td>
<td>{{$value->city}}</td>
<td>
<form action={{ route('job.destroy',$value->id) }} method=post>
#csrf
#method('DELETE')
<div class=btn-group>
<a href={{ route('job.edit',$value->id) }} class=btn btn-info btn-sm>Edit</a>
<button type=submit class=btn btn-danger btn-sm>Delete</button>
</div>
</form>
</td>
</tr>
#endforeach
and in JavaScript
$.ajax({
type:'POST',
url,
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
$('#showJobs').html(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
Also if you want to append last created job detail then
public function store(Request $request)
{
$job=Job::create([
'user_id' => auth()->id(),
'employment_type' => $request->employment_type,
'job_type' => $request->job_type,
'post_title' => $request->post_title,
'history' => $request->history,
'state' => $request->state,
'city' => $request->city,
'start_date' => $request->start_date,
'end_date' => $request->end_date,
]);
return view('jobdetail',compact('job'));
}
then in view jobdetail
<tr>
<td>{{$job->id}}</td>
<td>{{$job->employment_type}}</td>
<td>{{$job->start_date}}</td>
<td>{{$job->end_date}}</td>
<td>{{$job->state}}</td>
<td>{{$job->city}}</td>
<td>
<form action={{ route('job.destroy',$job->id) }} method=post>
#csrf
#method('DELETE')
<div class=btn-group>
<a href={{ route('job.edit',$job->id) }} class=btn btn-info btn-sm>Edit</a>
<button type=submit class=btn btn-danger btn-sm>Delete</button>
</div>
</form>
</td>
</tr>
and in JavaScript
$.ajax({
type:'POST',
url,
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
$('#showJobs').append(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
Related
Having Problem with POST Request
All the get routes are working fine.
Post route when submiting any form it gets updated in DB and then redirected to homepage but where I go back to previous link. I see that I am having all the success and errors on that page before getting redirected to homepage.
My POST Route:
Route::post('/update-faq', 'FaqController#update')->name('admin.faq.update');
My Controller Function:
public function index(){
$all_faqs = Faq::all();
return view('backend.pages.faqs')->with(['all_faqs' => $all_faqs]);
}
public function update(Request $request){
$this->validate($request,[
'title' => 'required|string',
'description' => 'required|string',
'status' => 'nullable|string|max:191',
]);
Faq::find($request->id)->update([
'title' => $request->title,
'description' => $request->description,
'status' => $request->status,
'is_open' => !empty($request->is_open) ? 'on' : '',
]);
return redirect()->back()->with(['msg' => 'Faq Updated...','type' => 'success']);
}
My View:
<div class="modal fade" id="faq_item_edit_modal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">{{ 'Edit Faq Item' }}</h5>
<button type="button" class="close" data-dismiss="modal"><span>×</span></button>
</div>
<form action="{{ route('admin.faq.update') }}" id="faq_edit_modal_form" enctype="multipart/form-data"
method="post">
<div class="modal-body">
#csrf
<input type="hidden" name="id" id="faq_id" value="">
<div class="form-group">
<label for="edit_title">{{ 'Title' }}</label>
<input type="text" class="form-control" id="edit_title" name="title"
placeholder="{{ 'Title' }}">
</div>
<div class="form-group">
<label for="edit_is_open">{{ 'Is Open' }}</label>
<label class="switch">
<input type="checkbox" name="is_open" id="edit_is_open">
<span class="slider"></span>
</label>
</div>
<div class="form-group">
<label for="edit_description">{{ 'Description' }}</label>
<textarea name="description" id="edit_description" cols="30" rows="10"
class="form-control max-height-150" placeholder="{{ 'Description' }}"></textarea>
</div>
<div class="form-group">
<label for="edit_status">{{ 'Status' }}</label>
<select name="status" id="edit_status" class="form-control">
<option value="publish">{{ 'Publish' }}</option>
<option value="draft">{{ 'Draft' }}</option>
</select>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">{{ 'Close' }}</button>
<button type="submit" class="btn btn-primary">{{ 'Save Changes' }}</button>
</div>
</form>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$(document).on('click', '.faq_edit_btn', function() {
var el = $(this);
var id = el.data('id');
var title = el.data('title');
var form = $('#faq_edit_modal_form');
form.find('#faq_id').val(id);
form.find('#edit_title').val(title);
form.find('#edit_description').val(el.data('description'));
form.find('#edit_status option[value="' + el.data('status') + '"]').attr('selected', true);
if (el.data('is_open') != '') {
form.find('#edit_is_open').attr('checked', true);
} else {
form.find('#edit_is_open').attr('checked', false);
}
});
});
</script>
I am doing a simple insert in laravel 7 using ajax, here the validation is working properly but the success result is not working or showing propoerly.
The routes are
// Product Poutes
Route::get('create/product', 'Product\ProductController#create')->name('createProduct');
Route::post('store/product', 'Product\ProductController#store')->name('storeProduct');
The Model is
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
//
protected $fillable = [
'name', 'category_id','sell_price','purchase_price',
];
}
The Controller code
public function store(Request $request)
{
$validation = Validator::make(
$request->all(),
[
'name' => 'required|unique:products|max:120|min:4',
'category_id' => 'required',
'sell_price' => 'required',
'purchase_price' => 'required'
]
);
if ($validation) {
return response()->json(['error' => $validation->errors()->all()]);
}
$product = new Product;
$product->name = $request->name;
$product->category_id = $request->category_id;
$product->sell_price = $request->sell_price;
$product->purchase_price = $request->purchase_price;
$product->save();
return response()->json(['success' => "New Product Added!"]);
}
The Blade form
#extends('layouts.newApp')
<!-- Product create -->
#section('content')
<!-- Begin Page Content -->
<div class="container">
<!-- Page Heading -->
<h1 class="h3 mb-4 text-gray-800">Create Product</h1>
<div class="row">
<form method="POST">
#csrf
<div class="row justify-content-center">
<div class="form-group col-md-10">
<div id="div-error" class="col-md-10 justify-content-center">
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
</div>
</div>
<div class="form-group col-md-10">
<label for="category">Category</label>
<select id="category_id" class="form-control custom-select" name='category_id'>
<option selected>Choose...</option>
#foreach ($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-10">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" placeholder="Product Name" name='name'>
</div>
<div class="form-group col-md-5">
<label for="sell_price">Notes</label>
<input type="number" class="form-control" id="sell_price" placeholder="sell_price"
name='sell_price'>
</div>
<div class="form-group col-md-5">
<label for="purchase_price">Notes</label>
<input type="number" class="form-control" id="purchase_price" placeholder="purchase_price"
name='purchase_price'>
</div>
<div class="form-group col-md-10">
<button class="btn btn-primary btn-submit" type="submit">Submit</button>
</div>
</div>
</form>
</div>
</div>
<script>
$(document).ready(function() {
$(".btn-submit").click(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': jQuery('meta[name="csrf-token"]').attr('content')
}
});
var category_id = document.getElementById("category_id").value;
var name = $("input[name=name]").val();
var sell_price = $("input[name=sell_price]").val();
var purchase_price = $("input[name=purchase_price]").val();
$.ajax({
type: 'POST',
url: "{{ route('storeProduct') }}",
dataType: 'json',
data: {
category_id: category_id,
name: name,
sell_price: sell_price,
purchase_price: purchase_price
},
success: function(data) {
if ($.isEmptyObject(data.error)) {
alert(data.success);
} else {
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function(key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
});
</script>
#endsection
The validation is working fine:
But after I add data and press submit it returns undefined type:
I tried all sort of possible method found non.
Hope to sort out the problem very soon.
may be you are getting some error in your response.why dont you check your ajax hit in inspect element to see what its returning i think its returning some php error or something else or you data in json maybe
I wrote a code to submit a form without page refresh in laravel and here's my codes :
my view :
<form action="{{ url('/admin/products/new') }}" method="post">
{{ csrf_field() }}
<div class="form-group row">
<label for="example-text-input" class="col-sm-2 col-form-label">pid</label>
<div class="col-sm-10">
<input type="text" id="pid" name="pid" class="form-control" placeholder="مثال : Oil distillation machine" id="name">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-sm-2 col-form-label">name</label>
<div class="col-sm-10">
<input type="text" id="name" name="name" class="form-control" placeholder="مثال : Oil distillation machine" id="name">
</div>
</div>
<div class="form-group row">
<label for="example-text-input" class="col-sm-2 col-form-label">value</label>
<div class="col-sm-10">
<input type="text" id="value" name="value" class="form-control" placeholder="مثال : Oil distillation machine" id="name">
</div>
</div>
<div class="form-group">
<button type="submit" id="submit" class="btn btn-primary btn-lg text-center waves-effect waves-light">ارسال</button> </div>
</div>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#submit').click(function(e){
e.preventDefault();
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/admin/products/new') }}",
method: 'post',
data: {
name: jQuery('#pid').val(),
email: jQuery('#name').val(),
subject: jQuery('#value').val(),
},
success: function(data){
jQuery.each(data.errors, function(key, value){
jQuery('.alert-danger').show();
jQuery('.alert-danger').append('<p>'+value+'</p>');
});
}
});
});
});
</script>
</form>
my controller :
public function add_product_post(Request $request)
{
$pid = $request->pid;
$name = $request->name;
$value = $request->value;
DB::table('product_features')->insert([
'pid' => $pid,
'name' => $name,
'value' => $value
]);
return ['message' => 'success'];
}
my problem is that when i click on submit button i just get a response in blank page {"message":"success"}
I want to submit my form without any page refreshing.
What is wrong with my code?
Thanks
In your controller action, you just return an array, plz change it to response:
public function add_product_post(Request $request)
{
$pid = $request->pid;
$name = $request->name;
$value = $request->value;
DB::table('product_features')->insert([
'pid' => $pid,
'name' => $name,
'value' => $value
]);
return response()->json(['message' => 'success']);
}
Another thing is in jquery ajax,you need to display the success message instead of the error message.
I'm not sure but try to change the button type into "button"
<button type="button" id="submit" class="btn btn-primary btn-lg text-center waves-effect waves-light">ارسال</button>
So I'm trying create data using ajax and modal box from boostrap, but my pagination not using ajax, after created data Paginate and Table Has change by using render() in laravel.. after that I click Another page.. it making error Like This.. Click Me for Look the Error
web.php
Route::prefix('ajaxCrud')->group(function () {
Route::get('', 'ajaxCrudController#index')->name('crud.index');
Route::post('add', 'ajaxCrudController#masuk')->name('crud.add');
});
Javascript / crudCustom.js
$('#form-tambah').submit(function (e) {
e.preventDefault();
$.ajax({
type: "post",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: "json",
success: function (results) {
$('#tbody-row').html(results.template.table);
$('#paginate').html(results.template.paginate);
// ajaxLoad(results.url);
history.pushState(null, null, results.url);
}
});
});
AjaxCrudController.php
siswa::create([
'name' => $req->name,
'nomor' => $req->phone,
'alamat'=> $req->address
]);
$template = [
'table' => view('ajaxCrud.ajax.table')->with(['data' => $siswa])->render(),
'paginate' => view('ajaxCrud.ajax.paginate')->with(['data' => $siswa])->render()
];
$response = [
'status' => true,
'template' => $template,
'url' => route('crud.index')
];
return response()->json($response);
index.blade.php
#foreach ($data as $item)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$item->name}}</td>
<td>{{$item->nomor}}</td>
<td>{{$item->alamat}}</td>
<td>
<a class="btn btn-success" href="#">Edit</a>
<a class="btn btn-danger" href="#">Delete</a>
</td>
</tr>
#endforeach
Paginate
<div id="paginate">
{{ $data->links() }}
</div>
Modal
<form method="post" action="{{route('crud.add')}}" id="form-tambah">
#csrf
<span id="form_output"></span>
<div class="modal-body">
<div class="form-group">
<label for="nama">Name</label>
<input type="text" name="name" class="form-control">
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="number" name="phone" class="form-control">
</div>
<div class="form-group">
<label for="address">Address</label>
<textarea name="address" class="form-control"></textarea>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-success">Add</button>
</div>
</form>
I would like to ask what are the causes of this error? When i check the inspect elements to check it out, it said console.log(xhr.status); console.log(xhr.responseText); console.log(thrownError); are my errors. what is wrong in here?
My view
<h3> Product
<span class = "fa fa-plus-square-o ">
<div class="modal fade" id="new_product" role="dialog" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add New Product</h4>
</div>
<form method="post" id="form-submit" enctype="multipart/form-data">
<!-- <form method="post" enctype="multipart/form-data" name = "select_design"action="<?php echo base_url(); ?>Administrator/new_product"> -->
<div class="modal-body">
<!-- <div class="form-group">
<label class="control-label ">Genre:</label>
<select name = "product_genre" class="select2_multiple " multiple="multiple" >
<option>Choose option</option>
<option value ="drama">Drama</option>
<option value ="action">Action</option>
<option value ="comedy">Comedy</option>
<option value ="horror">Horror</option>
</select>
</div> -->
<div class="form-group">
<label>Product Name</label>
<input type="text" class="form-control" id="product_name" name="product_name" placeholder="Name" value="<?php echo set_value('product_name'); ?>"> </div>
<div class="form-group">
<label>Product Description</label>
<input type="text" class="form-control" id="product_description" name="product_description" placeholder="Description" value="<?php echo set_value('product_description'); ?>">
</div>
<div class="form-group">
<label>Stocks</label>
<input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" value="<?php echo set_value('quantity'); ?>">
</div>
<div class="form-group">
<label>Product Image</label>
<input type="file" required class="form-control" id="userfile" name="userfile">
</div>
<div class="form-group">
<label>Product Price</label>
<input type="number" min="1" class="form-control" id="product_price" name="product_price" placeholder="Price" value="<?php echo set_value('price'); ?>">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Register</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
My js
<script>
$("#form-submit").on('submit',function(event){
// $.LoadingOverlay("show");
var form = new FormData(document.getElementById("form-submit"));
$.ajax({
url: base_url + "Administrator/new_product",
type: "POST",
data: form,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function(data) {
var result = JSON.parse(data);
//alert(data);
if(result===1)
{
swal({
type: 'success',
html: 'New Product Added',
timer: 2000,
})
setTimeout(function() {
document.location.href= base_url + "Administrator/view_products";
}, 2000);
}
else
{
swal({
type: 'error',
html: result
});
}
// $.LoadingOverlay("hide");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownError);
}
})
event.preventDefault();
});
</script>
My controller
public function new_product()
{
// $data['new_product'] = $this->AdministratorModel->getCourses();
$config['upload_path'] = './products/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048000';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
$this->form_validation->set_rules('product_name', ' Name', 'required|trim');
$this->form_validation->set_rules('product_description', ' Name', 'required|trim');
$this->form_validation->set_rules('quantity', 'stocks', 'required|trim');
$this->form_validation->set_rules('product_price', 'price', 'required|trim');
$this->form_validation->set_rules('userfile', 'image', 'callback_handle_upload');
if ($this->form_validation->run() == FALSE)
{
echo json_encode(validation_errors());
}
else
{
$products = array(
'product_name' => strip_tags($_POST['product_name']),
'product_description' => strip_tags($_POST['product_description']),
'product_category' => "Drama",
'product_quantity' => strip_tags($_POST['quantity']),
'product_image' => $this->input->post('userfile'),
'upload_data' => $this->upload->data(),
'product_price' => strip_tags($_POST['product_price'])
);
$this->AdministratorModel->addProduct($products);
echo json_encode(1);
}
}
My model
public function addProduct($products)
{
$products = array(
'product_name' => strip_tags($_POST['product_name']),
'product_description' => strip_tags($_POST['product_description']),
'product_category' => strip_tags($_POST['product_genre']),
'product_quantity' => strip_tags($_POST['quantity']),
'product_image' => $this->input->post('userfile'),
'product_image' => $this->upload->data('file_name'),
'product_price' => strip_tags($_POST['product_price'])
);
$this->db->insert('products',$products);
}