Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mikebarwick's avatar

Laravel Data Handling From AngularJS http.post

I'm using a AngularJS library within my Laravel application, and the data returned is null. I'm assuming the data being sent by the AngularJS method is not being encoded/handled correct on the larval end.

Anything standing out? The AngularJS ajax method below has an alert(data) call in the success function that's returning blank.

UPDATE: When I console.log the data being passed to Laravel, "data=" + window.btoa(encodeURIComponent(jsonData)), it's outputting some data that's pretty foreign to me. This must be where I'm going wrong. How is Laravel suppose to process this? data=JTdCJTIydGV4dCUyMiUzQSUyMnNvY2lhbGJ1bmd5LmNvbSUyMiUyQyUyMmltYWdlQW1vdW50JTIyJTNBLTElN0Q=

AngularJS Ajax (send the form data):

var jsonData = angular.toJson({
    text: $text,
    imageAmount: $scope.imageAmount
});

    $http({
        url: url,
        method: "POST",
        data: "data=" + window.btoa(encodeURIComponent(jsonData)),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).success(function (data, status, headers, config) {   
    
        alert(data);
    });

Laravel Route:

    Route::group(['middleware' => 'auth'], function () 
    {
    
        Route::post('previewr/crawl', function (Previewr $previewr) 
        {
            if(Request::ajax())
            {
                return $previewr->crawl(Request::all());
            }
        });
    
    });

Laravel Method:

    class Previewr
    {
        /**
         * Crawl Text from <textarea>
         *
         * @return response
         */
        public function crawl($post)
        {
            SetUp::init();
    
            $data = json_decode(urldecode(base64_decode($post)));
    
            $text = $data->text;
            $imageAmount = $data->imageAmount;
            $text = str_replace("\n", " ", $text);
            $header = "";
    
            $linkPreview = new LinkPreview();
            $answer = $linkPreview->crawl($text, $imageAmount, $header);
    
            return $answer;
    
            SetUp::finish();
        }
    }
0 likes
1 reply
mikebarwick's avatar
mikebarwick
OP
Best Answer
Level 5

Issue actually wasn't the data being passed. The issue was the if(Request::ajax() condition. This looks for the wrong headers. So the request was never making it through. Instead, i had to use if(Request::wantsJson()) for AngularJS Ajax.

Please or to participate in this conversation.