Suraj Libi
Suraj Libi

Reputation: 515

HTTP post appends null to the request data ionic

I have this data coming from form using

<form #form="ngForm" (ngSubmit)="myFunction(form.value)">

I am sending the form value to HTTP post method as

myFunction(formData){
   let headers = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded',
    });
    return new Promise( resolve => {
      this.http.post(this.my_api, formData, { headers: headers})
        .subscribe( data => {
          resolve(data);
        });
    });
}

When i console the form.data, i get

{name: 'myname', address:'myaddress'}

But what i get in the api is

{{"name":"myname", "address":"myaddress"} : null }

which is making me hard to get the values in my backend.

P.S. I am using Laravel as Backend

Why is that : null is getting appended to the request? How to get the values in the Laravel backend?

Upvotes: 2

Views: 91

Answers (1)

Sujan Gainju
Sujan Gainju

Reputation: 4769

You have to encode the form data and then send that to the API call

 getFormUrlEncoded(formData) {
        const formBody = [];
        for (const property in toConvert) {
            const encodedKey = encodeURIComponent(property);
            const encodedValue = encodeURIComponent(toConvert[property]);
            formBody.push(encodedKey + '=' + encodedValue);
        }
        return formBody.join('&');
    }

then call the function

this.http.post(this.my_api, this.getFormUrlEncoded(formData), { headers: headers})
        .subscribe( data => {
          resolve(data);
        });
    });

Upvotes: 1

Related Questions