2

On my page, I have one input that the user fills out.

Then, in my JS, I have an object, like so:

var obj = {
    sort: 'newest',
    num: 10,
    values: [1, 2, 3, 4]
};

As you can see, the object contains various types (a string, an integer, and an array). I need to pass both the input value and the object's data to Laravel under a post request with the original type (i.e. string, integer, array).

But currently, all the data is being passed as a string:

https://i.stack.imgur.com/y6NGU.png

Here is my current code:

$('form').on('submit', function (event)
{
    event.preventDefault();

    var form = $(this);

    var data = form.serializeArray();

    $.each(obj, function (key, val)
    {
        data.push({ name: key, value: val });
    });

    $.ajax({
        url: 'https://website.com/save',
        type: 'post',
        data: data,
        dataType: 'json',
        success: function (data)
        {
            //
        }
    });
});

What should I change to pass the data as their respective types?

  • 1
    [Send it as JSON](https://stackoverflow.com/questions/12693947/jquery-ajax-how-to-send-json-instead-of-querystring) and on your server use [`json_decode`](http://php.net/manual/en/function.json-decode.php) – Ivar Feb 08 '18 at 23:30
  • On server side, you can use unserialize function like unserialize($_POST['data']). – slon Feb 08 '18 at 23:31
  • It should work if you use like $data = $_POST['data']; $data['num'] or $data['sort'] etc.. – slon Feb 08 '18 at 23:34
  • @AslanShemilov I'm using Laravel, so doing that would go against the framework standards. – user1658132 Feb 08 '18 at 23:36
  • I gave you the example, so you use post like Laravel is using. – slon Feb 08 '18 at 23:36
  • @Ivar I just tried that. All it does is bundle the request into one array, meaning that Laravel validation can't read it. – user1658132 Feb 08 '18 at 23:36

2 Answers2

0

You have to change jQuery code like below:

var obj = {
  sort: 'newest',
  num: 10,
  values: [1, 2, 3, 4]
};

$.ajax({
  url: 'https://example.com/save',
  type: 'post',
  data: $.param(obj), //will become e.g. sort='newest'&num=10&etc..
  contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
  dataType: 'json',
  success: function (data)
  {
    //
  }
});
slon
  • 1,002
  • 1
  • 8
  • 12
0

As mentioned by @Ivar in comments, send your data as encoded and decode it in your server.

Hence you need to change your JS as

$('form').on('submit', function (event) {
    event.preventDefault();

    var formdata = new FormData();
    formdata.append('form', $(this).serialize());
    formdata.append('obj', JSON.stringify(obj));

    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });

    $.ajax({
        url: 'https://website.com/save',
        type: 'POST',
        data: formdata,
        processData: false,
        contentType: false,
        success: function (data)
        {
            //
        }
    });

});

and in your controller method you could decode the values as

public function yourMethod(Request $request)
{
    // You could access the form variables in $output array
    parse_str($request->form, $output);

    // Decode the obj variable
    $obj = json_decode($request->obj, TRUE);
}
linktoahref
  • 7,812
  • 3
  • 29
  • 51