Building an AJAX button on follow laravel - ajax

my blade view
I was working on updating the follow button in real-time so I noticed if I clicked on unfollow automatically it update to follow, but when i click on follow it's does nothing until I refresh the page manually
<button data-id="{{ $user->id }}" class="w-1/2 px-3 py-2 text-base text-white border rounded-lg action-follow bg-blue-lite hover:bg-blue"> <strong>
#if (auth()->user()->isFollowing($user))
UnFollow
#else
Follow
#endif
</strong>
</button>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.action-follow').click(function(){
var user_id = $(this).data('id');
var cObj = $(this);
var c = $(this).parent("div").find(".tl-follower").text();
$.ajax({
type:'POST',
url:'/profile/follow',
data:{user_id:user_id},
success:function(data){
console.log(data.success);
if(jQuery.isEmptyObject(data.data)){
cObj.find("strong").text("Follow");
cObj.parent("div").find(".tl-follower").text(parseInt(c)-1);
}else{
cObj.find("strong").text("UnFollow");
cObj.parent("div").find(".tl-follower").text(parseInt(c)+1);
}
}
});
});
});
My Controller
public function follwUserRequest(Request $request){
$user = User::find($request->user_id);
$response = auth()->user()->toggleFollow($user);
return response()->json(['success'=>$response]);
}

Try this one:
$user = User::find($request->user_id);
$response = auth()->user()->toggleFollow($user);
$status = auth()->user()->isFollowing($user);
return response()->json([ 'success' => $response, 'is_following' => $status ]);
<button data-id="{{ $user->id }}" id="mybutton{{ $user->id }}" class="w-1/2 px-3 py-2 text-base text-white border rounded-lg action-follow bg-blue-lite hover:bg-blue">
<strong>
#if (auth()->user()->isFollowing($user))
UnFollow
#else
Follow
#endif
</strong>
</button>
$.ajax({
type:'POST',
url:'/profile/follow',
data:{user_id:user_id},
success:function(data){
console.log(data);
if(data.is_following == true){
cObj.find("strong").text("UnFollow");
cObj.parent("div").find(".tl-follower").text(parseInt(c)+1);
}else{
cObj.find("strong").text("Follow");
cObj.parent("div").find(".tl-follower").text(parseInt(c)-1);
}
}
});

Related

How to submit a form with 3 submit buttons using ajax without redirecting to the form action url in Laravel?

I have here a datatable with a form inside that has 3 submit buttons. I did a switch statement which it checks what submit button was clicked, then performs the operation of that submit button on my store() function. Currently, I'm trying to submit the form using ajax. If I remove the switch statement, and just return one operation/function.e.g. saveCredit(), then it saves data in the database. However, with switch statement, in place, it doesn't save any data.
Also, another instance is if I remove the e.preventDefault(), it saves data in the database but it redirects to make-a-sale/save-purchase route which should not be. It must redirect to the same page. How can I make the submit buttons save the data in the database even with switch statement and e.preventDefault() in place? How can make it redirect to the current page? What am I doing wrong here?
Please see my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\{
Customer\BillingInfo,
Customer,
Product,
Purchases,
SetupBusiness
};
use App\Traits\PrintReceiptTrait;
use Carbon\Carbon;
use Picqer;
use Auth;
class PurchasesController extends Controller
{
use PrintReceiptTrait;
public function index()
{
return view('make-a-sale.index', ['has_id' => false]);
}
public function indexWithId($product_id)
{
return view('make-a-sale.index', ['product_id' => $product_id, 'has_id' => true]);
}
public function create()
{
return view('make-a-sale.index');
}
public function computeAndConvertData(Request $request)
{
$qty_per_item = array_map('intval', $request->qty);
$zero = floatval('0.00');
$payment = floatval($request->payment);
$total = floatval($request->total);
$balance = $total - $payment;
$new_data = array(
'qty_per_item' => $qty_per_item,
'zero' => $zero,
'payment' => $payment,
'total' => $total,
'balance' => $balance
);
return $new_data;
}
public function saveCredit(Request $request)
{
$product_ids = array_map('intval', $request->product_id);
$cod = $this->computeAndConvertData($request);
$data = $this->createData($request, $product_ids, $cod['qty_per_item'], $cod['balance']);
$this->createPurchaseData($data, $product_ids, $cod['qty_per_item'], $cod['zero'], $cod['total']);
$this->updateProductQtyOnHand($product_ids, $cod['qty_per_item']);
return redirect()->route('make-a-sale.index');
}
public function savePurchaseAndPrint(Request $request)
{
$product_ids = array_map('intval', $request->product_id);
$cod = $this->computeAndConvertData($request);
$payment = $cod['payment'] == $cod['zero'] ? $cod['zero'] : $request->payment;
$balance = $cod['balance'] != $cod['zero'] ? $request->total : $cod['balance'];
$data = $this->createData($request, $product_ids, $cod['qty_per_item'], $balance);
$purchase = $this->createPurchaseData($data, $product_ids, $cod['qty_per_item'], $payment, $balance);
$this->updateProductQtyOnHand($product_ids, $cod['qty_per_item']);
return $this->printReceipt($purchase->code, $purchase->barcode, $purchase->product_id, $purchase->qty_per_item, $purchase->balance);
}
public function savePurchase(Request $request)
{
$product_ids = array_map('intval', $request->product_id);
$cod = $this->computeAndConvertData($request);
$data = $this->createData($request, $product_ids, $cod['qty_per_item'], $cod['balance']);
$this->createPurchaseData($data, $product_ids, $cod['qty_per_item'], $request->payment, $cod['balance']);
$this->updateProductQtyOnHand($product_ids, $cod['qty_per_item']);
return redirect()->route('make-a-sale.index');
}
public function store(Request $request)
{
switch($request->get('action_create')) {
case 'credit':
$this->saveCredit($request);
break;
case 'save_and_print':
$this->savePurchaseAndPrint($request);
break;
case 'save':
$this->savePurchase($request);
break;
default:
return redirect()->route('make-a-sale.index');
}
}
private function generateRandomNumbers($length = 12)
{
$num = '0123456789';
$num_length = strlen((string)$num);
$random_number = '';
for ($i = 0; $i < $length; $i++) {
$random_number .= $num[rand(0, $num_length - 1)];
}
return $random_number;
}
private function generateBarcode($code_to_convert)
{
$generator = new Picqer\Barcode\BarcodeGeneratorHTML();
$barcode = $generator->getBarcode($code_to_convert, $generator::TYPE_CODE_128, 2, 35);
return $barcode;
}
public function createData(Request $request, $product_ids, $qty_per_item, $balance)
{
$code = $this->generateRandomNumbers();
$validation = $request->validate([
'code' => 'unique:purchases',
'product_id' => 'required',
'customer_id' => 'required'
]);
$data = array_merge($validation, [
'code' => $code,
'barcode' => $this->generateBarcode($code),
'status' => 'Regular',
'type' => $balance == floatval('0.00') ? 'Sale' : 'Accounts Receivables',
'cashier_id' => Auth::user()->id,
'customer_id' => $request->customer_id,
'product_id' => $product_ids,
'no_of_items' => $request->no_of_items,
'qty_per_item' => $qty_per_item,
'payment_type' => $balance <= 0 ? 'cash' : 'credit',
'total' => $request->total,
'created_at' => Carbon::now()->timestamp
]);
return $data;
}
public function createPurchaseData($data, $product_id, $qty_sold, $payment, $balance)
{
$purchases = Purchases::create(array_merge($data, [
'payment' => $payment,
'balance' => $balance,
'product_details' => $this->createProductsDetails($product_id, $qty_sold)
]));
return $purchases;
}
public function updateProductQtyOnHand($product_ids, $qty_per_item)
{
$products = array_combine($product_ids, $qty_per_item);
foreach ($products as $product_id => $receive_item_qty) {
$qty_on_hand = Product::where('id', '=', $product_id)->value('qty_on_hand');
$difference = $qty_on_hand - $receive_item_qty;
Product::select('qty_on_hand')->where('id', '=', $product_id)->update(['qty_on_hand' => $difference]);
}
}
}
Here's my route:
Route::post('make-a-sale/save-purchase', [PurchasesController::class, 'store'])->name('make-a-sale.store');
Here's some of my Ajax:
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function() {
$.noConflict();
var tableId = '#tbl-make-a-sale';
// Footer button group actions
saveCredit(tableId);
savePurchase(tableId);
});
function saveCredit(tableId) {
$('#btn-credit').on('click', function(e) {
e.preventDefault();
if (!$("input[name='product_id[]']").val()) {
toastr.error('The table is empty. Please add some products first.');
} else {
let productIds = $("input[name='product_id[]']").map(function(){ return $(this).val(); }).get();
let qtyPerItem = $("input[name='qty[]']").map(function(){ return $(this).val(); }).get();
let params = {
product_id: productIds,
qty: qtyPerItem,
no_of_items: $("input[name='no_of_items']").val(),
customer_id: $("input[name='customer_id']").val(),
payment: parseFloat($('input[name="payment"]').val()),
total: parseFloat($('input[name="total"]').val()),
_token: $('meta[name="csrf-token"]').attr('content')
}
$.ajax({
url: 'make-a-sale/save-purchase',
type: 'POST',
data: params,
success: function(data) {
toastr.success("A new ledger has been created!");
$(tableId).DataTable().clear().draw(false);
$('#search-customers').val('0').trigger('change.select2').prop('disabled', true);
$('#cash-container, #txt-amount-due').hide();
},
error: function(xhr, status, error) {
let errors = xhr.responseJSON.errors;
for (var key in errors) {
if (errors.hasOwnProperty(key)) {
toastr.error(errors[key]);
}
}
}
});
}
});
}
function savePurchase(tableId) {
$('#btn-save').on('click', function(e) {
e.preventDefault();
if (!$("input[name='product_id[]']").val()) {
toastr.error('The table is empty. Please add some products first.');
} else {
let productIds = $("input[name='product_id[]']").map(function(){ return $(this).val(); }).get();
let qtyPerItem = $("input[name='qty[]']").map(function(){ return $(this).val(); }).get();
let params = {
product_id: productIds,
qty: qtyPerItem,
no_of_items: $("input[name='no_of_items']").val(),
customer_id: $("input[name='customer_id']").val(),
payment: parseFloat($('input[name="payment"]').val()),
total: parseFloat($('input[name="total"]').val()),
_token: $('meta[name="csrf-token"]').attr('content')
}
$.ajax({
url: 'make-a-sale/save-purchase',
type: 'POST',
data: params,
success: function(data) {
toastr.success("Products have been sold successfully!");
$(tableId).DataTable().clear().draw(false);
$('#search-customers').val('0').trigger('change.select2').prop('disabled', true);
$('#cash-container, #txt-amount-due').hide();
},
error: function(xhr, status, error) {
let errors = xhr.responseJSON.errors;
for (var key in errors) {
if (errors.hasOwnProperty(key)) {
toastr.error(errors[key]);
}
}
}
});
}
});
}
Here's my HTML:
<form id="form-make-a-sale" action="{{ route('make-a-sale.store') }}" method="post" enctype="multipart/form-data">
#csrf
<table id="tbl-make-a-sale" class="w-full tbl-responsive overflow-x-auto rounded-lg border-none tbl-default">
<thead class="w-min">
<tr>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">Actions</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Barcode
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Name
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Description
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Qty. On Hand
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Qty. To Sell
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none hidden">
SRP
</th>
<th
class="px-6 py-0 bg-persian-blue h-16 text-left text-xs text-white uppercase tracking-wider border-none">
Ext. Price
</th>
</tr>
</thead>
<tbody class="bg-white"></tbody>
</table>
<div class="w-full pb-6 md:pb-0 border-t border-gray-200 md:border-none">
<div class="flex bg-white justify-between items-center">
<div class="pt-6 pb-0 px-6 whitespace-no-wrap">
<p class="text-2xl text-gray-700 font-bold">Total</p>
</div>
<div class="pt-6 pb-0 px-6 whitespace-no-wrap">
<p class="text-4xl text-gray-700 font-extrabold font-mono text-right">
<span id="total">₱ 0.00</span>
<input type="hidden" name="total" readonly/>
</p>
</div>
</div>
<div id="cash-container" style="display: none;">
<div class="flex justify-between items-center">
<div class="px-6 whitespace-no-wrap">
<p class="text-lg text-gray-700 font-bold">Cash</p>
</div>
<div class="px-6 whitespace-no-wrap">
<p class="text-lg text-gray-700 font-extrabold font-mono text-right">
<span id="cash">0.00</span>
</p>
</div>
</div>
</div>
</div>
<div class="mt-4 w-full md:border-t md:border-b md:border-gray-200">
<div id="amount-due-container" class="flex bg-persian-blue md:bg-white justify-between items-center">
<div class="p-6 whitespace-no-wrap">
<p id="lbl-amount-due" class="text-2xl text-gray-50 md:text-gray-700 font-bold">Amount Due</p>
</div>
<div class="p-6 whitespace-no-wrap">
<p id="txt-amount-due" class="text-3xl text-gray-50 md:text-gray-700 font-extrabold font-mono text-right">
<span id="amount_due"></span>
</p>
</div>
</div>
</div>
<div id="btn-footer-group-mas" class="m-6 justify-between">
<button type="button" class="px-8 py-4 text-md font-medium text-gray-50 transition-colors duration-300 transform bg-red-400 hover:bg-red-500 rounded hover:text-white focus:outline-none focus:ring cstm-size-m-mas cstm-size-w-full-mas btn-clear" name="clear" value="clear" tabindex="2">Clear
</button>
<div id="btn-footer-right-group-mas">
<button type="button" id="btn-cash" class="px-8 py-4 text-md font-medium text-white transition-colors duration-300 transform rounded bg-green-400 hover:bg-green-300 focus:outline-none focus:ring cstm-size-m-mas cstm-size-w-full-mas" data-hystmodal="#pay-in-cash-modal" tabindex="3">Cash
</button>
<button type="submit" id="btn-credit" class="px-8 py-4 text-md font-medium text-white transition-colors duration-300 transform rounded bg-yellow-400 hover:bg-yellow-300 focus:outline-none focus:ring cstm-size-m-mas cstm-size-w-full-mas credited" name="action_create" value="credit" tabindex="4">Credit
</button>
<button type="submit" id="btn-save-and-print" class="px-8 py-4 text-md font-medium text-indigo-400 transition-colors duration-300 transform border-2 border-indigo-400 rounded bg-indigo-100 hover:bg-indigo-200 focus:outline-none focus:ring disabled:opacity-40 cursor-not-allowed cstm-size-m-mas cstm-size-w-full-mas" name="action_create" value="save_and_print_receipt" tabindex="5">Save and Print Receipt
</button>
<button type="submit" id="btn-save" class="px-8 py-4 text-md font-medium text-white transition-colors duration-300 transform rounded bg-indigo-600 rounded hover:bg-indigo-500 focus:outline-none focus:ring cstm-last-el-size-m-mas cstm-size-w-full-mas" name="action_create" value="save" tabindex="6">Save
</button>
</div>
</div>
</form>
Any help is much appreciated.
On the controller side instead of redirecting to the route, you can redirect JSON to the Ajax at frontend.
For Example:
Instead of:
return redirect()->route('make-a-sale.index');
You can:
return response()->json(["status"->true]);
your question I doesn't understand but first check on submit Your Ajax send request to your controller function of not...
2nd thing, you don't need to write hardcoded url in ajax request...
$.ajax({
type: "GET",
url: "{{ route('home') }}?page="+ page,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
// data: { id: deal_id, }
}).done(function( data ) {
//on success do your operation
})
.fail(function(jqXHR, ajaxOptions, thrownError)
alert('No response from server');
});
If you want to pass Param in URL like domainname.com/user/edit/{id}
then you can pass to ajax as above same URL using route you...
simply do as like below
user_id = 3; //on click get user_id
url = "{{ route('admin.users.edit',':id') }}";
url = url.replace(':id', user_id);
then that url variable pass to ajax
$.ajax({
type: "POST",
url: url,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
// data: { id: deal_id, }
}).done(function( data ) {
//on success do your operation
})
.fail(function(jqXHR, ajaxOptions, thrownError)
alert('No response from server');
});
Sorry #Harsh Patel if I cannot explain my question well.
I managed to solved it by:
return response()->json([$data]);
And adding redirect per case in my switch statement:
return redirect()->route('make-a-sale.index');
Switch statement:
public function store(Request $request)
{
switch($request->get('action_create')) {
case 'credit':
$this->saveCredit($request);
return redirect()->route('make-a-sale.index');
break;
case 'save_and_print':
$this->savePurchaseAndPrint($request);
break;
case 'save':
$this->savePurchase($request);
return redirect()->route('make-a-sale.index');
break;
default:
return redirect()->route('make-a-sale.index');
}
}
Thank you #Shree Sthapit

Symfony redirect by ajax

The page login use ajax, in controller response in view web browser {"response":true,"data":{"from":"apachecms_api_login_submit","to":"/dashboard"}} and not redirect.
function to ajax when success
function beforeSuccess(data){
if(data.data.from=='apachecms_api_login_recovery_submit'){
loading.hide();
$.toast({
heading: "{{ 'success' | trans }}",
text: "{{ 'forgot.password.sending' | trans }}",
position: 'top-right',
icon: 'success',
hideAfter: 5000,
stack: 10
});
changeForm('login')
}else if(data.data.from=='apachecms_api_login_submit'){
location.href=data.data.to;
}else if(data.data.from=='apachecms_api_login_create_submit'){
location.href=data.data.to;
}
}
Whats happend?
LoginController.php extends BaseController
public function loginAction(Request $request){
$form=$this->createForm(LoginType::class, null,array('action'=>$this->generateUrl('apachecms_api_login_submit'),'method' => 'POST'));
$form->handleRequest($request);
if($errors=$this->ifErrors($form)) return $errors;
try {
$entity = $this->getDoctrine()->getRepository('ApachecmsBackendBundle:Customer')->findOneBy(array('email'=>$form->get('_username')->getData(),'isDelete'=>false));
if(!$entity)
throw new Exception(null,200);
$encoder_service = $this->get('security.encoder_factory');
$encoder = $encoder_service->getEncoder($entity);
if(!$encoder->isPasswordValid($entity->getPassword(), $form->get('_password')->getData(), $entity->getSalt()))
throw new Exception(null,200);
$token = new UsernamePasswordToken($entity, $form->get('_password')->getData(), "main", $entity->getRoles());
$this->get("security.token_storage")->setToken($token);
$event = new InteractiveLoginEvent($request, $token);
$this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
return $this->responseOk(array('from'=>'apachecms_api_login_submit','to'=>$this->generateUrl('apachecms_frontend_dashboard'))); // HERE RETURN RESPONSE
}catch (Exception $excepcion) {
return $this->responseFail(array(array('property'=>'_username','code'=>'invalid_credentials','message'=>$this->get('translator')->trans('invalid.credentials'),'data'=>null)),200);
}
}
BaseController.php
public function responseOk($data=array(),$code=200){
try{
// if(!$data)
// throw new Exception('No se encontrĂ³ el registro',200);
return new Response($this->get('jms_serializer')->serialize(
array('response'=>true,'data'=>$data),
'json',$this->context),$code);
}catch (Exception $excepcion) {
return $this->responseFail(array(array(
'property'=>null,
'message'=>$excepcion->getMessage(),
'code'=>'not_found',
'data'=>null
)),$excepcion->getCode());
}
}
index.html.twig <= Login Page
{{ form_start(formLogin, {'attr': {'id':'loginform','novalidate':'novalidate','class':'form-horizontal form-material sendToApi login'} }) }}
<div class="form-group">
<div class="col-xs-12">
{{form_widget(formLogin._username)}}
<small class="text-danger error">{{ form_errors(formLogin._username) }}</small>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
{{form_widget(formLogin._password)}}
<small class="text-danger error">{{ form_errors(formLogin._password) }}</small>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<div class="checkbox checkbox-info pull-left p-t-0"></div>
<a href="javascript:changeForm('recovery')" id="to-recover" class="text-dark pull-right">
<i class="fa fa-lock m-r-5"></i> {{ 'forgot.password' | trans }}</a>
</div>
</div>
<div class="form-group text-center">
<div class="col-xs-12 p-b-20">
{{form_widget(formLogin.submit,{ 'attr':{ 'class':'btn btn-block btn-lg btn-info btn-rounded','secondary-label':'loading' | trans}})}}
</div>
</div>
{{ include('ApachecmsFrontendBundle::Login/social.html.twig') }}
<div class="form-group m-b-0">
<div class="col-sm-12 text-center">
{{ 'not.account' | trans }}
<a href="javascript:changeForm('register')" class="text-info m-l-5">
<b>{{ 'register' | trans }}</b>
</a>
</div>
</div>
{{ form_end(formLogin) }}
Ajax
// pre-submit callback
function showRequest(formData, form, options) {
loading.show('{{ 'loading' | trans }}');
var url = form.attr("action");
var method = form.attr("method").toUpperCase();
var dataForm = form.serialize();
var submitBtn = form.closest('form').find(':submit');
var inputs=form.closest('form').find(':input:not(.dropify)');
inputs.removeClass('error');
inputs.next('small').html('');
BtnSecondaryLabel=submitBtn.attr('secondary-label');
BtnHtml=submitBtn.html();
submitBtn.html('<i class="fa fa-gear fa-spin"></i> '+BtnSecondaryLabel);
submitBtn.attr('disabled',true);
return true;
}
// post-submit callback
function showResponse(data, statusText, xhr, form) {
var submitBtn = form.closest('form').find(':submit');
submitBtn.attr('disabled',false);
submitBtn.html(BtnHtml);
if(data.response==true){
beforeSuccess(data);
}
}
$(function (){
var options = {
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
$( "form.sendToApi" ).ajaxForm(options); <= capture class to form sendToApi
})
function beforeSuccess(data){
if(data.data.from=='apachecms_api_login_recovery_submit'){
loading.hide();
$.toast({
heading: "{{ 'success' | trans }}",
text: "{{ 'forgot.password.sending' | trans }}",
position: 'top-right',
icon: 'success',
hideAfter: 5000,
stack: 10
});
changeForm('login')
}else if(data.data.from=='apachecms_api_login_submit'){
location.href=data.data.to;
}
}

Laravel 5: When store data to database The server responded with a status of 405 (Method Not Allowed)

I m new in Laravel and trying to add data to the database via ajax, but it throws this message: "The server responded with a status of 405 (Method Not Allowed)" I define two routes for this one is for form page
Route::get('/create/{id}', 'Participant\ParticipantProjectDefinitionController#create')->name('participant.project-definition.create');
and other route to save this data like this:
// To save Project definition Data
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
And the Ajax code I'm using is this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: {
'_token' : token,
'customer_name' : $('#field_name_0').val(),
'customer_name' : $('#field_data_0').val(),
// 'form_fields' : form_fields
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
Controller code
/**
* create project Definition Form
*
*/
public function create(request $request, $id){
$ProjectDefinitionFields = ProjectDefinitionFields::all();
$ProjectDefinitionFieldRow = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
// dd($ProjectDefinitionFieldRow);
return view('participants.project_definition.create', ['ProjectDefinitionFieldRow' => $ProjectDefinitionFieldRow]);
}
public function store(request $request, $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields){
$project = ProjectDefinitionFields::find('field_id');
$count = ProjectDefinitionFields::where('project_definition_id','=', $id)->count();
$pd_id = ProjectDefinitionFields::where('project_definition_id','=', $id)->get();
for($i=0;$i<$count;$i++){
$data[]= array (
'field_name'=>$request->get('field_name_'.$i),
'field_data'=>$request->get('field_data_'.$i),
'user_id' => Auth::user()->id,
// 'user_id' => $request->user()->id,
'project_definition_id' => $pd_id,
// 'field_id' => $projectDefinitionFields->id,
);
}
$project_data = ProjectDefinitionData::create($data);
if($project_data){
return response()->json($project_data);
}
}
Model
on ProjectDefinition
public function formFields(){
// return $this->hasMany('App\Model\ProjectDefinitionFields');
return $this->belongsTo('App\Model\ProjectDefinitionFields');
}
on projectDefinitionFields
public function projectDefinition(){
return $this->belongsTo('App\Model\ProjectDefinition');
}
This is my create.blade.php
<form id="create_project_definition_data_form" enctype="multipart/form-data" >
#csrf
{{ method_field('PUT') }}
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
#section('scripts')
<script src="{{ asset('js/participants/project-definition.js') }}"></script>
<script>
// on document ready
$(document).ready(function(){
var baseUrl = "{{ url('/') }}";
var indexPdUrl = "{{ route('participant.projectDefinition') }}";
var token = "{{ csrf_token() }}";
{{-- // var addUrl = "{{ route('participant.project-definition.create') }}"; --}}
storeDefinitionFormData(token, baseUrl);
// console.log(addUrl);
});
</script>
ERROR
Request URL:http://127.0.0.1:8000/participant/project-definition/create/2kxMQc4GvAD13LZC733CjWYLWy8ZzhLFsvmOj3oT
Request method:POST
Remote address:127.0.0.1:8000
Status code: 405 Method Not Allowed
Version:HTTP/1.0
Add method attribute in form
method="post"
Change your route from
Route::get('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
to
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
Firstly, you should post here what's your problem and where's your problem we don't need to see all of your code to solve a basic problem.
Your form should be this:
<form id="create_project_definition_data_form" enctype="multipart/form-data" method='post'>
#csrf
<?php $count = 0; ?>
#foreach($ProjectDefinitionFieldRow as $value)
<div class="row">
<div class="form-group col-md-12" id="form-group">
<div class="row">
<label for="definition_data_<?php echo $count; ?>" class="col-sm-2 col-md-2 col-form-label" id="field_name_<?php echo $count; ?>" name="field_name_<?php echo $count; ?>[]" value="{{$value->field_name }}">{{$value->field_name }}</label>
<div class="col-sm-10 col-md-10">
{{-- textbox = 1
textarea = 0 --}}
<<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?> class="form-control" name="field_data_<?php echo $count; ?>[]" placeholder="Enter project definition_data" id="field_data_<?php echo $count; ?>" aria-describedby="field_data_help"></<?php if($value->field_type = 1){echo "input";}else{echo "textarea";} ?>>
<small id="field_data_help_<?php echo $count; ?>" class="form-text text-muted help-block">
Optional Field.
</small>
<span id="field_data_error_<?php echo $count; ?>" class="invalid-feedback validation"></span>
</div>
</div>
</div>
</div>
<hr />
<?php $count++; ?>
#endforeach
<div class="text-center">
<button type="submit" class="btn btn-primary" id="create_project_definition_data">Create Project Defination Data</button>
</div>
</form>
You should use 'post' method when you're creating a something new, this is safer than using 'get' method. so change route method too.
Route::post('/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
also, in your 'ParticipantProjectDefinitionController->store()' function has
$id, User $user, ProjectDefinitionFields $ProjectDefinitionFields parameters but your router not. We can fix it like this:
Route::post('/store-project-definition-data/{id}/{user}/{ProjectDefinitionFields}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
That means you should pass all of them to your controller.
Soo we can edit your ajax call like this:
function storeDefinitionFormData(addUrl, token, baseUrl){
$('#create_project_definition_data').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form_fields = [];
var counter = 0;
$('.form-group').each(function(){
var values = {
'field_name' : $('#field_name_' + counter).val(),
'field_data' : $('#field_data_' + counter).val(),
};
form_fields.push(values);
counter++;
});
$.ajax({
type: 'POST',
dataType: 'JSON',
url: addUrl,
data: { // $id, User $user, ProjectDefinitionFields $ProjectDefinitionFields
'_token' : token,
'id' : 'your_id_field',
'user' : '{{ Auth::user() }}',
'ProjectDefinitionFields' : 'your_definition_fields' // you need to pass type of 'ProjectDefinitionFields'
},
success: function(data){
alert('done');
window.location = baseUrl;
},
error: function(data){
alert('fail');
if(data.status == 422){
errors = data.responseJSON.errors; // => colllect all errors from the error bag
var fieldCounter = 0;
$('.help-block').show();
$('.validation').empty(); // => clear all validation
// display the validations
$('.validation').css({
'display' : 'block'
});
// iterate through each errors
$.each(errors, function(key, value){
if(key.includes('form_fields.')){
var field_errors = key.split('.');
var field_error = field_errors[2] + "_" + field_errors[1];
$('#' + field_error + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
}
$('#' + key + '_help').hide();
$('#' + key + '_error').append("<i class='zmdi zmdi-alert-circle' style='font-size: 15px;'></i> " + value); // => append the error value in the error message
});
}
}
});
});
}
before try it, I'll give you a advice. Read whole documentation and review what others do on github or somewhere else
Route::match(['GET','POST'],'/store-project-definition-data/{id}', 'Participant\ParticipantProjectDefinitionController#store')->name('participant.project-definition.store');
You can try this Route it will resolve 405

in my website error GET http://localhost:8000/storage/img/ 404 (Not Found)

I have a project in laravel but I have a problem GET http://localhost:8000/storage/img/ 404 (Not Found) like a picture any one can help me
the website works fine but shows error in devtools chrom I can't find the problem
I have data.blade.html file
#foreach($posts as $post)
#php
$img=$post->images->first();
$img_name=$img['image'];
#endphp
<a id="brick{{$post->id}}"href="/{{$post->id}}" class="card p-2 m-2 mb-3 shadow">
<div class="" >
<img class="card-img-top border" src="storage/img/{{$img_name}}" onerror="this.onerror=null;this.src='storage/img/car.jpg'" alt="Card image cap">
<div class="card-body">
<h5 class="card-title">{{$post->title}}</h5>
<h6 class="card-text">{{$post->text}}</h6>
<h4><span class="badge badge-primary">{{number_format($post->price,2)}} Dzd</span></h4>
</div>
</div>
</a>
#endforeach
and hameController
public function ok2()
{
$posts=Post::select('id','title','text','price','user_id')
->latest()
->paginate(1);
$view = view('data',compact('posts'))->render();
return response()->json(['html'=>$view]);
}
and java script
$(function(){
var page=15 ;
$(window).on("scroll", function() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
for(i=0;i<5;i++)
{
page++;
loadMoreData(page);
}
}
});
function loadMoreData(page){
$.ajax(
{
url: '/ok2?page=' + page,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
if(data.html == ""){
$('.ajax-load').html("No more records found");
return;
}
$('.ajax-load').hide();
var box = document.createElement('div');
box.innerHTML = data.html;
console.log(box);
bricklayer.append(box);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
});
thank you
In blade view file, you call $post->images
You should make sure that the images relationship has been created.
If images relationship has been created. You should use Eager Loading to achieve optimal speed.
And you need to make sure any posts has an image.
Finally, check $img varible:
#if (filled($img))
<img class="card-img-top border" src="storage/img/{{$img_name}}" onerror="this.onerror=null;this.src='storage/img/car.jpg'" alt="Card image cap">
#endif

Image deleted but page not refreshed ajax laravel

Hi there I am having a problem when I click button delete it deletes the folder with image inside and that is what I want but the page it is not refreshed so I do not know that is deleted till I click refresh
this is the code:
#if($question->question_image)
<img src="{{url('/')}}/images/questions/{{ $question->id }}/medium/{{ $question->question_image }}" class="answer-image-create" id="question_image_box">
<input onchange="readquestionURL(this);" type="file" id="question_file" name="question_image" style="display:none"/>
#else
<img src="{{ asset('noavatars/no-image-selected.png') }}" class="answer-image-create" id="question_image_box">
<input onchange="readquestionURL(this);" type="file" id="question_file" name="question_image" style="display:none"/>
#endif
</div>
{{-- <button type="button" class="btn" id="question_upfile"
style="cursor:pointer; padding-left: 24px; padding-right: 15px;">
<i class="fa fa-upload" aria-hidden="true">
</i>#lang('buttons.upload_image')
</button> --}}
<button type="button" value="{{-- {{ $i }} --}}" class="btn btn-flat btn-default btn-sm delete_image" id="delete_image" title="#lang('buttons.remove_option')"><i class="fa fa-trash-o" aria-hidden="true"></i> </button>
and the javascript code is this:
<script>
$(document).on("click", "button[id=delete_image]", function(data){
var questionid = {{$question->id}};
var element = 'questions';
$.ajax({
type: "POST",
url: "{{ action('website\images\ImagesController#deleteImage') }}",
data: {
_token: "{{ csrf_token() }}",
'id':questionid,
'element' : element,
},
success: function(response) {
console.log(response);
},
error: function(response){
alert("fail");
}
});
function readquestionURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#question_image_box')
.attr('src', e.target.result)
};
reader.readAsDataURL(input.files[0]);
}
}
});
</script>
The controller is this:
public function deleteImage($element =null, $id = null){
if(request()->ajax()) {
$id = request()->input('id');
$element = request()->input('element');
if($element != null && $id != null){
Storage::disk('public')->deleteDirectory('/images/'.$element. '/'. $id);
}
return 1;
}
}
How can I achieve to delete the image and be refreshed at the same time. Can someone please help me thank you very much .
You can refresh the page using javascript
location.reload();
You'll need to add that line on your ajax's success method.

Resources