Pravin
Pravin

Reputation: 441

How to pass php array to angularjs service

I am trying to pass a php array in ng-click function to have it in php controller.

Here is my code I am passing php array to angular function.

 <button type="button" class="btn btn-success" 
  ng-click="removeItem('<?php echo  htmlspecialchars(json_encode($value['BookingsHotel']));?>')">Cancel Room</button>

here is my code, i am accessing my posted data with angularjs service

$booked_rooms=htmlspecialchars_decode($this->request->data['rooms']);
$booked_rooms=json_decode($this->request->data['rooms']);

once we are doing json decode it gives a null value.

Upvotes: 0

Views: 572

Answers (1)

Mike J
Mike J

Reputation: 425

Since you're using angular. Just use $http to communicate with your PHP backend.

$http({method: 'POST', url: your_url_variable, contentType: 'application/json; charset=utf-8',
        data: {var1:angular_var1, var2:angular_var2},
        headers: { 'Content-Type': 'application/json; charset=utf-8' }
    }).success(function (result) {
        console.log("result", result);
    }).error(function (data, status, headers, config) {
        console.log('ERROR', data, status, headers, config);
    });

In your php page...

if($_SERVER["REQUEST_METHOD"] == "POST") {
        $postdata = file_get_contents("php://input");
        if(!empty($postdata)) {
            $post = json_decode($postdata);

            $var1 = $post->var1;
            $var2 = $post->var2;

            // do some stuff, then echo the response as json back to your app.

            $result = ["success" => true; "message" => "This is a test message"];
            header('Content-Type: application/json');
            echo json_encode($result);
        }
}

Upvotes: 2

Related Questions