Tarenk 77
Tarenk 77

Reputation: 95

Laravel with ajax does not save data

Hi I am trying to implement ajax in my laravel project to save records.

First I display a list of products in the view. The following script is used to fetch products from database. This works without any problem:

<script>
    var Show = function(id) {
        var route = "{{url('products')}}/"+id+"/showProduct";
        $.get(route, function(data) {
            $("#name").val(data.pro_nom);
            $("#price").val(data.pro_prec);
            $("#pro_id").val(data.pro_id);  
        });
    }
</script>

This is my button in the modal to send the data

<button type="button" class="btn btn-primary" id="addProduct">Save</button>

This is the Ajax script:

$("#addProduct").click(function() {
    var dc_cant=1;
    var col_id=1;
    var pro_id=$("#pro_id").val();
    var route="{{action('ProductsController@store')}}";
    var token=$("#token").val();
 
    $.ajax({
        url: route,
        headers:{'X-CSRF-TOKEN':token},
        type:'POST',
        dataType:'json',
        data: {    
            pro_id: pro_id,
            dc_cant: dc_cant,
            col_id: cold_id
        },
        success: function(data) {
            if (data.success=='true') {
                alert("save");     
            }
        },
        error: function(data) {
            alert("error");
        }
    });
});

And this is the code in the controller:

public function store(Request $request)
{
    if ($request->ajax()) {           
        $result = detail_product::insert($request->all());

        if ($result) {
            return response()->json(['success'=>'true']);
        } else {
            return response()->json(['success'=>'false']);
        }            
    }       
}

No record is saved and I don't know where my code fails, it is the first time I try to implement ajax, until the moment the modal is shown with the data it works, but when I press to save it does nothing

Upvotes: 0

Views: 938

Answers (2)

bhucho
bhucho

Reputation: 3420

If you have not added meta tag of csrf token, you can add it.

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

Then in jquery,

<script>
    $(document).ready(function(){
        var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
        $(".postbutton").click(function(){
            $.ajax({
                url: '/storeProduct', //put your url here directly
                type: 'POST',
                /* send the csrf-token and the input to the controller */
                data: {_token: CSRF_TOKEN, pro_id: pro_id,
                                           dc_cant: dc_cant,
                                           col_id: col_id
                      },
                dataType: 'JSON',
                /* here 'data' is the response of the Controller */
                success: function (data) { 
                    $(".writeinfo").append(data.msg); 
                }
            }); 
        });
   });    
</script>

Access the data as $request->pro_id, $request->col_id .. etc.

Upvotes: 0

Erwin Smith
Erwin Smith

Reputation: 75

as alternative because i no longer use jquery, you can use axios it's very simple to use all what you have to do is to import cdn then do something like that :

const axios = require('axios');

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    // handle success
    console.log(response);
  })
  .catch(function (error) {
    // handle error
    console.log(error);
  })
  .then(function () {
    // always executed
  });

you can setup global variable to catch response and errors. or directly you can manipulate you data in the then(). axios uses behind the scenes jquery anyway more details about axios https://github.com/axios/axios

Upvotes: 0

Related Questions