Can’t use method POST for Ajax, Can’t get values by dd(); in controller after using GET method, Can’t add records to DB

  ajax, jquery, json, laravel, php

When I am trying to use post method and change method in view and routing, I am getting error "POST method is not supported". When I am using get method I can’t get values in controller by dd();. I am checking dev tools in chrome and getting only html view code in Network/response tab. How to check this values in controller or what am I doing wrong?

This is code of view with Ajax and form to send by Ajax.

<head>
        <meta charset="utf-8">
            <title></title>

    <!-- Meta to be used by laravel and ajax requests -->
        <meta name="csrf-token" content="echo this => csrf_token() ">
 </head>

@extends('layouts.app')


@section('content')


<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


<script type="text/javascript">
$(document).ready(function(){
    var maxField = 100; //Input fields increment limitation
    var addButton = $('.add_button'); //Add button selector
    var wrapper = $('.field_wrapper'); //Input field wrapper
    var fieldHTML = '<div><div class="form"><label><STRONG>Przedmiot leasingu</STRONG></label><input type="text" name="przedmiot[]" class="form-control"></div>'
        fieldHTML+=  '<div class="form"><label><STRONG>Nazwa</strong></label><input type="text" name="nazwa_przedmiot[]" class="form-control"></div>'
        fieldHTML+=  '<div class="form"><label><strong>Rok produkcji</strong></label><input type="text" name="rok[]" class="form-control"></div>'
        fieldHTML+=  '<div><label><strong>Cena netto (bez VAT)</strong></label></div>'
        fieldHTML+=  '<input class="form-control" type="text" class="kwota" name="cena[]" style="display: inline-block; width: 415px;" ><span style="display: inline-block;"> <strong>&nbspPLN</strong></span>'
        fieldHTML+=  '<div class="form"><label><strong>Wartość VAT</strong></label><select name="vat[]" class="form-control"><option value="">-- wybierz --</option><option value="0">0%</option><option value="8">8%</option><option value="23">23%</option><option value="zw">ZW</option></select><br></div>'
        fieldHTML+=  '<a href="javascript:void(0);" class="remove_button"><div class="btn btn-danger"><i class="far fa-trash-alt"></i> Usuń przedmiot</div></a></div>'; //New input field html 
    var x = 1; //Initial field counter is 1
    
    //Once add button is clicked
    $(addButton).click(function(){
        //Check maximum number of input fields
        if(x < maxField){ 
            x++; //Increment field counter
            $(wrapper).append(fieldHTML); //Add field html
        }
    });
    
    //Once remove button is clicked
    $(wrapper).on('click', '.remove_button', function(e){
        e.preventDefault();
        $(this).parent('div').remove(); //Remove field html
        x--; //Decrement field counter
    });
});
</script>

<script type="text/javascript">



$('#dynamic_form').on('save', function(event) {
  event.preventDefault();
  var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
  $.ajax({
    url: '{{ route("dynamic-field.insert") }}',
    method: 'get',
    data: $(this).serialize(),
    dataType: 'json',
   
    beforeSend: function() {
      $('#save').attr('disabled', 'disabled');
    },
    error: function(data) { 
                console.log("Error on ajax");
                console.log(data.error);
                console.log(data);
            },
    statusCode: {
                500: function() {
                    console.log('DB error');
                }
            },
    success: function(data) {
         console.log('Yes Working');
      if (data.error) {
        var error_html = '';
        for (var count = 0; count < data.error.length; count++) {
          error_html += '<p>' + data.error[count] + '</p>';
        }
        $('#result').html('<div class="alert alert-danger">' + error_html + '</div>');
      } else {
        dynamic_field(1);
        $('#result').html('<div class="alert alert-success">' + data.success + '</div>');
      }
      $('#save').attr('disabled', false);
    }
  })
});
</script>

<meta name="csrf-token" content="{{ csrf_token() }}">

<div class="py-12">
     <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">   
         <div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">  

                        <div class="row">
                            <div class="col-lg-12 margin-tb">
                                <div class="pull-left" style="margin-left: 53px; margin-right: 30px; width: 95%;">
                                    <h2>iLeasing Oferta</h2>
                                </div>
                                <div class="pull-right" style="margin-left: 53px; margin-right: 30px; width: 95%;">
                                    <a class="btn btn-primary" href="{{ route('leasings.index') }}"> Wstecz</a>
                                </div>
                                <br> 
                            </div>
                        </div>
                        @if ($errors->any())
                            <div class="alert alert-danger">
                                <strong>Whoops!</strong> There were some problems with your input.<br><br>
                                <ul>
                                    @foreach ($errors->all() as $error)
                                        <li>{{ $error }}</li>
                                    @endforeach
                                </ul>
                            </div>
                        @endif    

                        @if(session()->has('message'))
                        <div class="alert alert-success">
                            {{ session()->get('message') }}
                        </div>
                        @endif
              

                <form id="dynamic_form" enctype="multipart/form-data" style="font-size: 15px; margin-left: 30px; margin-right: 30px;">
                @csrf                        
                             <div style="row">
                                            <div class="col-xs-12 col-sm-12 col-md-12">
                                            <header><h4>Typ leasingu</h4></header>
                                            </div>

                                            ...                                           

                                    <div class="col-xs-12 col-sm-12 col-md-12">
                                        <div class="form-group">
                                            <div class="field_wrapper">
                                                <div>
                                                   
                                                    <a href="javascript:void(0);" class="add_button" title="Add field"><div class="btn btn-primary"><i class="fa fa-plus-circle"></i> Dodaj kolejny przedmiot</div></a>
                                                </div>
                                            </div>
                                        </div>   
                                    </div>
                                   
                                           


                                    



                                            <div class="col-xs-12 col-sm-12 col-md-12">
                                                <div class="form-group">
                                                    <div class="form">
                                                        <label>Opłata wstępna</label>
                                                        <select name="oplata" class="form-control">
                                                            <option value="1">1%</option>
                                                            <option value="5">5%</option>
                                                            <option value="10">10%</option>
                                                            <option value="20">20%</option>
                                                            <option value="30">30%</option>
                                                            <option value="40">40%</option>
                                                            <option value="45">45%</option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="col-xs-12 col-sm-12 col-md-12">
                                                <div class="form-group">
                                                    <div class="form"><label>Długość leasingu</label>
                                                            <select name="dlugosc" class="form-control">
                                                                <option value="3">3 miesiące</option>
                                                                <option value="6">6 miesięcy</option>
                                                                <option value="9">9 miesięcy</option>
                                                                <option value="12">12 miesięcy</option>
                                                                <option value="15">15 miesięcy</option>
                                                                <option value="18">18 miesięcy</option>
                                                                <option value="21">21 miesięcy</option>
                                                                <option value="24">24 miesiące</option>
                                                                <option value="27">27 miesięcy</option>
                                                                <option value="30">30 miesięcy</option>
                                                                <option value="33">33 miesiące</option>
                                                                <option value="36">36 miesięcy</option>
                                                                <option value="39">39 miesięcy</option>
                                                                <option value="42">42 miesiące</option>
                                                                <option value="45">45 miesięcy</option>
                                                                <option value="48">48 miesięcy</option>
                                                                <option value="60">60 miesięcy</option>
                                                            </select>
                                                     </div>
                                                </div>
                                            </div>
                                            <div class="col-xs-12 col-sm-12 col-md-12">
                                                
                                                    <div class="form operacyjny"><label>Kwota wykupu</label></div>   
                                                
                                            </div>
                                            <div class="col-xs-12 col-sm-12 col-md-12">
                                                <div class="form-group">
                                                    <div class="form operacyjny"><input  style="display: inline-block; width: 415px;" type="text" name="wykup" class="form-control"><span>%</span></div>   
                                                </div>
                                            </div>
                                            <div class="col-xs-12 col-sm-12 col-md-12">
                                                
                                                    <div class="form operacyjny"><label>Prowizja</label></div>   
                                                
                                            </div>
                                            <div class="col-xs-12 col-sm-12 col-md-12">
                                                <div class="form-group">
                                                    <div class="form"><input style="display: inline-block; width: 415px;" type="text" name="prowizja" class="form-control"><span>%</span></div>
                                                </div>
                                            </div>
                                            <div class="col-xs-12 col-sm-12 col-md-12">
                                                <div class="form-group">
                                                     <div class="form"><label>Dostawca</label><input type="text" name="dostawca" class="form-control" maxlength="10"></div>
                                                </div>
                                            </div>
                                            <div class="col-xs-12 col-sm-12 col-md-12">
                                                <div class="form-group">
                                                    <div class="form"><label>Suma rat</label><select class="form-control" name="suma"><option value="0">nie wyświetlaj</option><option value="1">wyświetlaj</option></select></div>
                                                </div>
                                            </div>
                                            

                                            
                                            










                                            
                                            
                                            <div class="leasing finansowy">
                                            <div class="produkt">
                                            
                                            
                                           
                                          
                                            
                                            </div>
                                                     
                                            </div>
                                            
                                            <div class="leasing operacyjny">
                                            <div class="produkt">
                                            
                                            
                                            
                                            
                                           
                                            </div>
                                                
                                            </div>
                                            

                                            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
                                             @csrf
                                             <button type="save" name="save" id="save" class="btn btn-primary" value="save">zapisz</button>
                                            </div>                                            
                                            

                                           
                                           
                                            </div>
                                   
                                  
                                

                            </div>


                        </form>

              </div>
        </div>
   </div>
  

 

@csrf

  
 </body>
</html>


@endsection

This is routes with dynamic-field for Ajax:

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllersPartnerController;
use AppHttpControllersLeasingController;
use AppHttpControllersDynamicFieldController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
    return view('dashboard');
})->name('dashboard');

Route::middleware(['auth:sanctum', 'verified'])->get('/proposals', function () {
    return view('proposals');
})->name('proposals');

Route::middleware(['auth:sanctum', 'verified'])->get('/proposal/{id_proposal}', function ($id_proposal) {
    return view('proposal', ['id_proposal' => $id_proposal]);
    //return $id_roposal;
})->name('proposal');



Route::middleware(['auth:sanctum', 'verified'])->get('/ileasing', function () {
    return view('dashboard');
})->name('ileasing');

Route::get('dynamic-field/insert', [DynamicFieldController::class, 'insert'])->name('dynamic-field.insert');
Route::resource('partners', PartnerController::class);
Route::resource('leasings', LeasingController::class);
Route::get('windykacja', [LeasingController::class, 'debtcollection'])->name('leasings.debtcollection');
Route::get('statystyki', [LeasingController::class, 'stat'])->name('leasings.stat');
Route::get('excel', [PartnerController::class, 'excel'])->name('partner.excel');

This is controller for Ajax where i am trying to get values using dd();

<?php

namespace AppHttpControllers;
use DB;
use IlluminateHttpRequest;
use AppModelsDynamicField;
use Validator;
use AppModelsLeasing; 


class DynamicFieldController extends Controller
{
    function index()
    {
       
     return view('livewire.leasings.create');
    }

    function insert(Request $request)
    {

      dd($request->all());



  /*    return response()->json([
       'success'  => 'Data Added successfully.'
      ]);
*/
            if(Request::ajax()) {
                                 $data = Input::all();
                                }  
        dd(json_encode($data));

      
/*

        $autoyear = date('Y');
        $automonth = date('m');
        
        $autonumber = DB::table("proforms as proforms")
            ->select(DB::raw('MAX(proformnumber) as proformnumber')) 
            ->where('automonth', '=', $automonth)
            ->where('autoyear', '=', $autoyear)   
            ->get();
            
            
            $autonumber[0]->proformnumber++;
            $number = $autonumber[0]->proformnumber;
            $number = "$number/$automonth/$autoyear/proforma"; */
 
    /*
    
    request()->validate([

    'user_id' => 'required',
    'proformdate' => 'required',
    'selldate' => 'required',
    
    'paymentdate' => 'required',
    'status' => 'nullable',
    'city' => 'nullable',
    'comments' => 'nullable',
 
    
    ]);
    
*/
   // $zero=1;

//      $request->request->add(['autonumber' => $number, 'automonth' => $automonth, 'autoyear'=> $autoyear, 'proformnumber'=> $autonumber[0]->proformnumber, 'issued'=> $zero, ]);
     
 //   Leasing::create($request->only(['user_id', 'proformdate', 'selldate', 'paymentmethod', 'paymentdate', 'status', 'city', 'comments', 'autonumber', 'automonth', 'autoyear', 'proformnumber', 'issued', 'form_id', 'currency_id', 'gross', 'net']));   

     if($request->ajax())
     {
      $rules = array(
       'przedmiot.*'  => 'required',
      
       'nazwa_przedmiot.*'  => 'required',
       'rok.*'  => 'required',
       'cena.*'  => 'required',
       'vat.*'  => 'required',
     
      );
      $error = Validator::make($request->all(), $rules);
      if($error->fails())
      {
       return response()->json([
        'error'  => $error->errors()->all()
       ]);
      }
      $autonumber = DB::connection('mysql2')->table("ileasing")
      ->select(DB::raw('MAX(id) as id'))  
      ->get();     
      
      $autonumber[0]->id++;
      $number = $autonumber[0]->id;
/*
      $autonumber2 = DB::connection('mysql2')->table("ileasing_przedmiot")
      ->select(DB::raw('MAX(id) as id'))  
      ->get();
  
      
      $autonumber2[0]->id++;
      $number2 = $autonumber2[0]->id; 
      $gross=0;                                                 
      $net=0; */

/*      $gross1 = DB::table('proforms')
      ->select(DB::raw('gross'))
      ->where('id', $number)
      ->first();

      $net1 = DB::table('proforms')
      ->select(DB::raw('net'))
      ->where('id', $number)
      ->first();
  */    
 //     $gross =$gross1->gross;
 //     $net =$net1->net;



      $przedmiot = $request->przedmiot;
    
      $nazwa_przedmiot = $request->nazwa_przedmiot;
      $rok = $request->rok;
      //$netunit = $request->netunit;
      $cena = $request->cena;
      $vat = $request->vat;
      //$ileasing = $request->ileasing;
      $numer_faktura = 21;

      for($count = 0; $count < count($przedmiot); $count++)
      {
      
       $data = array(
        'ileasing' => $number, 
     //   'id' => $number2++,  
        'przedmiot' => $przedmiot[$count],
       
        'nazwa' => $nazwa_przedmiot[$count],
        'rok'  => $rok[$count],
        'netto' => $cena[$count],
        'vat'  => $vat[$count],
      //  'ileasing' => $ileasing[$count],
        'numer_faktura'  => $numer_faktura,
        

       );
     //  $gross = $gross + $grosstotal[$count];
     //  $net = $net + $nettotal[$count]; 

       $insert_data[] = $data; 
      }
 /*    $affected = DB::table('proforms')
      ->where('id', $number)
      ->update(['gross' => $gross]);

      $affected2 = DB::table('proforms')
      ->where('id', $number)
      ->update(['net' => $net]);   */
      DynamicField::insert($insert_data);
     
      return response()->json([
       'success'  => 'Data Added successfully.'
      ]);
     }
    }
}

This is my model

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

class DynamicField extends Model
{


    protected $table='ileasing_przedmiot';
    protected $connection='mysql2';

    protected $fillable = [
        'przedmiot', 'nazwa', 'rok', 'netto', 'vat', 'ileasing', 'numer_faktura'
    ];

  /*  public function proform()
    {
        return $this->belongsTo('AppIleasing');
    }
*/
}

Source: Laravel

Leave a Reply