send array data from ionic 3 app to php page - ionic-framework

please help me with this issue, i'm trying to send data in array form from ionic 3 app and need to receive it in php code
my code:
this.listArray = [
{'title': 'testTitle'},
{'body': 'testbody'},
{'footer': 'testfooter'},
];
var headers = new Headers();
headers.append("Accept", "application/json");
let options = new RequestOptions({ headers: headers });
let body = new FormData();
body.append("file", this.listArray);
this.http
.post("https://android.test.com/test.php",
body,options)
.map(res => res.json())
.subscribe(data => {
console.log(data['_body']);
alert("success")
}, error => {
console.log(error);
alert("error")
});
});
php:
$arrayLength = count($_POST['file']);
$message = $message."<p> ".$arrayLength."</p>";
$i = 0;
while ($i < $arrayLength)
{
echo $_POST['file'][$i] ."<br />"; $i++;
}
any suggestions are appreciated

Related

Ionic 4: Setting native http post headers properly

I'm struggling to find the solution to my problem with ionic native http.
I tried the answer to this post, but still i am getting the same error
this is my code
switchToggle(){
let url = 'https://io.adafruit.com//api/v2/myusername/feeds/my-feed-id/data/';
const headers = new Headers();
headers.set("Content-Type", "application/json")
headers.set("X-AIO-Key", "PASTED_MY_KEY_HERE");
let data = {
"datum":{
"value" : 1
}
};
this.http.setDataSerializer('json');
this.http.post(url,data,{headers:headers})
.then(data => {
console.log(data);
}).catch(error => {
console.log(error)
});
}
and this is the error I am getting
when I try other post request without headers it is working fine. But for this specific API I need to send the request together with the headers.
set your header like this =>
setHeaders() {
let headers = new Headers();
headers.append("X-AIO-Key", "PASTED_MY_KEY_HERE");
headers.append('Content-Type', 'application/json' );
const requestOptions = new RequestOptions({ headers: headers });
return requestOptions;
}
switchToggle(): Observable<any>{
let data = {
"datum":{
"value" : 1
}
};
return this.http.post(url, data, this.setHeaders())
.map(Response => Response.json())
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}

Ionic formData append showing null in server

I am trying to upload an image using formData. The api is working fine. But the data is displaying null in the server.
My function is
capture_dl_front(){
this.camera.getPicture(this.cameraOptions)
.then(imageData => {
this.customer.dl_front = normalizeURL(imageData);
this.upload_dl_front(imageData);
}, error => {
this.func.showAlert('Error',JSON.stringify(error));
});
}
upload_dl_front(imageFileUri: any): void {
this.file.resolveLocalFilesystemUrl(imageFileUri)
.then(entry => (<FileEntry>entry).file(file => this.readFile_dl_front(file)))
.catch(err => console.log('Error',JSON.stringify(err)));
}
private readFile_dl_front(file: any) {
const reader = new FileReader();
reader.onloadend = () => {
const imgBlob = new Blob([reader.result], { type: file.type });
this.dl_front_imageUri = imgBlob;
this.dl_front_imageName = file.name;
alert(this.dl_front_imageName)
const img = new FormData();
img.append('image', this.dl_front_imageUri, this.dl_front_imageName)
this.api.test(img).then(data=>alert("final: "+data))
};
reader.readAsArrayBuffer(file);
}
and my api function is
test(image){
let headers = new HttpHeaders({
'Content-Type': 'application/x-www-form-urlencoded',
});
return new Promise( resolve => {
this.http.post(url, image, { headers: headers})
.subscribe(
data => {
resolve(data['message']);
},
error => {
resolve(error.statusText);
}
);
});
}
and i am getting the file in my laravel server as
$image = $request->file('image');
but i am getting null in the image parameter.
What am i doing wrong here?
You should remove the headers in the api call.
test(image){
return new Promise( resolve => {
this.http.post(url, image)
.subscribe(
data => {
resolve(data['message']);
},
error => {
resolve(error.statusText);
}
);
});
}

How to make http GET/POST request in ionic 2?

How to http GET/POST request in ionic2
and what are the data need to import ?
I tried with HTTP GET request in JavaScript? but it does not work for me.
GET Example
this.posts = null;
this.http.get('https://www.reddit.com/r/gifs/top/.json?limit=2&sort=hot').map(res => res.json()).subscribe(data => {
this.posts = data.data.children;
});
console.log(this.posts);
https://www.joshmorony.com/using-http-to-fetch-remote-data-from-a-server-in-ionic-2/
POST Example
let headers = new Headers();
headers.append('Content-Type', 'application/json');
let body = {
message:"do you hear me?"
};
this.http.post('http://spstest.000webhostap..., JSON.stringify(body), {headers: headers})
.map(res => res.json())
.subscribe(data => {
console.log(data);
});
}
https://www.joshmorony.com/how-to-send-data-with-post-requests-in-ionic-2/
Good luck.
For Creating the request firstly we need to add provider by using this command :-
$ ionic g provider restService
here restService is the ts file name in which we write the below code for making request
load() {
console.log(' RestServiceProvider Load Method fro listing');
let postParams = { param1 : '', param2: '' }
if (this.data) {
return Promise.resolve(this.data);
}
// don't have the data yet
return new Promise(resolve => {
this.http.post("YOUR URL", postParams)
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
In the above code load() is the method of restService class.this method is help out to make the request .This method is called in your other class like this.
this.restSrvProvider.load().then(data => {
let mydata = data;
});
For more knowledge you may go through the ionic blog the

Angular 2 Http Post with Promise failing, not sending data

I am attempting to make a http.post call with angular 2. I have tested the call in postman, so I know that the api is working. I get an error, input empty which means that it isn't getting the data. I've read a few answers and articles, but not able to make a successful call with the data.
Can anyone give me some insight into what I am missing?
public upload(name: string, data: any, result, contentType: string) : Promise<Response> {
let headers = new Headers({ 'Content-Type': contentType });
let options = new RequestOptions({ headers: headers });
return this.http
.post(this.urlAPI, data, options)
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
extractData(res:Response) {
console.log('res: ', res);
let body = res.json();
return Promise.resolve(res);
}
handleError(err: any): Promise<any> {
console.error('An Error has occured: ', err);
return Promise.reject(err);
}
I am not sure what is the type of your 'data'. Data has to be stringified before sent. Below is a workable version for me.
saveNote(note: ApprovalNoteModel): Observable<ApprovalNoteModel> {
let body = JSON.stringify(note);
let headers = this.utilsSvc.getAuthHeaders();
headers.set('Content-Type', 'application/json');
return this.http.post('cloud/api/approval/note', body,
{ headers: headers }
).map(response => response.json());
}
If it is a file, then you can not do that thru 'http', I believe. Here is my workable version.
addFileRequest(referenceId: number, licenseId: number, url: string, files: File[]): Observable<any> {
return Observable.create(observer => {
this.progressObserver = observer;
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
formData.append('referenceId', referenceId);
formData.append('licenseId', licenseId);
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(xhr.response);
observer.complete();
} else {
if (xhr.response.status)
observer.error(xhr.response);
else
observer.error({ 'status': xhr.status, '_body': xhr.response });
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.setRequestHeader('Authorization', this.utilsSvc.getToken());
xhr.send(formData);
});
}

ionic 2 http request after oauth not working

I have a button redirect to this function
loginGoogle() {
this.cordovaOauthG.login().then((success) => {
console.log("Google Login DONE ");
if (success != null) {
console.log(JSON.stringify(success));
//alert(success.access_token);
if (success.access_token != null && success.access_token != '') {
var params = "google_id=" + success.access_token;
// var token = success.access_token;
// this.postLoginGoogle(params);
this.tesLogin();
}
}
}, (error) => {
alert(error);
});
}
and this is the function for http request
tesLogin(){
// var params = "google_id="+gid;
var params = "google_id="+'ya29.Ci_4ApeVHCD7av30Y82JRZPLG4T9ZUgmU1SNLUGIlVV_ufAcCoBc4ILqsY6Ah55i-g';
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
console.log(params);
this.http.post(Config.base_url + 'api/user-account/login-google', params, {headers: headers})
.map(res => res.json()).subscribe(data => {
console.log(data);
if (data.success) {
this.local.set('access_token', data.message);
this.menu.enable(true);
this.nav.setRoot(HomePage);
}
else {
this.doAlert("Incorrect email or password");
}
});
}
My problem is, whenever I tried to call using success.access_token, it doesnt work
but If I am calling the request without any parameters(just throwing in some random strings) then it works
I tried to debug it using mobile inspector from chrome, either way it is returning a error like this (working post & not working post both returning error)
EXCEPTION: SyntaxError: Unexpected token < in JSON at position 1
I suggest to send the authentication token in the header not in the parameters. Something like that:
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Bearer ' + authToken);