1

I am trying to send from Laravel a response to an AJAX post request.

public function infoRoute(Request $request)
    {
        // Get info
        $ship_id = $request->ship_id;
        $startDate = $request->datepicker_start;
        $endDate = $request->datepicker_end;

        // Get all the locations between those dates
        $routeArray = $this->measurementRepository->getCoordinates($ship_id, $startDate, $endDate);

        $ship = $this->shipRepository->getShipForId($ship_id);
        $info = $this->createRouteArrayForShip($ship, $routeArray);

        if($request->ajax()) {
            return response()->json(json_encode($info));
        }
    }

    protected function createRouteArrayForShip($ship, $routeArray)
    {
        $info['type'] = "showRoute";

        $index = 0;

        foreach($routeArray as $coordinates)
        {
            $info['info']['route']['loc'. $index] = $coordinates;
            $index++;
        }

        $info['info']['shipInfo'] = $ship;

        //dd($info);
        return $info;
    }

When I receive the information and process it with jQuery, everything shows except from the route, that is empty.

Thank you,

6
  • if you use your browser developer tools.. what data do you see coming back in the response? Commented May 5, 2016 at 11:19
  • You have a multidimensional array there.. Commented May 5, 2016 at 12:39
  • Try to return it as a JSON Commented May 5, 2016 at 12:50
  • 1
    At least you don't need response()->json(json_encode($info));, use response()->json($info); Commented May 5, 2016 at 14:15
  • @Dale What I get back is an Object, containing an Object "info" and a string "type". Inside "info" I only get the object shipInfo. But there is no sign of route Commented May 6, 2016 at 7:46

1 Answer 1

3

The response()->json() method converts the given array into JSON using the json_encode() PHP function behind the scene. Therefor you should remove your json_encode() from inside the response()->json() call.

Basically it should look like this

return response()->json($info);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I have done that but it still isn't working. I think it has something to do with the fact that $info does not contain the coordinates from the route. It is sent empty. If I do dd($info) before returning the response, the route is empty. But when I call the function createRouteArrayForShip it actually saves the records in the array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.