Search code examples
phpjsonajaxangularjs-scopejsondecoder

How to receive a json object filled up with angularjs and sent by ajax to server side (PHP)?


I have the following json object:

$scope.sellAccessories=
 [
 {"id": "1","name": "aa", "quantity": "3","total_price": "100"}
 ,
 {"id": "2","name": "bb", "quantity": "4","total_price": "200"}
 ,
 {"id": "3","name": "cc", "quantity": "5","total_price": "300"}
];

i sent the object using ajax as follow:

var options={
    type : "get",
    url : "../php/sell.php",
    data: {"function":"sellAccess","data":$scope.sellAccessories},
    dataType: 'json',
    async : false,
    cache : false,
    success : function(response,status){
        alert("success")
    },
    error:function(request,response,error){
        alert("error")
    }
};
$.ajax(options);

I tried to receive the data using $_GET['name'] but it didn't work

My php code:

$item_name=json_decode($_GET['name']);

i also, tried to do: $data=json_decode($_GET['data']);

but none of them works!

thanks in advance


Solution

  • You need to retrieve the data based on the url query. So for example if you need the JSON data then you would retrieve the JSON by doing

    $jsonData = $_GET['data'];

    Then you would have to process this JSON object and you can make it an array by using the PHP function json_decode like so

    $arrayData = json_decode($jsonData, true);

    Then you can traverse said data, as any other array.