Failed to FETCH (JS) - javascript

Problem:
I am request data from my client (the js file) with $_GET in my PHP and sending the a response back. The problem is that the response is an error.
HTML
<div>
<input type="text" id="text">
<div id="send" onclick="sendData()">send</div>
</div>
<h1 id="data"></h1>
JS
function sendData() {
var text = document.getElementById('text').value
console.log(text);
fetch(`./home.php?data=${text}`)
.then(data => {
console.log(data.text());
document.getElementById('data').innerHTML=data
})
.catch(err => {
console.log(err);
document.getElementById('data').innerHTML=err
})
}
PHP:
if(isset($_GET["data"])){
$output = $_GET["data"];
echo $output;
}

Here's how you can fix the code:
JS:
function sendData() {
var text = document.getElementById('text').value
console.log(text);
fetch(`./home.php?data=${text}`)
.then(response => response.text())
.then(data => {
console.log(data);
document.getElementById('data').innerHTML = data;
})
.catch(err => {
console.log(err);
document.getElementById('data').innerHTML = err;
});
}
PHP:
if (isset($_GET['data'])) {
$output = $_GET['data'];
echo $output;
}

Related

Processing formData from alpine js form

I have the following html
<div class="row" x-data="pageState()" x-init="mounted()">
<form method="post" enctype="multipart/form-data" #submit.prevent="postFormData()">
<div class="col-sm-4 p-2"><label>First Name</label><input x-model="form.firstname" name="firstname" type="text" required /></div>
<div class="col-sm-4 p-2"><label>Second Name</label><input x-model="form.secondname" name="secondname" type="text" required /></div>
<div class="col-sm-4 p-2"><label>Images</label><input name="images" type="file" x-on:change="selectFile($event)" accept="image/png, image/jpg, image/jpeg" multiple required /></div>
<button class="btn btn-primary mt-5">Submit Form Data</button>
</form>
</div>
and alpine js code
<script>
function pageState(){
return {
form: {
firstname: '',
secondname: '',
},
selectFile(event) {
this.form.images = event.target.files[0];
},
postFormData(){
//Create an instance of FormData
const data = new FormData()
let url = 'http://localhost:8000/alpine_form'
// Append the form object data by mapping through them
Object.keys(this.form).map((key, index) => {
data.append(key, this.form[key])
});
fetch(url, {
method: 'POST',
/**
headers: {
'Accept': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
*/
body: data
})
.then(response => {
console.log(response);
})
.finally(() => {
});
/**
axios.post('https://eot1ip4i6xwine.m.pipedream.net', {
firstname: this.firstname,
secondname: this.secondname
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
*/
},
mounted(){
this.$watch('form.firstname', (value, oldValue) => this.form.firstname = value);
this.$watch('form.firstname', (value, oldValue) => console.log(value, oldValue));
console.log('mounted');
}
}
}
</script>
In the backend i have this laravel code
public function alpine_form(Request $request){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$data = $request->all();
$firstname = $data['firstname'];
$secondname = $data['secondname'];
$images = $data['images'];
$ai = '';
$uploaded_images_array = [];
//images
if($request->hasfile('images'))
{
foreach($request->file('images') as $fil)
{
$nam = mt_rand().uniqid().'.'.$fil->extension();
$fil->move(public_path().'/uploads/', $nam);
$uploaded_images_array[] = $nam;
}
$ai = json_encode($uploaded_images_array);
DB::table('form')->insert(
array(
'firstname' => $firstname,
'secondname' => $secondname,
'images' => $ai
)
);
}
}
I am able to receive firstname and secondname but he images array is always empty when i insert the data into the database. Am i acquiring the images posted correctly?
I appended my images like this
postFormData(){
//Create an instance of FormData
const data = new FormData()
data.append('firstname', this.form.firstname);
data.append('secondname', this.form.secondname);
let input_file = document.querySelector('input[type="file"]')
Array.from(input_file.files).forEach((f) => {
data.append('images[]', f)
})
let url = 'http://localhost:8000/alpine_form'
fetch(url, {
method: 'POST',
/**
headers: {
'Accept': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
*/
body: data
})
.then(response => {
console.log(response);
})
.finally(() => {
});
},
and no other modification was necessary.

Is it posible to POST request the responseType "array buffer"?

I made an api that will return an image. at first I tried it on get method request and it works, but for security reasons I need to make it to post method but post is not working like my get method. Do you think that responseType is available only in get method since it is not working on my post method?
Here is my code using get method that works:
frontend:
export const getImageFile = async (imageName) => {
try {
const { data } = await axios.get(`${apiUrl}/image/${imageName}`,{
responseType: "arraybuffer",
});
const image = new Buffer.from(data, "binary").toString("base64");
return `data:image/png;base64, ${image}`;
} catch (err) {
alert("File not found.");
}
};
backend (php symfony):
/**
* #Route("/api/graph/image/{imageName}", methods={"GET"}, name="get- image-graph")
*/
public function getImage($imageName)
{
try {
$file = $this->parameterBag->get('kernel.project_dir').'/public/graphImage/graphs/'.$imageName;
$response = new BinaryFileResponse($file);
return $response;
} catch (\Exception $e) {
return $this->json(['error' => 'File not found'], JsonResponse::HTTP_NOT_FOUND);
}
}
here is my code when I use POST method that doesnt works:
frontend:
export const getImageFile = async (imageName) => {
try {
const { data } = await axios.post(`${apiUrl}/image`,{
responseType: "arraybuffer",
"imageName": imageName,
});
const image = new Buffer.from(data, "binary").toString("base64");
return `data:image/png;base64, ${image}`;
} catch (err) {
alert("File not found.");
}
};`
backend:
```php
/**
* #Route("/api/graph/image", methods={"POST"}, name="get-image-
graph")
*/
public function getImage(Request $request)
{
try {
$content = json_decode($request->getContent(), true);
$imageName = $content["imageName"];
$file = $this->parameterBag->get('kernel.project_dir')
.'/public/graphImage/graphs/'.$imageName;
$response = new BinaryFileResponse($file);
return $response;
} catch (\Exception $e) {
return $this->json(['error' => 'File not found'],
JsonResponse::HTTP_NOT_FOUND);
}
}`
From the Documentation,
axios.post(url, data, config)
Your post request:
const { data } = await axios.post(`${apiUrl}/image`,{
responseType: "arraybuffer",
"imageName": imageName,
});
It seems you mixed data and config. So your post request should be
const {data} = await axios.post(
`${apiUrl}/image`,
{
"imageName": imageName,
},
{
responseType: "arraybuffer"
}
);
// In server side php,you access it like
$image = $_POST["imageName"];
And if you would like to send it as json, use headers in config
{
responseType: "arraybuffer",
headers: {'Content-Type': 'application/json'}
}

JavaScript https get request

a get request to the address https://api.steampowered.com/ISteamApps/GetAppList/v2/?format=json is sent too long with this code:
https.get("https://api.steampowered.com/ISteamApps/GetAppList/v2/?format=json", (res) =>
{
res.setEncoding("utf8");
let bodyCount = "";
res.on("data", (dataCount) => {
bodyCount += dataCount;
});
res.on("end", () => {
bodyCount = JSON.parse(bodyCount);
console.log(bodyCount);
});
});
The process takes up to several seconds, so how to make it happen faster?
In case anyone is wondering how I solved the problem:
setInterval(() =>{
https.get("https://api.steampowered.com/ISteamApps/GetAppList/v2/?format=json", (res) => {
res.setEncoding("utf8");
let body ="";
res.on("data", (dataCount) => {
body += dataCount;
});
res.on("end", () =>{
fs.writeFile('./steamdatabase.txt', body, (err) => {
if (err) {
console.error(err)
return
}
});
});
});
}, 86400000);
...
fs.readFile('./steamdatabase.txt', (err, data) => {
if (err) {
console.error(err)
return
}
let body = JSON.parse(data);
for(let i = 0;i<body.applist.apps.length;i++){
if(body.applist.apps[i].name == generateParameter(args)) appidGame = body.applist.apps[i].appid;
}
if(appidGame) appInfo(appidGame,mess);
});

stripe not redirecting to checkout page

i am getting redirect to pay.php and got session.id in pay.php but i am not redirecting to checkout page :(
var checkoutButton = document.getElementById("paymentform").submit();
i am trying to redirect to checkout page should i create product in stripe ?
<!DOCTYPE html>
<html>
<head>
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
</head>
<?php if(isset($_POST['productname']) && $_POST['productname']!="" && isset($_POST['amount']) && $_POST['amount']!="")
{ ?>
<form name="paymentform" class="paymentform" style="display:none" id="paymentform" method="post" action="pay.php">
<input name="productname" type="hidden" value="<?=$_POST['productname'];?>">
<input name="amount" type="hidden" value="<?=$_POST['amount'];?>">
</form>
<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe("pk_test_576576576576576");
var checkoutButton = document.getElementById("paymentform").submit();
checkoutButton.addEventListener("click", function () {
fetch("/pay.php", {
method: "POST",
})
.then(function (response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function (result) {
// If redirectToCheckout fails due to a browser or network
// error, you should display the localized error message to your
// customer using error.message.
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
});
</script>
<?php } else{
header("location:http://www.example.com");
}?>
pay.php
<?php if(isset($_POST['productname']) && $_POST['productname']!="" && isset($_POST['amount']) && $_POST['amount']!="")
{
require 'vendor/autoload.php';
\Stripe\Stripe::setApiKey('sk_test_86876876876');
header('Content-Type: application/json');
$YOUR_DOMAIN = 'https://localhost';
$checkout_session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'price_data' => [
'currency' => 'usd',
'unit_amount' => $_POST['amount'],
'product_data' => [
'name' => $_POST['productname'],
'images' => ["https://i.imgur.com/EHyR2nP.png"],
],
],
'quantity' => 1,
]],
'mode' => 'payment',
'success_url' => $YOUR_DOMAIN . '/stripe/success.php',
'cancel_url' => $YOUR_DOMAIN . '/stripe/cancel.php',
]);
echo json_encode(['id' => $checkout_session->id]);
}else{
header("location:http://www.example.com");
}
?>
In your JavaScript code, you have added a .submit() before the Event Listener. This causes to redirect the page without submitting the information. Please check the below code.
<html>
<head>
<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
<script src="https://js.stripe.com/v3/"></script>
</head>
<?php if(isset($_POST['productname']) && $_POST['productname']!="" && isset($_POST['amount']) && $_POST['amount']!="")
{ ?>
<form name="paymentform" class="paymentform" style="display:none" id="paymentform" method="post" action="pay.php">
<input name="productname" type="hidden" value="<?=$_POST['productname'];?>">
<input name="amount" type="hidden" value="<?=$_POST['amount'];?>">
</form>
<script type="text/javascript">
// Create an instance of the Stripe object with your publishable API key
var stripe = Stripe("pk_test_576576576576576");
var paymentform = document.getElementById("paymentform");
let formData = new FormData();
formData.append('productname', paymentform.elements["productname"]);
formData.append('amount', paymentform.elements["amount"]);
fetch("/pay.php", {
method: "POST",
body: formData
})
.then(function (response) {
return response.json();
})
.then(function (session) {
return stripe.redirectToCheckout({ sessionId: session.id });
})
.then(function (result) {
// If redirectToCheckout fails due to a browser or network
// error, you should display the localized error message to your
// customer using error.message.
if (result.error) {
alert(result.error.message);
}
})
.catch(function (error) {
console.error("Error:", error);
});
</script>
<?php } else{
header("location:http://www.example.com");
}?>

running a nodeJS function within a csv file

I have a nodeJS app in which I designed it to run three API calls based on the name of the business and return results. What i want to do is run this app in a CSV file that I have. Below is my code. Any ideas on how to do this? Below is a sample of my code. Im trying to run the name column, pass it inside my functions and return the results inside the CSV file.
function fetchYelp() {
let token = '<Token>';
axios.get('https://api.yelp.com/v3/businesses/search?term=Grace Christian Fellowship&location=Mounds, il 62964',{
headers: {
Authorization: 'Bearer ' + token
}
})
.then(res => {
if(res.data.businesses.length < 1){
fetchWhitePages();
}else{
console.log(res.data.businesses);
console.log('running YelpAPI')
}
})
.catch(err => {
console.log(err)
})
}
fetchYelp();
function fetchWhitePages() {
axios.get('https://proapi.whitepages.com/3.0/business?api_key=<key>&address.city=Mounds&address.country_code=US&address.postal_code=62964&address.state_code=il&name=Grace Christian Fellowship')
.then(res => {
if(!res.data.business.length < 1){
fetchGooglePlace()
}else{
console.log(res.data);
console.log('running whitePagesAPi')
}
})
.catch(err => {
console.log(err)
});
}
function fetchGooglePlace(){
axios.get('https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Grace Christian Fellowship, mounds il 62964&inputtype=textquery&fields=photos,formatted_address,name,rating,opening_hours,geometry,place_id&key=<APIKEY>')
.then(res => {
if(res.data.candidates.length < 1){
console.log('Manual Search')
}else{
console.log(res.data.candidates[0].place_id);
console.log('Passing Place ID to fetchGoogleTel')
fetchGoogleTel()
}
})
.catch(err => {
console.log(err)
});
}
function fetchGoogleTel ()

Categories