I'm new to react and want to use it with index.php. I made my react project using create-react-app. I researched about it and found that you can use react with php after building it. But I want to work with development mode. Please help me with this.
use another server for PHP;
first debug React, "npm start" http://localhost:3000/
let buttonPHPSet = () => document.getElementById("buttonPHP").addEventListener("click", (e) => {
const that = e.target;
const data = {
"p": "7",
"h": "2",
"P": "3"
};
postAjax("http://my-app.local/controller/HomeController.php", data, (result) => {
let json = JSON.parse(result);
that.textContent = JSON.stringify(json);
console.log(json);
});
}, false);
function postAjax(url, object, success) {
let xhr = new XMLHttpRequest();
xhr.open('POST', url, true); //URL-aдpec интерпретируется относительно страницы, с которой вызывается код, хотя можно указать и абсолютный путь //только готовит его к отправке
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
success(xhr.responseText);
}
};
xhr.setRequestHeader('Content-Type', 'text/plain; charset=UTF-8');
xhr.send(JSON.stringify(object));
// let xhrFormData = new FormData();
// for (const key in object) {
// if (object.hasOwnProperty(key)) {
// xhrFormData.append(key, object[key]);
// }
// }
// xhr.send(xhrFormData);
// const allHeaders = xhr.getAllResponseHeaders();
// xhr.abort();
return xhr;
}
sec debug php whis IIS http://my-app.local/
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");
header('Content-Type: text/plain; charset=utf-8');
// header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT");
// header('Access-Control-Allow-Credentials: true');
// header('Content-Type: application/json;charset=UTF-8');
// header('Content-type: application/xml');
// header('Content-type: multipart/form-data);
// header('Content-type: text/html;charset=utf-8);
// header('Content-type: application/x-www-form-urlencoded; charset=UTF-8);
$postdata = file_get_contents("php://input");
$postDataDecode = json_decode($postdata);
if($_POST){
$array = [];
foreach ($_POST as $key => $value) {
$array[$key] = $value;
}
echo json_encode($array);
} elseif ($postDataDecode) {
echo json_encode($postDataDecode);
}
?>
vs code
edge
Related
You are using the nginx web server
React is trying to use the php mail function.
However, I don't know how to set it up on the web server.
I am using AWS es2 and I am using ubuntu 20.04 version.
Here's how we've done it so far.
I installed the first php8.1, php pfm8.1.
I installed postfix twice.
But I don't know which of these two ways is right.
Is it right to install and use php on the server?
I don't know if it's right to use postfix.
I want to implement the function of sending mail to my mailbox after writing it.
React Code
function Contact() {
const [textarea, setTextarea] = useState<textAreaType>({
message: ''
});
const [inputs, setInputs] = useState<inputTypes>({
company: '',
number: '',
email: '',
name: '',
phone: '',
})
const { company, number, email, name, phone } = inputs
const { message } = textarea
const onChangeInput = (e: React.ChangeEvent<HTMLInputElement>) => {
const { value, name } = e.target;
setInputs({
...inputs, // 기존의 input 객체를 복사한 뒤
[name]: value // name 키를 가진 값을 value 로 설정
});
};
const onChangeTextarea = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
const { value, name } = e.target
setTextarea({
...textarea,
[name]: value
});
};
function handleFormSubmit(event: React.FormEvent) {
// 언제나 HTMLInputElement 가 반환된다는 것을 알려줌. (타입 단언)
const email_Input = (document.getElementById('email') as HTMLInputElement).value
const name_Input = (document.getElementById('name') as HTMLInputElement).value
const phone_Input = (document.getElementById('phone') as HTMLInputElement).value
if (email_Input.length === 0) {
alert('이메일을 입력해주세요.')
} else if (name_Input.length === 0) {
alert('담당자 이름을 입력해주세요.')
} else if (phone_Input.length === 0) {
alert('담당자 전화번호를 입력해주세요.')
} else {
axios({
method: 'post',
url: `${API_PATH}`,
headers: { 'content-type': 'application/json' },
data: { ...inputs, ...textarea }
}).then(res => {
if (res.status === 200) {
alert('메일을 전송하였습니다. 홈으로 이동합니다.')
window.location.pathname = '/'
} else {
alert("메일전송에 실패하였습니다.")
}
}).catch(error => console.error(error));
event.preventDefault()
}
};
const API_PATH: string = 'http://XXXX.com/index.php'
PHP
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: X-PINGOTHER, Content-Type, Authorization");
header("Access-Control-Max-Age: 86400");
$rest_json = file_get_contents("php://input");
$_POST = json_decode($rest_json, true);
// company - 회사명
// number - 회사번호
// email - 이메일
// name - 담당자 명
// phone - 담당자 전화번호
// message - 메세지
$to = "XXXX#XXXX.com";
$subject = "Grigom_Pictures CONTACT MAIL - ".$_POST['company'];
$contents= nl2br(
"회사명 : ".$_POST['company']."\n".
"회사번호 : ".$_POST['number']."\n".
"이메일 : ".$_POST['email']."\n".
"담당자 명 : ".$_POST['name']."\n".
"담당자 전화번호 : ".$_POST['phone']."\n".
"내용 : ".$_POST['message']."\n"
);
$headers = implode("\r\n", [
//"From:" . $_POST['email'] . "",
"From: grigompictures.com",
'MIME-Version: 1.0',
'Content-Type: text/html; charset=UTF-8',
'X-Mailer: PHP/' . PHP_VERSION
]);
mail($to, $subject, $contents, $headers);
?>
[SOLVED] Had to split the download() method in 2, so it goes as generateCSV() and then getDownload().
After the the generation of the file, added this on sweetalert confirm button, which route points to getDownload().
preConfirm: () => {
window.location.href = "/customers/resale/filterToCSV/download";
}
After the user selects a few checkboxes for filtering a database table, the server writes to a CSV file, but it doesn't prompt the browser to download it.
route:
Route::get('/customers/resale/filterToCSV', 'Resale_customerController#getFilteredQueryResults');
blade view:
axios.get('/customers/resale/filterToCSV', {
params: {
dataFromClient: arrJson,
}
})
.then(function (response) {
Swal.fire({
icon: 'success',
title: '...',
text: '...',
})
console.log("Response (Filtered data to CSV): " + response.data);
});
controller:
public function getFilteredQueryResults(Request $request)
{
$arr = json_decode($request->dataFromClient, true);
$selection = $this->queryBuilderFromCheckboxSelection($arr);
$jsn = $selection->toJson();
$this->download($jsn);
}
which calls the download() method:
public function download($jsn)
{
$filePath = public_path().'\\file.csv';
$headers = array(
"Content-type" => "text/csv",
"Content-Disposition" => "attachment; filename=file.csv",
"Pragma" => "no-cache",
"Cache-Control" => "must-revalidate, post-check=0, pre-check=0",
"Expires" => "0"
);
$jsonDecoded = json_decode($jsn, true);
$csvFileName = 'file.csv';
$fp = fopen($csvFileName, 'w');
foreach ($jsonDecoded as $row) {
fputcsv($fp, $row);
}
fclose($fp);
echo response()->download($filePath, $csvFileName, $headers);
return response()->download($filePath, $csvFileName, $headers);//->deleteFileAfterSend(true);
}
Any idea what am I missing? Thank you!
I'm attempting to stream php data to an ajax handler and display it on the page using the code below, but on some devices the results being echoed by the page are't being displayed. I've used wireshark to confirm that the data is being received by the host (can see it in the tcp packets) but it doesn't seem to make it to ajax? What could possibly be going wrong?
Client side:
$.ajax(
{
xhrFields: {
onprogress: function(e)
{
var this_response, response = e.currentTarget.response;
if(last_response_len === false)
{
this_response = response;
last_response_len = response.length;
}
else
{
this_response = response.substring(last_response_len);
last_response_len = response.length;
}
/* Put output on page */
$('#tool-output-area').append(this_response + '<br>');
}
},
method: 'POST',
url: '../../../../../../../../page.php',
data:
{
data-key: data-variable...
}
})
.done(function(data)
{
// stuff
})
.fail(function()
{
// stuff
});
});
Server Side:
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
/* Set Maximum Execution Time By Plan */
ini_set('max_execution_time', getMaxExeTime());
ini_set('output_buffering', 'off');
ini_set('zlib.output_compression', false);
ini_set('implicit_flush', true);
ob_implicit_flush(true);
while (ob_get_level() > 0)
{
$level = ob_get_level();
ob_end_clean();
if (ob_get_level() == $level) break;
}
if (function_exists('apache_setenv'))
{
apache_setenv('no-gzip', '1');
apache_setenv('dont-vary', '1');
}
// Checks
$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "proc.txt", "a")
);
$pipes = array();
$process = proc_open('exec ' . escapeshellcmd($tool_command), $descriptorspec, $pipes, '/path-here', null);
$proc_details = proc_get_status($process);
$pid = $proc_details['pid'];
$proc_row = logProcess($pid, $tool_command, $output_file, $tool);
$str = '';
session_write_close();
if(is_resource($process))
{
while ($curStr = fgets($pipes[1]))
{
echo nl2br(htmlentities($curStr)); // Send the data back
flush();
$str .= nl2br(htmlentities($curStr));
$arr = proc_get_status($process);
sleep(1);
}
}
fclose($pipes[0]);
fclose($pipes[1]);
fclose($pipes[2]);
proc_close($process);
I was wondering how I would get php script to retrieve my base64 encoded image then write to server? I tried doing a post dump from my php script and I keep getting a response that it is empty. I've tried following a few other stackoverflow guides on this but none of them use a factory afaik.
js
var app = angular.module("app", ["ui.bootstrap"]);
//http://stackoverflow.com/questions/18571001/file-upload-using-angularjs
app.factory('API', function ($http) {
return {
uploadImage: function (image) {
return $http.post('/js/upload.php', image);
}
}
});
app.controller('MainController',['$scope', '$http', 'API', function($scope, $http, API) {
$scope.imageUrl = "";
$scope.template = "";
$scope.templates = [
'select an option...',
'MakeGray',
'Canny'
];
$scope.template = $scope.templates[0];
$scope.add = function() {
var f = document.getElementById('fileToUpload').files[0]; // name of image
var files = document.getElementById('fileToUpload').files;
var r = new FileReader();
r.onload = function(event){
console.log(event.target.result);
}
r.onloadend = function(e) {
var data = e.target.result;
var formData = new FormData();
$("#img1").prop("src", data);
$("#img2").prop("src", data);
formData.append("fileToUpload", f,f.name);
API.uploadImage(formData)
.success(function (imgUrl) {
$scope.imageUrl = imgUrl;
})
.error (function (error) {
});
}
r.readAsDataURL(f);
}
}]);
php
<?php
if(isset($_FILES['fileToUpload'])){
$errors= array();
$file_name = $_FILES['fileToUpload']['name'];
$file_size =$_FILES['fileToUpload']['size'];
$file_tmp =$_FILES['fileToUpload']['tmp_name'];
$file_type=$_FILES['fileToUpload']['type'];
$file_ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
$extensions = array("jpeg","jpg","png");
if(in_array($file_ext,$extensions )=== false){
$errors[]="image extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size cannot exceed 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"../uploads/".$file_name);
echo " uploaded file: " . "images/" . $file_name;
}else{
print_r($errors);
}
}
else{
$errors= array();
$errors[]="No image found";
print_r($errors);
}
?>
Angular have a particularity in concern the uploading.
First, you have to kno, angular's default transformRequest function will try to serialize our FormData object, so we override it with the identity function to leave the data intact.
Next, the default content-type header for POST requests is "application/json", so you must to change this because you want to upload a file.
By setting 'Content-Type': undefined, the browser sets the Content-Type to multipart/form-data himself and fills in the correct boundary.
Manually setting 'Content-Type': multipart/form-data will fail to fill in the boundary parameter of the request.
Look about others possible issues : https://docs.angularjs.org/api/ng/service/$http
Now you can get you image from $_POST global array of PHP.
Fixed code
uploadImage: function (formData)
{
return $http.post('js/upload.php', formData,
{
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
}
Note:
That the below service uses the FormData object which is not supported by IE9 and earlier.
Hi I'm wanting to post a variable from ajax js file to a php file. here is my attempt so far.
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
here is my php file
<?php
print_r($_POST);
$node = $_POST['deletenode'];
print "node to be deleted: $node";
?>
nothing comes up in my php file, what can be the issue. my ajax request is intact and working right too. thank you and here is my handle request.
function handleRequest(request) {
// we only care for now about when we get to readyState 4
// which means the request completed and we have the response back
if(request.readyState == 4){
//alert("response: " + request.responseText); // check to see what
// we got back just for testing
// now get response's TEXT and put into document (specify where)
// below we have an html element with the id as timeLoc
json= eval ("(" + request.responseText + ")");;
//alert ("json="+json); //tests what was recieved
//clicking the close button
closeButton.onclick = function() {
node.setData('alpha', 0, 'end');
node.eachAdjacency(function(adj) {
adj.setData('alpha', 0, 'end');
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
});
}// end readystate=4
}//end handle request
Remember you have to send the data as key/value pairs - request.send("deletenode=" + encodeURIComponent(deletenode));
I'm not sure if this is a copy/paste error, but if that's your actual code you appear to be missing a few curly braces closes. And have a double;; at the end of your eval line. This is the code tidied up with the extra curly braces, does that work?
function handleRequest(request) {
if(request.readyState == 4){
json= eval ("(" + request.responseText + ")");
closeButton.onclick = function() {
node.setData('alpha', 0, 'end');
node.eachAdjacency(function(adj) {
adj.setData('alpha', 0, 'end');
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
});
}
}
}