Sent Variable to Controller via Ajax in Blade

- 1 answer

Ad

I have a variable contains this data below

{"_method":"PUT","_token":"rs8iLxwoJHSCj3Cc47jaP5gp8pO5lhGghF1WeDJQ","id":"1"}

I want to sent it to controller via Ajax

I've tried

$( "form#edit" ).on( "submit", function( event ) {
  event.preventDefault();

    $("#edit :input").each(function() {
        inputs[$(this).attr("name")] = $(this).val();
    });

    var $inputs = JSON.stringify(inputs);

    $.ajax({
        url: $url,
        type: 'PUT',
        dataType: 'json',
        data: $inputs ,
        success: function (data, textStatus, xhr) {

            console.log(data);
        },
        error: function (xhr, textStatus, errorThrown) {

            console.log('PUT error.', xhr, textStatus, errorThrown);
        }
    });

});

It kept failing on me. Did I do anything wrong ?

Ad

Answer

Ad

I think that your jQuery code is over complicated. Something just like that should work :

$.ajax({
    type: "PUT",
    url: $url,
    data: $("form").serialize(),
    success: function () {

    },
    error: function () {

    }
});

The jQuery function serialize() is the key here.

Ad
source: stackoverflow.com
Ad