pavlenko
pavlenko

Reputation: 665

laravel 5 and Ajax get data from database:

I have simple form:

{{ Form::open(array('id' => 'frm')) }}

  <div class="form-group">
    {!!  Form::label('id','id:'); !!} 
    {!!  Form::text('id',null,['class' => 'form-control']); !!} 
  </div>

  <div class="form-group">
    {!!  Form::submit('Update',['class' => 'btn btn-primary form-control']); !!} 

{!! Form::close() !!}

I want to post the values from the form input fields to the controller then in the controller mthod run a query on the database for the id value from the form. Finally, using ajax, show the results of the DB query and if there are no results show a message alerting the user.

I have tried this:

<script>
    $("document").ready(function(){
        $("#frm").submit(function(e){
            e.preventDefault();
            var customer = $("input[name=postal]").val();
            $.ajax({
                type: "POST",
                url : "http://laravel.test/ajax",
                data : dataString,
                dataType : "json",
                success : function(data){

                }
            }, "json");
        });
    });//end of document ready function
</script>

I have tried a couple of ways to get the post data in the controller but have had no success.

---Problem 1:

There is problem when I try to use this in route:

Route::post('ajax', function() { // callback instead of controller method
    $user = App\User::find(\Input::get('id');
    return $user; // Eloquent will automatically cast the data to json
});

I get sintax error,on second line for (;)

Also, I try to get data in controller and than print them:

 if(Request::ajax()) {
      $data = Input::all();

      print_r($data);die;
    }

ROUTES.PHP

Route::post('/', 
  ['as' => 'first_form', 'uses' => 'TestController@find']);

Route::get('/', 'TestController@index');
  Route::post('ajax', function() { // callback instead of controller method
        $user = App\User::find(\Input::get('id');
        return $user; // Eloquent will automatically cast the data to json
    });

Function:

    public function ajax()

    {
        //

  // Getting all post data
    if(Request::ajax()) {
      $data = Input::all();
      print_r($data);die;
    }

    }

I found a couple more ways to send data from view to controller,but even woant show posted data. I check with fire-bug,there is posted value in post request

Upvotes: 0

Views: 9974

Answers (1)

haakym
haakym

Reputation: 12358

It appears you're passing your ajax method a variable that doesn't exist. Try passing it the form data directly and see if that yields any results, you can do this with the serialize method:

$("#frm").submit(function(e){
    e.preventDefault();
    var form = $(this);
    $.ajax({
        type: "POST",
        url : "http://laravel.test/ajax",
        data : form.serialize(),
        dataType : "json",
        success : function(data){
            if(data.length > 0) {
              console.log(data);
            } else {
              console.log('Nothing in the DB');
            }
        }
    }, "json");
});

The ajax call has console.log in it now so it will output anything returned to it in the console.

routes.php (an example)

Route::post('ajax', function() { // callback instead of controller method
    $user = App\User::find(\Input::get('id'));
    return $user; // Eloquent will automatically cast the data to json
});

Please bear in mind I am just putting the code as an example as you didn't put your controller code in the question.

EDIT

I'm going to make a really simple example that works for you. I have made a fresh install of laravel and coded this and it's working fine for me. Please follow along carefully.

app/Http/routes.php

<?php
// route for our form
Route::get('/', function() {
    return view('form');
});
// route for our ajax post request
Route::post('ajax', function() {
    // grab the id
    $id = \Input::get('id');

    // return it back to the user in json response
    return response()->json([
        'id' => 'The id is: ' . $id
    ]);
});

resources/views/form.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Ajax Example</title>
</head>
<body>

    {!! Form::open(['url' => 'ajax', 'id' => 'myform']) !!}
        <div class="form-group">
            {!!  Form::label('id','id:') !!} 
            {!!  Form::text('id', null, ['class' => 'form-control']) !!} 
        </div>

        <div class="form-group">
            {!!  Form::submit('Update',['class' => 'btn btn-primary form-control']); !!} 
        </div>
    {!! Form::close() !!}

    <div id="response"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $("document").ready(function(){
        // variable with references to form and a div where we'll display the response
        $form = $('#myform');
        $response = $('#response');

        $form.submit(function(e){
            e.preventDefault();

            $.ajax({
                type: "POST",
                url : $form.attr('action'), // get the form action
                data : $form.serialize(), // get the form data serialized
                dataType : "json",
                success : function(data){
                    $response.html(data['id']); // on success spit out the data into response div
                }
            }).fail(function(data){
                // on an error show us a warning and write errors to console
                var errors = data.responseJSON;
                alert('an error occured, check the console (f12)');
                console.log(errors);
            });
        });

    });
</script>

</body>
</html>

Upvotes: 1

Related Questions