简体   繁体   中英

How To Pass Jquery Values / Variables To PHP In Laravel

I am creating a Ticket Reservation System and I want to insert data into the Database. As usual, I used HTML form and all the data goes to the database except seat numbers. And it doesn't give me an error. For the seat numbers, I used Jquery and I want to insert that Jquery values into the database. I don't know is this possible or not. ( Seat numbers = items )

Form and Seat Structure Image

How can I Fix this?

Here is my Seat.blade.php

#holder{    
 height:300px;   
 width:800px;
 background-color:#F5F5F5;
 border:1px solid #A4A4A4;
}

 #place {
 position:relative;
     margin-top:33px;
 margin-left:35px;
 }

 #place a{
 font-size:80%;
 }

 #place li
 {
     list-style: none outside none;
     position: absolute;   
 }  

 #place li:hover
 {
    background-color:yellow;      
 } 

 #place .seat{
 background:url("img/Other/Available Seat.png") no-repeat scroll 0 0 transparent;
 height:30px;
 width:45px;
 display:block;  
 }

  #place .selectedSeat
  { 
background-image:url("img/Other/Disabled Seat.png");         
  }

   #place .selectingSeat
  { 
    background-image:url("img/Other/Booked Seat.png");           
  }

  #place .row-3, #place .row-4{
    margin-top:10px;
  }

  #seatDescription li{
  verticle-align:middle;      
  list-style: none outside none;
  padding-left:35px;
  height:35px;
  float:left;
      font-family: Times New Roman;
  font-size:120%;
  color:#353c47;
  }

</style>    

<form class="form-horizontal" id="form1" method="POST" action="{{ route('seatsinsert') }}" enctype="multipart/form-data">    

    {{ csrf_field() }}    

    <div class="dt"> <br>

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

        <div class="form-group row">
            <label for="example-date-input" class="col-2 col-form-label">Select Date :</label>
            <div class="col-10">
                <input class="form-control" type="date" name="date" placeholder="mm-dd-yyyy" id="example-date-input">
            </div>
        </div>

        <div class="form-group">
            <label for="exampleSelect1">Select Time :</label>
            <select name="st" class="form-control" id="exampleSelect1">
                <option>10.30 am</option>
                <option>1.30 pm</option>
                <option>4.30 pm</option>
                <option>7.30 pm</option>
            </select>
        </div>  

    </div>

    <h2 style="font-size:1.2em;font-family: Times New Roman;"> Choose seats by clicking below seats :</h2>

    <div id="holder"> 
        <ul id="place">
        </ul>    
    </div>

    <input type="submit" class="btn btn-primary" id="btnShowNew" value="Continue"> <br><br>

    <script type="text/javascript">

        $(function () {

            $('#btnShowNew').click(function () {
                var str = [], item;
                $.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
                    var item = $(this).attr('title').val();
                    //str.push(item);                   
                    $.ajax({
                        type: "post",
                        url: "{{ route('seatsinsert') }}",
                        data: {items: item}
                    })

                });

                //alert(str.join(','));
            })
        });

    </script>
</form>

Here is my SeatController.php

public function seatsinsert(Request $request) {

    $date = $request->input('date');
    $st = $request->input('st');
    $item = $request->input('items');
    //$item = item;

    $user = new Seats();
    $user->date = $date;
    $user->st = $st;
    $user->item = $item;

    $this->validate($request, [
        'date' => 'required'
    ]);

    $user->save();

    $request->session()->flash('Msg', 'Successfully Inserted !!');

    return redirect('Seats');
}

Here are my Routes.

Route::post('seatsinsert', [
    'uses' => 'SeatsController@seatsinsert',
    'as' => 'seatsinsert'
]);

For efficiency's sake, move the $.ajax outside of the loop and only submit once. Collect items as an array of item values, then POST a single time.

$('#btnShowNew').click(function (e) {
    e.preventDefault();

    var items = [];
    $.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
        items.push($(this).attr('title'));
    });

    $.ajax({
        type: "post",
        url: "{{ route('seatsinsert') }}",
        data: {
            _token: "{{ csrf_token() }}",
            items: items,
            date: $('input[name=date]').val(),
            st: $('select[name=st]').val()
        }, success: function(data){
            console.log(data.message); // "Success"
        }
    });
});

EDIT: Since $("#btnShowNows") is an <input type="submit" ... you need to prevent the submit when being pressed:

$('#btnShowNew').click(function (e) {
    e.preventDefault();
    ...

To actually handle the AJAX submission. Also note how I added the _token value to your data being submitted; should avoid any CSRF_TOKEN exceptions.

You'll have to adjust your PHP to handle items as an array too, but that's pretty easy:

$this->validate($request, [
    'date' => 'required'
]);

foreach($request->input("items") AS $item){
    $user = new Seats();
    $user->date = $date;
    $user->st = $st;
    $user->item = $item;

    $user->save();
}

Although another side note on variable naming arises from this; $user is not a good variable name for an instance of a Seats model.

Also, models are by tradition singular ( Seat , not Seats ) while the database they are attached to is plural ( tbl_seats , seats , etc)

Also also, $date and $st would be null here, since they aren't being submitted in the data section of your $.ajax request. To fix this, we would add:

data: {
    _token: "{{ csrf_field() }}",
    items: items,
    date: $('input[name=date]').val(),
    st: $('select[name=st]').val()
}

Unless explicitly included in an AJAX request, FORM elements will not be submitted, as the form is never physically submitted (via form.submit() or otherwise). Think of AJAX as a copy of a form and all of it's elements being submitted without actually submitting it.

Lastly (I hope) return redirect('Seats'); does nothing for an AJAX request. You should use:

return response()->json(["message" => "Success"], 200); // Customize as needed

And handle via the success function in your $.ajax request:

$.ajax({
    type: "post",
    url: "{{ route('seatsinsert') }}",
    data: {
        _token: "{{ csrf_field() }}",
        items: items,
        date: $('input[name=date]').val(),
        st: $('select[name=st]').val()
    }, success: function(data){
        console.log(data.message); // "Success"
    }
});

Isn't it better to keep all the form in 1 piece .. add a hidden input field (or any other type) .. record the seat number/s in the value and pull that data from there.

<input type='hidden' name='seatNumbers' value='' id='seatNumbers'>

on Laravel side : $request->input('seatNumbers')

on the JS side : object.getElementById('seatNumbers').value
// you need to use this because .val() is not
updating the value in html but adding another node.

You might want to change this:

var item = $(this).attr('title').var();

To this:

var item = $(this).attr('title').val();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM