Ngoni X
Ngoni X

Reputation: 145

Send cordova FileTransfer parameters to php server using ionic 2/3

I have a form that contains some fields and also uses the camera plugin to upload pics for ionic 2/3 to php server. So I would like to send the form data with an uploaded pic to the server. Below is my code:

add-event.html

<form (ngSubmit)="add_event()" #eventForm="ngForm">
<ion-item>
    <ion-label fixed>Title</ion-label>
    <ion-input placeholder="Title here"
       name="title" [(ngModel)]="eventData.title" required>
    </ion-input>
  </ion-item>

   <ion-item>
    <ion-label>Select Photo</ion-label>
    <ion-icon name="camera" (click)="presentActionSheet()" item-right></ion-icon>
   </ion-item>
    <img src="{{pathForImage(lastImage)}}" style="width: 100%" [hidden]="lastImage === null">
    <h5 align="center" [hidden]="lastImage !== null" class="preview_text">Photo Preview</h5>

<button ion-button full [disabled]="eventForm.invalid">Add Event</button>
</form>

add-event.ts

filename: string;
eventData = { title: '', image: this.filename};

public add_event() {
// Destination URL
var url = apiURL.BASE_URL+"add_events";

// File for Upload
var targetPath = this.pathForImage(this.lastImage);

 // File name only
 var filename = this.lastImage;

var options = {
fileKey: "file",
fileName: filename,
chunkedMode: true,
mimeType: "multipart/form-data",
params : this.eventData // Is this where i pass parameters to php?
};

const fileTransfer: FileTransferObject = this.transfer.create();

  this.loading = this.loadingCtrl.create({
    content: 'Submitting...',
  });
  this.loading.present();

 // Use the FileTransfer to upload the image
    fileTransfer.upload(targetPath, url, options).then(data => {
      this.loading.dismissAll()
      this.presentToast('Event succesfully added.');
      console.log(data);
      console.log(options);
      console.log(this.eventData);
    }, err => {
      this.loading.dismissAll()
      this.presentToast('Error while uploading event.');
      console.log(err);
    });

}

add.php (Using Slim Framework)

 $data = json_decode($request->getBody());

$title=$data->title; //returns null
$image=$data->image; //returns null

header('Access-Control-Allow-Origin: *');

// for image upload
$file_name = $_FILES["file"]["name"];
$tmp = $_FILES["file"]["tmp_name"];

$target_path = "../path/to/picfolder";

$target_path = $target_path . basename( $file_name );

Now the issue is that when I submit the form, the title and image parameters are not being received at the php side. How can I successfully pass the parameters on submit of the app?

Upvotes: 0

Views: 1410

Answers (1)

saperlipopette
saperlipopette

Reputation: 1693

Since you're sending your params in raw JSON, this is the way to retrieve the data on server-side : (just replace your first line with this)

json_decode(file_get_contents('php://input'), true);

Upvotes: 1

Related Questions