Ajax response in not working properly in laravel 7 - php

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

Related

need to make a submit without redirect page (ajax?)

I have a view where I pull the data with an "onclick" of the "Asisgnar" button and when I click on the "Enviar formulario" button, an email is sent directly with the loaded data... this works perfectly, but I would like it to be sent the mail without redirecting me to another page.
My form code
<form action="{{route('contactanos.store')}}" method="POST">
{{ csrf_field() }}
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="inspector">Inspector</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" id="inspector" for="inspector" name="inspector" >
<option selected></option>
#foreach($users as $user)
<option value="{{ $user->name }}">{{ $user->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<label for="estado">Estado</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" id="estado" for="estado" name="estado">
<option selected></option>
<option value="Pendiente">Pendiente</option>
<option value="Coordinado">Coordinado</option>
<option value="Peritando">Derivado a inspector</option>
<option value="Baja">Baja</option>
</select>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="localidad">Localidad</label>
<input type="text" name="localidad" id="localidad" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="fechaip">Fecha IP</label>
<input type="date" name="fechaip" id="fechaip" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="siniestro">Siniestro</label>
<input type="text" name="siniestro" id="siniestro" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="inspector">Inspector</label>
<select class="form-select col-xs-12 col-sm-12 col-md-12" aria-label="Default select example" id="emailperito" for="emailperito" name="emailperito" >
<option selected></option>
#foreach($users as $user)
<option value="{{ $user->email }}">{{ $user->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="email">Email taller</label>
<input type="text" name="email" id="email" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="patente">Patente</label>
<input type="text" name="patente" id="patente" class="form-control" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<label for="modalidad">Tipo de inspección</label>
<input type="text" name="modalidad" id="modalidad" class="form-control" >
</div>
</div>
<input type="hidden" id="id">
<button type="submit" id="updateButton" class="btn btn-success" onclick="updateData(event)">Guardar</button>
<button type="submit" class="btn btn-primary float-right">Enviar formulario</button>
</form>
Controller Code to send mail
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
//mail
use App\Mail\ContactanosMailable;
use Illuminate\Support\Facades\Mail;
use App\Models\Siniestro;
class CoordinacionesController extends Controller
{
public function index(){
return view('contactanos.index');
}
public function store(Request $request){
$siniestro = Siniestro::paginate(1000);
$this->siniestro = $siniestro;
$email = $this->siniestro['emailperito'];
$cc = $this->siniestro['email'];
$correo = new ContactanosMailable($request->all());
Mail::to($email)->cc($cc)->send($correo);
return redirect()->route('siniestros.index');
}
}
View.blade
My view
I have tried removing the post method and removing the "return redirect()->route('sinisters.index');" of the controller, but it doesn't work.
you can do it with an ajax like this
$.ajax({
url: '{{route("your-route")}}',
method: "POST",
data: {
_token: '<?php echo csrf_token() ?>',
... // the rest of your form
}
})
Try this solution
add jquery in your blade file
jquery cdn
<script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
Give class to your form
<form action="{{route('contactanos.store')}}" method="POST" class="my_form">
Change your javascript code as per below
$(document).on('submit', '.my_form', function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (response) {
if(response.success){
//handle success message
} else {
//handle error message
}
},
error: function (xhr, textStatus, errorThrown) {
console.log("ERROR");
}
});
});
change your controller->store function
public function store(Request $request){
try {
$siniestro = Siniestro::paginate(1000);
$this->siniestro = $siniestro;
$email = $this->siniestro['emailperito'];
$cc = $this->siniestro['email'];
$correo = new ContactanosMailable($request->all());
Mail::to($email)->cc($cc)->send($correo);
return response()->json([
'success' => true,
'message' => 'Your success message'
]);
} catch (\Throwable $th) {
return response()->json([
'success' => false,
'message' => 'Your error message'
]);
}
}

Laravel post form without refresh problem

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>

MethodNotAllowedHttpException error in Laravel 5.7 using ajax [duplicate]

This question already has answers here:
Stop form refreshing page on submit
(20 answers)
How can I prevent refresh of page when button inside form is clicked?
(16 answers)
Closed 4 years ago.
Im trying to insert data with ajax, but i got error :
Symfony \ Component \ HttpKernel \ Exception \
MethodNotAllowedHttpException
This is my form in add-gallery.blade.php:
<form method="post" action="" enctype="multipart/form-data" autocomplete="off" class="mt-4 mb-4 card p-4">
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="gallery_name">Name</label>
</div>
<div class="col-md-6 align-self-center">
<input type="text" name="gallery_name" id="gallery_name" class="form-control" placeholder="Type Gallery Name" />
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="category">Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="category" id="category">
<option value="">Select Category</option>
<option value="Home">Home</option>
<option value="Office">Office</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="subcategory">Sub Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="subcategory" id="subcategory">
<option value="">Select Sub Category</option>
<option value="Interior">Interior</option>
<option value="Eksterior">Eksterior</option>
<option value="Decoration">Decoration</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center">
<label for="subsubcategory">Subsub Category</label>
</div>
<div class="col-md-3 align-self-center">
<select class="form-control custom-select" name="subsubcategory" id="subsubcategory">
<option value="">Select Subsub Category</option>
<option value="Room">Room</option>
<option value="Bathroom">Bathroom</option>
<option value="Kitchen">Kitchen</option>
<option value="Terrace">Terrace</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2">
<label for="gallery_image">Image</label>
</div>
<div class="col-md-10">
<div class="fileinput fileinput-new" data-provides="fileinput">
<div class="fileinput-new thumbnail w-100" style="display: none;">
<img src="http://placehold.it/1186x800" />
</div>
<div id="toAnnotate" class="fileinput-preview fileinput-exists thumbnail w-100"></div>
<div>
<span class="btn btn-xs btn-success btn-file"><span class="fileinput-new">Select image</span><span class="fileinput-exists">Change</span><input type="file" name="gallery_image" id="gallery_image"></span>
Remove
</div>
</div>
<p><small><em>Image Size : 1186px (width), 800px (height)</em></small></p>
</div>
</div>
</div>
<div class="form-group">
<div class="row">
<div class="col-md-2 align-self-center"> </div>
<div class="col-md-10 align-self-center">
<button type="button" class="btn btn-secondary">Cancel</button>
<button type="submit" class="btn btn-success" id="save">Save</button>
</div>
</div>
</div>
</form>
And below is my ajax in same page add-gallery.blade.php:
<script type="text/javascript">
$(document).ready(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
//Save
$('#save').on('click', function () {
var gallery_name = $('#gallery_name').val();
var category = $('#category').val();
var subcategory = $('#subcategory').val();
var subsubcategory = $('#subsubcategory').val();
var gallery_image = $('#gallery_image').val();
var dataSubmit = $(this).serialize();
var top = top;
var left = left;
var file_data = $('#gallery_image').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : "{{ url('galleries/store') }}",
dataType : 'text', // what to expect back from the server
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
dataType : 'json',
success: function (response) {
console.log(response);
},
error: function (response) {
console.log(response);
}
});
});
});
</script>
This is my routes file web.php:
Route::post('galleries/store','Dashboard\GalleryController#store');
And this is my controller GalleryController.php:
public function store(Request $request){
if($request->hasFile('gallery_image')){
$fileImage = $request->file('gallery_image');
$fileImageExtension = $fileImage->extension();
$renameFileImage = 'ImageGalleries'.time().'.'.$fileImageExtension;
$pathFileImage = $fileImage->storeAs('public/galleries_documents/images_galleries', $renameFileImage); /images_articles
$galleries = new Gallery;
$points = new Point;
$galleries->name = $request->gallery_name;
$galleries->category = $request->category;
$galleries->sub_category = $request->subcategory;
$galleries->sub_subcategory = $request->subsubcategory;
$galleries->image = $renameFileImage;
$galleries->lang_id = session('lang_id');
$galleries->save();
$lastInsertId = $galleries->id;
for($i = 0; $i < count($request->node); $i++) {
$node[] = [
'node_position_top' => $request->node[$i],
'node_position_left' => $request->node[$i],
'id_gallery' => $lastInsertId,
];
$points->lang_id = session('lang_id');
}
Point::insert($node); //save to table
print_r($node[]);
exit();
}
}

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

405 (Method Not Allowed) in custom URL Route Laravel 5.2

I got stuck with my ajax POST request.
My URL looks like this localhost/product/list (if a row is clicked,it will redirect to page.edit through a request like this localhost/product/list/edit/{id} )
When localhost/product/list/edit/{id} receives the edit request the response shows an error like localhost/product/list/edit/update_list 405 (Method Not Allowed).
I am confused why the URL changes from localhost/product/list/edit/{id} to localhost/product/list/edit/update_list, I mean the variable /{id} is missing.
Console always marks this part in my AJAX edit.js as an error.
$.ajax({
type:"POST",
data: {
'id': id,
'judul': judulArtikel,
'isi': isiArtikel,
// --- till the end ---
}
});
Here is my load.js which loads data from a database.
<td><a id='"+result.data[count-1].id+"'' href='list/edit/"+result.data[count-1].id+"' class='glyphicon glyphicon-pencil'></a></td>
Here is my route.php.
Route::get('list/edit/{id}', 'Controller#list_to_edit');
Route::post('/update_list', 'ProductController#update_list');
Here is my controller.
public function list_to_edit($id){
$artikel = Artikel::where("id","=",$id)->get();
return view('page.edit',compact('artikel'));
}
Here is my edit.js.
$(document).ready(function(){
$('#isi_artikel').summernote({
height: 300,
minHeight: 400,
maxHeight: 400,
focus: true
});
$('#btn_submit').click(function(e){
e.preventDefault();
var isiArtikel = $('#isi_artikel').summernote('code');
var judulArtikel = $('#judul').val();
var deskripsiArtikel = $('#deskripsi').val();
var kategori = $('input[name="etype"]:checked').val();
if($('#inputpicture').val() == ""){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN':$('meta[name="csrf_token"]').attr('content')
}
})
$.ajax({
type:"POST",
data: {
'id' : id,
'judul' : judulArtikel,
'isi' : isiArtikel,
'kategori' : kategori,
'deskripsi' : deskripsiArtikel,
'image' : null
},
dataType: "json",
url: "update_list",
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf_token']").attr('content'));
},
success: function(result){
if(result){
window.location.href = "kelola";
}
},
error : function(jqXhr) {
var errors = jqXhr.responseJSON;
//console.log(jqXhr);
errorsHtml = "<div class='alert alert-warning text-center' role='alert'>";
$.each( errors , function( key, value ) {
errorsHtml += value[0] ;
//console.log(value[0]);
});
errorsHtml += "</div>";
$('.alerts').html("<div>gila lu</div>");
$('.alerts').append(errorsHtml).fadeIn(200).fadeToggle(10000).fadeOut(50);
}
}, "json");
}else{
var ajax = function(imageData){
requestUploadArtikel(judulArtikel, isiArtikel, kategori, deskripsiArtikel, imageData);
}
imageupload($('#inputpicture').get(0), ajax);
}
});
function requestUploadArtikel(judul, isi, kategori, deskripsi, imageData){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN':$('meta[name="csrf_token"]').attr('content')
}
})
$.ajax({
type:"POST",
data: {
'id' : id,
'judul' : judul,
'isi' : isi,
'kategori' : kategori,
'deskripsi' : deskripsi,
'image' : imageData
},
dataType: "json",
url: "update_artikel",
success: function(result){
if(result){
window.location.href = "kelola";
}
},
error : function(jqXhr) {
var errors = jqXhr.responseJSON;
//console.log(jqXhr);
errorsHtml = "<div class='alert alert-warning text-center' role='alert'>";
$.each( errors , function( key, value ) {
errorsHtml += value[0] ;
//console.log(value[0]);
});
errorsHtml += "</div>";
$('.alerts').html("<div>gila lu</div>");
$('.alerts').append(errorsHtml).fadeIn(200).fadeToggle(10000).fadeOut(50);
}
}, "json");
}
function imageupload(element, ajax){
console.log('testimageupload');
var elementId = element.id;
if(element.files && element.files[0]){
var file = element.files[0];
var validFileType = ".jpg, .png, .bmp";
var extension = file.name.substring(file.name.lastIndexOf('.')).toLowerCase();
$("#"+elementId+"-show").attr('src', "");
console.log(extension);
//validatefile
if(validFileType.toLowerCase().indexOf(extension)<0){
$("#"+elementId+"-alert").show();
$("#"+elementId+"-show")
.attr('style', '')
.css('height','auto')
return;
}
$("#"+elementId+"-alert").hide();
//showfile
var reader = new FileReader();
reader.onload = function(e){
ajax(e.target.result);
}
if (reader.readAsDataURL) {reader.readAsDataURL(element.files[0]);}
else if(reader.readAsDataurl) {reader.readAsDataurl(element.files[0]);}
else if(reader.readAsDataUrl) {reader.readAsDataUrl(element.files[0]);}
}
else{
console.log('else');
$(elementId+"-show").attr('src',"");
}
}
});
here's my edit.blade.php
#extends('layout.layout')
#section('css')
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.css" rel="stylesheet">
#stop
#section('script')
<script type="text/javascript" src="{{ asset('js/artikel/edit.js') }}"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.js"></script>
#stop
#section('content')
<!-- Main Content -->
<div class="container">
<div class="row">
<h1 class="text-center edittengah">Edit Artikel</h1>
<div class="alerts"></div>
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
#foreach ($artikel as $a_artikel)
<input type="hidden" name="_token" value="{{{ csrf_token() }}}" />
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Judul Artikel</label>
<input type="text" class="form-control" placeholder="Judul Artikel" id="judul" required data-validation-required-message="Harap tuliskan judul artikel." value="{{$a_artikel->judul}}">
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label for="inputpicture">Ganti Foto Artikel</label>
<input type="file" name="picture" class="" id="inputpicture">
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Deskripsi Artikel</label>
<textarea name="deskripsi" id="deskripsi" cols="70" rows="5" placeholder="Deskripsi Artikel">{{ $a_artikel->deskripsi }}</textarea>
<p class="help-block text-danger"></p>
</div>
</div>
<div class="row control-group">
<div class="form-group col-xs-12 floating-label-form-group controls">
<label>Isi</label>
<div id="isi_artikel">{!! $a_artikel->content !!}</div>
<p class="help-block text-danger"></p>
</div>
</div>
<br>
<div class="row control-group">
<div class="form-group col-xs-12 controls">
<label>Jenis Artikel</label>
<?PHP if($a_artikel->kategori == "umum"){?>
<label><input class="CBumum" type="radio" name="etype" value="umum" checked="true"> Umum </label>
<label><input class="CBsh" type="radio" name="etype" value="selfhelp"> Self Help </label>
<label><input class="CBact" type="radio" name="etype" value="activites"> Activities </label>
<?PHP }
elseif($a_artikel->kategori == "selfhelp"){
?>
<label><input class="CBumum" type="radio" name="etype" value="umum" > Umum </label>
<label><input class="CBsh" type="radio" name="etype" value="selfhelp" checked="true"> Self Help </label>
<label><input class="CBact" type="radio" name="etype" value="activites"> Activities </label>
<?php }
else{
?>
<label><input class="CBumum" type="radio" name="etype" value="umum" > Umum </label>
<label><input class="CBsh" type="radio" name="etype" value="selfhelp"> Self Help </label>
<label><input class="CBact" type="radio" name="etype" value="activites" checked="true"> Activities </label>
<?php }?>
</div>
</div>
<hr>
<br>
<div id="success"></div>
<div class="row">
<div class="form-group col-xs-12">
<input class="btn btn-success" id="btn_submit" type="submit">
#endforeach
</div>
</div>
</div>
</div>
</div>
#stop
Your help is needed. Thanks in advance.
OKay my bad knowledge in routes,,
my ajax url update :
"url" : "/update_list"
it must should be
"url" : window.location + "/update_list"
and my controller from :
Route::post('/update_list', 'Controller#update_post');
to
Route::post('kelola/list/{id}/update_list', 'Controller#update_post');
'kelola/list/{id}/update_list' refer to my baseUrl before ajax process URL

Categories