2

I have a dropdown form where you can select one or more items. The selected items I want to send to a backend php script that will insert the selected values into a database. This is my angular insert function:

insertRepair: function (id_telefon, id_culoare, arrayPiese) {
                console.log(arrayPiese);
                http.get('../php/insert_reparatii.php', {
                    params: {id_telefon: id_telefon, arrayPiese: arrayPiese,
                        id_culoare: id_culoare}
                }).then(function () {
                }
            }

The call to this function is done like this:

serviceHttp.insertRepair($scope.phoneMP.selected.id, $scope.colorMP.selected.id, $scope.selectedPiesaMP.selected);

If I print into the console the arrayPiese array it will print for 2 selected items, something like this:

["Adezivi_Rama", "Polarizator"]

Now in the backend I retrieve the array list:

$arr = $_REQUEST['arrayPiese'];

If I print the $arr variable I get only one of two items printed. Need to mention that I migrated from jquery to angular, and from jquery I was able to send the entire array like this:

var arrayPiese = [];
$('.select2-selection__choice').each(function () {
    arrayPiese.push($(this).attr('id'));
});

The url looks like this arrayPiese=Adezivi_Rama&arrayPiese=Polarizator&id_culoare=1&id_telefon=18

Do I need to serialize the array before sending it to php? Or what would be the best approach in sending an array to backend??

2 Answers 2

4

You can pass array as json,

http.get('../php/insert_reparatii.php', {params: {id_telefon: id_telefon, arrayPiese:angular.toJson(arrayPiese),
            id_culoare: id_culoare}
    }).then(function () {
    }

Then in your PHP script, convert json to PHP array,

    $arrayPiese = json_decode($_GET['arrayPiese'], TRUE);
Sign up to request clarification or add additional context in comments.

Comments

2

arrayPiese=Adezivi_Rama&arrayPiese=Polarizator will result in a single variable $_REQUEST['arrayPiese'] with the value Polarizator because the latter overwrites the first one.

If you want to pass an array, you have to append brackets to the query parameter name:

arrayPiese[]=Adezivi_Rama&arrayPiese[]=Polarizator

…which will result in a PHP variable $_REQUEST['arrayPiese'] with an array value like:

[
    0 => 'Adezivi_Rama',
    1 => 'Polarizator'
]

3 Comments

hmm, looks easy, need to see how to append the brackets in angular
@AndreiMaieras I bet there is a method in Angular for this use case…
I found a solution by changing array param in the paramsobject like this: "arrayPiese[]":arrayPiese so for me this would be the accepted response

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.