Pass a JSON from the view to the route

4

I'm trying to send JSON of view to a route, but I can not. Unfortunately I know little about JSON , ajax , GET and POST .

In the view, json:

var json = {
  "numeroMesa": numeroMesa,
  "itens": itens 
};

Remembering that the variable numeroMesa is a global variable in javascript and itens is an array with some numbers.

Soon after, I have:

$.get('addPedido/' + json, function(data) {
  alert(data);
});

And on the route, I have:

Route::get('/addPedido/{json}', function($json) {
  $json = JSON_decode($json);
  return $json;
});

When I send, the alert does not show anything. I'm using the framework laravel .

    
asked by anonymous 03.02.2016 / 16:53

1 answer

3

It's not the best way, or I can still say it's wrong.

You are concatenating a javascript object with a string (in the url).

  var json = {
      "numeroMesa": numeroMesa,
      "itens": itens 
  };

$.get('addPedido/' + json)

In turn Laravel expects you to pass another segment (the url word between bars / ) when you use {json} .

A json string passed in the url would look bad and could cause errors. Not to mention you did not convert the json object to json through JSON.stringify .

The correct approach would be to use the url parameters in the ajax request. So:

$.get('addPedido/', json, function () { /**...**/ })

So, you could, by the route of Laravel , use the Input::get method to capture the values passed to the request parameter addPedido/

So:

Route::get('/addPedido', function() {
    $input = Input::only('numeroMesa', 'itens');

    var_dump($input['itens'], $input['numeroMesa']);
});

It is therefore not necessary to use json to send the data to Laravel . Just use the url parameters, so you can capture them in a GET request.

    
03.02.2016 / 17:05