0

I need to send an array of data using HttpClient of Angular 6 to PHP server.

I have some drop down list where I chose from and push into an array:

arrayOfLegalProtection=[];
addSit(){
    let l_id = '';
    let p_id = '';
    let s_id = '';
    let add_date = '';
    l_id = this.formGroup.controls['l_id'].value;

    p_id = this.formGroup.controls['p_id'].value;
    s_id = this.formGroup.controls['s_id'].value;
    add_date = this.formGroup.controls['add_date'].value;
    this.showSubHeader++;
    this.arrayOfLegalProtection.push({lId: l_id, 
      pId: p_id,
      sId: s_id, 
      addDate: add_date})
    console.log(this.arrayOfLegalProtection);
}

The console result is showing me the correct pushed values:

[{"lId":"1","prId":"1","sId":"2","addDate":"2018-09-14"},

{"lId":"","pId":"1","sId":"5","addDate":"2018-09-14"},

{"lId":"","pId":"2","sId":"","addDate":"2018-09-20"}]

Now, I need to add this array to httpclient post method and send it to the server, but as said in the discussion of this post, arrays cannot be sent through angular's HttpClient library.

We need to use append, or JSON.stringify() or .append().

I posted a question after using the method of JSON.stringify() and as you can see there was errors. And even the echo count($array) is always 1 even if the multidimensional array contains 0 or N rows of data.

So I switched, for the other method using the .append():

saveUnitData(unit_type, 
    location_type_id, user_id, number_of_hh, unit_status, add_date, arrayOfActualities)
  { 
    console.log(user_id);
    let httpParam = new HttpParams().set('unit_type', unit_type)
                                      .set('location_type_id', location_type_id)
                                      .set('user_id', user_id)
                                      .set('number_of_hh', number_of_hh)
                                      .set('unit_status',unit_status)
                                      .set('add_date', add_date);
    Object.keys(arrayOfActualities).forEach(key=>{
      httpParam = httpParam.append('arrayOfActualities', arrayOfActualities);
    })
                                      //.set('arrayOfActualities', arrayOfActualities);
    let headerOptions = new HttpHeaders();
    headerOptions.append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    console.log('h'+arrayOfActualities);
    return this.http.post(this.globalVar.UnitSavedataUrl, httpParam, {headers: headerOptions});
  }

Using this code:

Object.keys(arrayOfActualities).forEach(key=>{
          httpParam = httpParam.append('arrayOfActualities', arrayOfActualities);

I tried to convert an object into array using append so it can be sent through the httpClient service.

At the header of the request, we can see the ordinary data sent, but the array is being repeated hundreds and hundreds of times.

enter image description here

And the response from server is always:

C:\wamp64\www\dev\UnitSaveData.php:23:string '[{"legalId":"","protectionId":"","situationId":"","addDate":"2018-09-14"},{"legalId":"","protectionId":"","situationId":"","addDate":"2018-09-14"}]' (length=147)

But nothing was added to the database.

Please note that the PHP script is the same from the previous unanswered post

12
  • I've enever had an issue sending arrays to an API with the HttpClient. Post requests have a body where you can send virtually any js object. Http params are params that are appended to your url : if you use post requests, you don't need it. Commented Sep 10, 2018 at 7:37
  • Btw HttpHeaders is immutable, so you need to do this: let headerOptions = new HttpHeaders().append('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); Commented Sep 10, 2018 at 7:40
  • @trichetriche please check the github link added in my post and read about the issue of sending arrays using httpClients. If you are right maybe, I am having issue with building the array, so I added the method of pushing into the array. Commented Sep 10, 2018 at 7:58
  • 1
    @droidnation as told previously, there is no issue with sending arrays through post. If you have an issue, please provide a minimal reproducible example reproducing it. Commented Sep 10, 2018 at 8:05
  • 1
    Your PHP script is calling json_encode(), which produces a JSON string. If your intent is to transform JSON into an array, do json_decode(). Before anything, though, ensure that whatever you're passing into json_decode() is not already an array. Commented Sep 10, 2018 at 8:24

1 Answer 1

0

I found the solution.

Yes, HttpClient() do accept an array as HttpParams().

For the Angular script, I was doing the following:

let httpParam = new HttpParams().set('unit_type', unit_type)
   .set('location_type_id', location_type_id)
   .set('user_id', user_id)
   .set('number_of_hh', number_of_hh)
   .set('unit_status',unit_status)
   .set('add_date', add_date)
   .set('arrayOfActualities', arrayOfActualities); 

As the HttpParams() documentation mentioned, .set() take the value as a string which confused the server side script even when using json_encode().

So the solution was to append to arrayOfActualities the array:

let httpParam = new HttpParams().set('unit_type', unit_type)
    .set('location_type_id', location_type_id)
    .set('user_id', user_id)
    .set('number_of_hh', number_of_hh)
    .set('unit_status',unit_status)
    .set('add_date', add_date)
    .set('arrayOfActualities', arrayOfActualities);

httpParam.append('arrayOfActualities', JSON.stringify(arrayOfActualities));

At the PHP side, I need to use json_decode($arr, true), in order to let the server script iterate over an array, as iterating over a json array was making problem for me as it wasn't able to read the field titles because of double quotes:

$arr = json_decode($arrayOfActualities, true);
if(count($arr)>0)
  {
     foreach($arr as $array)
     {

     }
  }

...

As, like @B.Fleming said:

Your PHP script is calling json_encode(), which produces a JSON string. If your intent is to transform JSON into an array, do json_decode(). Before anything, though, ensure that whatever you're passing into json_decode() is not already an array.

Sign up to request clarification or add additional context in comments.

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.