0

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

Ali
  • 1,633
  • 7
  • 35
  • 58

1 Answers1

1

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.

Classified
  • 560
  • 1
  • 7
  • 21
  • so whats wrong in this? `$jsonData = $_GET['data'];` `$arrayData = json_decode($jsonData, true);` `$item_id=$_GET['id'];` `file_put_contents("hell.txt", $item_id);` – Ali May 08 '18 at 10:15
  • Where is $_GET['id'] defined? You don't use the $_GET variable to traverse arrays. I would highly suggest you read up on [this on PHP arrays.](https://www.w3schools.com/php/php_arrays.asp) – Classified May 08 '18 at 10:18
  • oh sorry i meant this: `$item_id=$arrayData[0]['id'];` `file_put_contents("hell.txt", $item_id);` – Ali May 08 '18 at 10:19
  • What's the issue with that? That should result in 1. Did you remember to add `true` as the second parameter to the `json_decode` so it becomes an associative array – Classified May 08 '18 at 10:24
  • yes, i surely did :S, maybe the problem from the js side? since i am sending the data in the ajax in this for: `{"function":"sellAccess","data":$scope.sellAccessories}` – Ali May 08 '18 at 10:30
  • Try from within your PHP server, to dump the array using `var_dump($jsonData)` and then doing it again after the conversion to the associative array. – Classified May 08 '18 at 10:31
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170605/discussion-between-classified-and-aly-al-ameen). – Classified May 08 '18 at 10:32