Laravel post form without refresh problem - php

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>

Related

My Laravel Website is redirecting all post request to index page

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>

Ajax response in not working properly in laravel 7

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

Laravel Error Page After Create data using ajax and boostrap

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>

Display return message for Ajax response from Laravel

I've got a working form that submits to a database from an HTML form using Laravel Collective that submits to my Controller, and it works fine.
I want to submit it without a page reload, so I'm submitting the data with AJAX.
I've got it working, and it's writing to the db, but I can't get the controller to return the response to the page on success.
The following is my script:
SCRIPT:
$(document).ready(function(){
$("#msg").hide();
$("#submit").click(function() {
$("#msg").show();
var name = $("#recipeName").val();
var description = $("#recipeDescription").val();
var token = $("#token").val();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "post",
data: "name="+name+"&description="+description,
dataType:'json',
url: "{{ route('recipes.store') }}",
success:function(data){
$("#msg").html("Recipe Saved");
$("#msg").fadeOut(2000);
}
});
})
})
HTML:
<div class="row">
<div class="col">
<p class="alert alert-success" id="msg"></p>
</div>
</div>
<div class="row">
<div class="col">
<!-- Start Form -->
<input type="hidden" name="csrf" value="{{csrf_token()}}" id="token">
<div class="form-group">
<label for="recipeName">Recipe name:</label>
<input type="text" class="form-control" id="recipeName" aria-describedby="emailHelp" placeholder="Enter recipe name">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="recipeDescription">Recipe Description:</label>
<textarea class="form-control" id="recipeDescription" rows="3" placeholder="Enter a recipe description"></textarea>
</div>
<button type="submit" class="btn btn-primary btn-block btn-lg" id="submit">Submit</button>
<!-- End Form -->
</div>
</div>
CONTROLLER:
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'description' => 'required'
]);
$recipe = new Recipe;
$recipe->name = $request->name;
$recipe->description = $request->description;
$recipe->user_id = auth()->user()->id;
$recipe->save();
return Response::json(array(
'success' => true,
'data' => $data
));
}
I can't workout what it is that I'm missing.
I'm learning AJAX on the fly (I'm learning all of it on the fly if I'm honest!), but as I say, it's writing to the db successfully, just need to notify the user of it.
SCRIPT
$("#submit").click(function() {
$("#msg").show();
var name = $("#recipeName").val();
var description = $("#recipeDescription").val();
$.ajax({
type: "post",
data: {name:name,description:description,'_token':'{{csrf_token()}}'},
dataType:'json',
url: "{{ route('recipes.store') }}",
success:function(data){
$("#msg").html("Recipe Saved");
$("#msg").fadeOut(2000);
}
});
});
HTML
change the the type of submit button from submit to button
<div class="row">
<div class="col">
<p class="alert alert-success" id="msg"></p>
</div>
</div>
<div class="row">
<div class="col">
<!-- Start Form -->
<input type="hidden" name="csrf" value="{{csrf_token()}}" id="token">
<div class="form-group">
<label for="recipeName">Recipe name:</label>
<input type="text" class="form-control" id="recipeName" aria-describedby="emailHelp" placeholder="Enter recipe name">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="recipeDescription">Recipe Description:</label>
<textarea class="form-control" id="recipeDescription" rows="3" placeholder="Enter a recipe description"></textarea>
</div>
<button type="button" class="btn btn-primary btn-block btn-lg" id="submit">Submit</button>
<!-- End Form -->
Controller
you must identify $data variable
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|max:255',
'description' => 'required'
]);
$data = 'some data';
$recipe = new Recipe;
$recipe->name = $request->name;
$recipe->description = $request->description;
$recipe->user_id = auth()->user()->id;
$recipe->save();
return Response::json(array(
'success' => true,
'data' => $data
));
}
Changing the following in the controller works correctly!
...
$recipe->save();
$data = [
'success' => true,
'message'=> 'Your AJAX processed correctly'
] ;
return response()->json($data);

cannot input textarea with CKeditor on Codeigniter

when i want to input textarea with CKeditor , the string is Null , but when i delete class="CKeditor" in textarea the string successfully filled.
i have check in controller and database but it does not matter
My Controller
function AddNews(){
$data = array(
'title_news' => $this->input->post('title_news'),
'text' => $this->input->post('text_news'),
'date' => $this->input->post('date'),
);
$insert = $this->m_news->save($data);
echo json_encode(array("status" => TRUE));
}
My View
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id_news"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title News </label>
<div class="col-md-9">
<input name="title_news" placeholder="Title Name" class="form-control" type="text"><span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Title News </label>
<div class="col-md-9">
<textarea class="ckeditor" name="text_news" rows="3" placeholder="Enter text . . . "></textarea><span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Date</label>
<div class="col-md-9">
<div class="input-group">
<input class="form-control date-picker" name="date" type="text" data-date-format="yyyy-mm-dd" placeholder="yyyy-mm-dd" /><span class="input-group-addon"><i class="fa fa-calendar bigger-110"></i></span>
</div>
</div>
</div>
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
</div>
</form>
My Ajax Input
function save()
{
var formData = new FormData($('#form')[0]);
$.ajax({
url : "<?php echo base_url('admin-spot/news/AddNews')?>",
type: "POST",
data: formData,
contentType: false,
processData: false,
dataType: "JSON",
redirect: true,
success: function(data){
if(data.status){
$('#modal_form').modal('hide');
}
else
{}
error: function (jqXHR, textStatus, errorThrown){
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
My Model
function Save($data)
{
$sql = $this->db->insert($this->table, $data);
return $sql;
}
hello guys,
when I want to input textarea with CKeditor , the string is Null , but when I delete class="CKeditor" in textarea the string successfully filled.
I have check in controller and database but it does not matter
Add this to your script
function save()
{
for (instance in CKEDITOR.instances) {
CKEDITOR.instances[instance].updateElement();
}
var formData = new FormData($('#form')[0]);
$.ajax({
....
});
}

Categories