0

I followed the following tutorial (https://code.tutsplus.com/tutorials/laravel-4-a-start-at-a-restful-api-updated--net-29785) to create a REST API with Laravel. Here we're creating a new Url which gets two inputs: a url and description and stores it to a database.

public function store()
{
    $url = new Url;
    $url->url = Request::get('url');
    $url->description = Request::get('description');
    $url->user_id = Auth::user()->id;

    $url->save();

    return Response::json(array(
        'error' => false,
        'urls' => $urls->toArray()),
        200
    );
}

In trying to teach myself AngularJS, I've been trying to connect this REST API with an AngularJS front end. Here's my form:

<form data-ng-controller="formController">
    <p>Store a URL To Read Later:</p>
    <div class="form-group">
        <input class="form-control" type="text" placeholder="Enter URL here" data-ng-   model="newurl" />
    </div>

    <p>Description:</p>
    <div class="form-group">
        <input class="form-control" type="text" placeholder="Enter a brief description" data-ng-model="newdescription" />
    </div>

    <div class="form-group text-right">
    <button class="btn btn-success" data-ng-click="submitUrl()">Add To List</button>
    </div>
</form>

The data-ng-click is calling the submitUrl function which I have defined in the FormController.

function formController($scope, $http) {
    $scope.submitUrl = function() {
        var data = { 'url': $scope.newurl, 'description': $scope.newdescription };
        $http.post("http://readitlater.loc/api/v1/url/", data )
    }
}

I guess I'm puzzled as to how to get the input data to the public function store() and what kind of data it's expecting. Thanks for your time.

2 Answers 2

2

I figured it out. Rewriting like this, solved the problem.

 function formController($scope, $http) {
    $scope.submitUrl = function() {
        var data = { 'url': $scope.newurl, 'description': $scope.newdescription };
        $http({
            method: 'POST',
            url: 'http://readitlater.loc/api/v1/url/',
            headers: { 'Content-Type' : 'application/x-www-form-urlencoded'},

            data: $.param(data)
        });
Sign up to request clarification or add additional context in comments.

2 Comments

I did the same, but getting Referenceerror: $ is not defined, any clue?
@Haseeb $.param is a function of jQuery. You need include a jQuery library in your application.
0

AngularJS sends POST requests with application/json type & JSON body by default. I'm not familiar with Laravel, but looks like using Input instead of Request is what you need: http://laravel.com/docs/4.2/requests#basic-input

Comments

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.