Here I am trying to send my js object from react app to php file with the help of axios but I am not getting my data there instead it is returning null and connection is made successfully between react and php beacuse if I echo something in php it works but when I try to print object data it returns null so someone can please help me
import { useState } from "react";
import axios from "axios";
const App = () => {
const [username, setUsername] = useState();
const [password, setPassword] = useState();
let [input, setInput] = useState({ username: "", password: "" });
const nameChangeHandler = (e) => {
setUsername(e.target.value);
};
const passwordChangeHandler = (e) => {
setPassword(e.target.value);
};
const formHandler = (e) => {
e.preventDefault();
setInput(((input.username = username), (input.password = password)));
JSON.stringify(input);
axios.post("http://localhost:80/api/index.php", input);
console.log(input);
};
return (
<form onSubmit={formHandler}>
<label>Username</label>
<input type="text" onChange={nameChangeHandler} />
<label>Password</label>
<input type="password" onChange={passwordChangeHandler} />
<input type="submit" />
</form>
);
};
export default App;
PHP:
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: *");
$data = json_decode( file_get_contents("php://input"));
print_r($data);
var_dump($data);
?>
Related
So i'm building a QRcode scanner app.
When I scan a barcode, I want another modal to appear but I want to data (decoded from barcode) to be passed to my child Component which is ResponseModal.
here is my code
QrScanner.js
import { useHistory } from "react-router-dom";
import BarcodeScannerComponent from "react-qr-barcode-scanner";
import React, { useEffect, useState} from "react";
import axios from 'axios';
import ResponseModal from './ResponseModal';
const QrScanner = () => {
const [data, setData ] = useState('');
const [flag, setFlag] = useState(false);
const history = useHistory();
useEffect(() => {
if(data === '') {
return;
}
if (Number.isInteger(parseInt(data))) { // barcode scanned
axios.get('/some/endpoint/code/' + data)
.then(res => {
if (res.data != false) {
setFlag(true);
} else{
setData('Sorry, Wrong barcode!');
}
})
}
})
return (
<>
<BarcodeScannerComponent
width={500}
height={500}
onUpdate={(err, result) => {
if (result) {
setData(result.text);
}
}}
/>
<p className="modal-result-show">{data}</p> <---- this updates fine when barcode is scanned
<ResponseModal open={flag} data={data}/> <---- this is empty, why?
</>
);
}
export default QrScanner
And here is my ResponseModal:
import 'react-responsive-modal/styles.css';
import Modal from 'react-responsive-modal';
import React, {useEffect, useState} from "react";
const ResponseModal = (flag, data) => {
const [open, setOpen] = useState(false);
const onCloseModal = () => setOpen(false);
console.log(data); <----- empty
useEffect(() => {
if(flag.open === true) {
setOpen(true);
flag.open = false;
}
})
return (
<>
<Modal open={open} onClose={onCloseModal}>
<div className="qr-modal-header-stock">
<h5>Enter fulfillment stock</h5>
<form action="/some/another/endpoint/save" method="POST">
<input type="hidden" name="ean" value={data} /> <--- empty
<input type="number" name="product_stock" class="form-control"/> <br />
<input type="submit" class="btn btn-primary form-control"/>
</form>
</div>
</Modal>
</ >
);
}
export default ResponseModal
My question is, why am I not receing the data in my ResponseModal? I thought whenever {data} updates, everything that uses it also re-renders or being passed. What am I missing? I need {data} to do some logic with it on my backend side.
You are using props wrong way. props is one object, just update like this.
const ResponseModal = (props) => {
const {flag, data} = props;
}
When I try to upload a file on my Symfony API, I have an error from MediaObjectAction.php which is a controller.
This file looks like this :
final class CreateMediaObjectAction extends AbstractController
{
public function __invoke(Request $request): MediaObject
{
$uploadedFile = $request->files->get('file');
if (!$uploadedFile) {
throw new BadRequestHttpException('"file" is required');
}
$mediaObject = new MediaObject();
$mediaObject->file = $uploadedFile;
return $mediaObject;
}
}
and it throws me the error : "file" is required
In the front-end, I use ReactJS and I do a simple file upload with these functions :
const handleFileChange = (event) => {
console.log(event.target.files[0])
setFile({ selectedFile: event.target.files[0], loaded: 0 })
}
const uploadFile = () => {
FileUtils.uploadFile(MEDIA_OBJECT_ENDPOINT, file.selectedFile)
.then((response) => {
console.log(response)
})
const FileUtils = {
uploadFile: async (url, file) => {
const data = new FormData()
data.append('name', 'file')
data.append('file', file)
const response = await api.post(url, data)
return response
},
}
And in html, the file input looks like this :
<input
type="file"
id="file"
name="file"
onChange={handleFileChange}
></input>
As you can see, it is very basic, but it does not work and I cannot figure out why. Do you have an idea of what I miss ?
PS : The function api.post() works very well, the problem does not come from it.
In php, I cannot access the uploaded files in $_FILES instead they appear in $_POST["imgs"] as [object File] without any properties like name.
How can I get those files accessed in $_FILES?
import React, { useCallback } from 'react'
import { useDropzone } from 'react-dropzone'
import axios from 'axios'
const imgAjaxUploader = axios.create({
baseURL: 'http://localhost',
timeout: 1000,
headers: { 'Content-Type': 'mulipart/form-data' }
});
export default function ImgDropzone() {
const onDrop = useCallback(acceptedFiles => {
const formData = new FormData()
formData.append('imgs', acceptedFiles)
try {
imgAjaxUploader.post('/store/admin/imgHandler.php', formData, {
headers: {
'Content-Type': 'mulipart/form-data'
}
}).then(data =>
console.log(data)
).catch(err => {
console.log(err)
return null
})
} catch (err) {
alert(err)
}
}, [])
const { getRootProps, getInputProps, isDragActive } = useDropzone({ onDrop: onDrop, accept: 'image/jpeg, image/png' })
return (
<div {...getRootProps()} style={{ display: "inline-block" }}>
<input {...getInputProps()} />
{
isDragActive ?
<p>Drop the files here ...</p> :
<p>Drag 'n' drop some files here, or click to select files</p>
}
</div>
)
}
I found the solution. Multiple files need to be appended to the same name with a trailing [], in order to be compatible with PHP:
acceptedFiles.forEach(file => {
formData.append('imgs[]', file)
})
resource example 3
I'am trying to upload a file to the server by using a service which passes the file to the php backend.
It works, but only once. If I try to repeat uploading another file (without reloading the page) it does not get send and this error occurs:
ERROR TypeError: "this.fileManagerService.uploadFile is not a function"
playground.component.html
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input type="file" name="avatar" (change)="onFileSelect($event)" />
<button type="submit">Upload</button>
</form>
playground.component.ts
export class PlaygroundComponent implements OnInit {
form: FormGroup;
fileManagerResponse;
constructor(private formBuilder: FormBuilder, private fileManagerService: FileManagerService) { }
ngOnInit() {
this.form = this.formBuilder.group({
avatar: ['']
});
}
onFileSelect(event) {
if (event.target.files.length > 0) {
const file = event.target.files[0];
this.form.get('avatar').setValue(file);
}
}
onSubmit() {
const formData = new FormData();
formData.append('avatar', this.form.get('avatar').value);
this.fileManagerService.uploadFile(formData).subscribe(
(res) => {
this.fileManagerService = res;
console.log(res);
},
(err) => {
console.log(err);
}
);
}
}
FileManagerService.ts
export class FileManagerService {
SERVER_URL: string = "http://127.0.0.1/backend/api/";
constructor(private httpClient: HttpClient) { }
public uploadFile(data) {
let uploadURL = `${this.SERVER_URL}/filemanager/upload.php`;
return this.httpClient.post<any>(uploadURL, data);
}
}
The error occurred in below line.
this.fileManagerService = res;
You cannot assign res to the instance of the FileManagerService.
Remove it. Everything will be fine.
I am working on an Ionic 3 app. Where I need to upload the Image file, PDF file and form data in a single HTTP request.
I have tried Cordova file transfer plugin also but for that I have to call multiple requests (one for image and one for PDF), which I don't want to do.
I have tried each and every solution from google, but I couldn't find the right solution because each and every solution is for upload the image.
I am using PHP as backend. Please let me know where I am making the mistake.
This is HTML
<form (ngSubmit)="submitLicence()" [formGroup]="licence" enctype="multipart/form-data">
<ion-list inset>
<ion-item>
<ion-label>Licence Type</ion-label>
<ion-input type="text" formControlName="licence_type" placeholder="Value"></ion-input>
</ion-item>
<ion-item>
<ion-label>State</ion-label>
<ion-input type="text" formControlName="state" placeholder="Value"></ion-input>
</ion-item>
<ion-item>
<ion-label>Year</ion-label>
<ion-input type="number" formControlName="year" placeholder="Value"></ion-input>
</ion-item>
<ion-item>
<ion-label>Select PDF</ion-label>
<ion-icon name="md-add-circle" item-end color="secondary" (click)="selectPDF()"></ion-icon>
</ion-item>
<ion-item>
<ion-label>Take a Photo</ion-label>
<ion-icon name="md-add-circle" item-end color="secondary" (click)="presentActionSheet()"></ion-icon>
</ion-item>
</ion-list>
<div padding>
<button ion-button type="submit" type="submit" [disabled]="!licence.valid" block>Submit</button>
</div>
</form>
These functions are for upload pdf.
selectPDF(){
this.fileChooser.open()
.then(uri =>
{(<any>window).FilePath.resolveNativePath(uri, (result) => {
let loaderPdf = this.loadingCtrl.create({
content: "Uploading PDF..."
});
loaderPdf.present();
// this.fd.append('doc',result);
this.testResponse = result;
this.nativepath = result;
this.readfile(loaderPdf);
})
})
.catch(e =>
this.testResponse = 'Error - '+e);
}
readfile(loaderPdf) {
(<any>window).resolveLocalFileSystemURL(this.nativepath, (res) => {
res.file((resFile) => {
var reader = new FileReader();
// reader.readAsArrayBuffer(resFile);
reader.onloadend = (evt: any) => {
loaderPdf.dismiss();
var src = evt.target.result;
src = src.split("base64,");
var contentAsBase64EncodedString = src[1];
var contentType = src[0].split(':');
this.testResponse = contentType[1].replace(';','');
contentType = JSON.stringify(contentType[1].replace(';',''));
var fileBlob = new Blob([evt.target.result], { type: contentType});
this.fd.append('doc',fileBlob,'doc');
//do what you want to do with the file
}
reader.readAsDataURL(resFile);
})
})
}
These functions are to select images.
public presentActionSheet() {
let actionSheet = this.actionSheetCtrl.create({
title: 'Select Image Source',
buttons: [
{
text: 'Load from Library',
handler: () => {
this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
}
},
{
text: 'Use Camera',
handler: () => {
this.takePicture(this.camera.PictureSourceType.CAMERA);
}
},
{
text: 'Cancel',
role: 'cancel'
}
]
});
actionSheet.present();
}
public takePicture(sourceType) {
let loaderImage = this.loadingCtrl.create({
content: "Uploading Image..."
});
loaderImage.present();
var options = {
quality: 100,
sourceType: sourceType,
saveToPhotoAlbum: false,
correctOrientation: true
};
// Get the data of an image
this.camera.getPicture(options).then((imageData) => {
// Special handling for Android library
this.base64Image = imageData;
this.readImage(loaderImage);
}, (err) => {
this.presentToast('Error while selecting image.');
});
}
readImage(loaderImage) {
(<any>window).resolveLocalFileSystemURL(this.base64Image, (res) => {
res.file((resFile) => {
var reader = new FileReader();
// reader.readAsArrayBuffer(resFile);
reader.onloadend = (evt: any) => {
var src = evt.target.result;
src = src.split("base64,");
var contentAsBase64EncodedString = src[1];
var contentType = src[0].split(':');
this.testResponse = contentType[1].replace(';','');
contentType = JSON.stringify(contentType[1].replace(';',''));
var imageBlob = new Blob([evt.target.result], { type: contentType});
loaderImage.dismiss();
this.fd.append('image',imageBlob,'image');
//do what you want to do with the file
}
reader.readAsDataURL(resFile);
})
})
}
And finally, this function is for post the form.
submitLicence(){
const licenceFormValue = JSON.stringify(this.licence.value);
let loader = this.loadingCtrl.create({
content: "Submitting form..."
});
loader.present();
var lt = this.licence.value.licence_type;
var st = this.licence.value.state;
var yr = this.licence.value.year;
this.fd.append('type',lt);
this.fd.append('state',st);
this.fd.append('year',yr);
this.fd.append('mode','createNewLicence');
this.testResponse = licenceFormValue;
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
this.lic = this.httpClient.post('http://website.com/api.php',this.fd,{headers:headers});
this.lic.subscribe(data => {
loader.dismiss();
this.testResponse = JSON.stringify(data);
})
}
This is PHP script to upload data and images as well.
error_reporting(0);
date_default_timezone_set('GMT');
require_once './config/config_live.php';
include_once PATH_FRONT_LIBRARY . 'adodb5/adodb.inc.php';
include_once PATH_FRONT_LIBRARY . "ADODBClass_mysql.php";
include_once PATH_FRONT_LIBRARY_MAILER . "phpmailer/class.phpmailer.php";
include_once PATH_FRONT_LIBRARY_MAILER . "sendEmail.php";
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-
Disposition, Content-Description');
if ($_POST['json']) {
$data = json_decode($_POST['json'], true);
} else {
$jsonString = file_get_contents('php://input');
$jsonObj = json_decode($jsonString, true);
$data = $jsonObj;
}
if ($data["key"] == "difsfk") {
NOTE: The PHP API on which I am working is created by another person and I have to write ionic code as per PHP code.
have you tried with ionic native http library
please follow link : https://ionicframework.com/docs/native/http/
in body send your image and file data and other param.
post(url, body, headers)
For example :
let body = new FormData();
body.append(‘image’, imagedata);
body.append(‘pdf’, pdfdata);
body.append(‘desc’, “testing”);
this.http.post(“Your api endpoint”, body, options).subscribe(res => {
console.log(res);
});