How to properly upload file from vue to laravel? - javascript

When I send a photo I get a 422 error from axios with message:
The preview must be a file of type: jpg, jpeg, png, pdf.
But I sent the photo in the correct format. I don't really understand where the error is.
My vue component methods:
data() {
return {
name: '',
description: '',
preview: '',
}
},
methods: {
create() {
this.projectStore.createProject(this.name, this.description, this.preview)
},
onFileChange(e) {
let img = e.target.files[0]
let reader = new FileReader()
reader.readAsDataURL(img)
this.preview = img
},
},
My store(Pinia) method:
async createProject(name, description, preview) {
let formData = new FormData()
formData.append('preview', preview)
console.log(formData);
axios.get('/sacntum/csrf-cookie').then(response => {
axios.post('api/create', {
name: name,
description: description,
preview: formData,
}, {
headers: {
'content-type': 'multipart/form-data',
}
})
.then(response => {
if (response.data.success) {
console.log(response)
} else {
console.log('response')
}
})
.catch(function (error) {
console.error(error)
})
})
},
My Controller in Laravel:
public function createProject(Request $request)
{
if (Auth::check()) {
$attr = $request->validate([
'name' => 'required|string|max:255',
'description' => 'required|string|max:1000',
'preview' => 'required|mimes:jpg,jpeg,png,pdf|max:2048',
]);
$generated_new_name = time() . '.' . $attr['preview']->getClientOriginalExtension();
$request->preview->move(public_path('preview_images'), $generated_new_name);
$project = Project::create([
'name' => $attr['name'],
'description' => $attr['description'],
'preview' => $generated_new_name,
]);
$success = true;
$message = 'Project created successfully';
} else {
$success = false;
$message = 'You are not logged yet';
}
$response = [
'success' => $success,
'message' => $message,
];
return response()->json($response);
}
I tried to make formdata in vue component and then pass to store but it didn't help

Use the below code in the controller
$photo = $request->file('image');
$imagename = time() . '.' . $photo->getClientOriginalExtension();
// Add Normal Image...
$destinationPath = public_path('uploads');
$photo->move($destinationPath, $imagename);
echo '<pre>';
print_r("Upload Successfully. Store File : laravel_code/public/uploads & laravel_code/public/uploads/thumbnail_images");

Related

Send image to backend as a Blob from Javascript to PHP using Fetch

id is a input where you can upload 1 image.
Basically I'd like for the image to be sent to back-end and be inserted into the DB.
Everything is working except getting the image to backend as a blob and uploading it.
Javascript Code:
const data = {
first_name: first_name.value,
last_name: last_name.value,
email: email.value,
company: company.value,
occupation: occupation.value,
students: students.value,
id: id.value
}
fetch('../scripts/partners_application', {
method: 'POST', headers: {'Content-Type': 'application/json',},
body: JSON.stringify(data)
}).then((response) => response.json()).then((data) => {
if (data["success"]){
error_message.style = "color:green;"
error_message.innerHTML = "<i class='fa-solid fa-check'></i> Successfully sent, we will be in touch with you soon."
}
}).catch((error) => {
console.error('Error:', error);
error_message.style = "color:red"
error_message.textContent = "Error occured, please try again later or contact us."
});
PHP Side:
$first_name = $data["first_name"];
$last_name = $data["last_name"];
$email = $data["email"];
$company = $data["company"];
$occupation = $data["occupation"];
$id = $data["id"];
$students = $data["students"];
$sql = "INSERT INTO partner_applications (first_name,last_name,email,company,occupation,id,students,date_created) VALUES(?,?,?,?,?,?,?,?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("sssssbss", $first_name, $last_name, $email,$company,$occupation,$id,$students,date("Y/m/d/H:i:s"));
$stmt->execute();
$response = array("success"=>true,"id"=>$id);
echo json_encode($response);

AJAX Javscript - PHP

I learn MVC and make some AJAX interaction. So I've routes file with
'cart/addProductAjax' => 'cart/addProductAjax',
CartController with actionAddProductAjax:
<?php
class CartController
{
public function actionIndex() {
}
public function actionAdd($productId) {
Cart::addProduct($productId);
$referer = '/';
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = $_SERVER['HTTP_REFERER'];
}
header("Location: $referer");
}
public function actionAddProductAjax() {
$productId = $_POST['productId'];
print_r($_POST);
exit;
Cart::addProduct($productId);
$itemsAmount = Cart::countItems();
exit(json_encode($itemsAmount));
}
}
And JS piece of code that send request and receive response from the server:
document.body.addEventListener('click', event => {
if(event.target.classList.contains('add-to-cart')) {
event.preventDefault();
let productId = event.target.dataset.id;
let response = fetch("/cart/addProductAjax/", {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(productId),
})
.then(response => response.json())
.then(response => console.log(response));
}
});
And nothing works. I think there is an error somewhere in PHP method. What shoul I do to make it work?

How do I fetch data from my back-end (localhost) that's being sent through Fetch API? (PHP, Fetch, React Native, POST request)

fetch("http://10.0.2.2:80/NewAdmin/scripts/main/transactions", {
method:'post',
headers:{
"Accept":"application/json",
"Content-type":"application/json"
},
// (var) payload looks like this {Header: "Sending", . . .}
body:JSON.stringify(payload)
})
.then(res => res.json())
.then(resp => console.log(resp))
.catch(err => console.log(err));
My PHP code
<?php
$json = json_decode(file_get_contents('php://input'), true);
echo $json;
if($json["Header"] == "Sending"){
echo json_encode('!WTF');
}else{
echo json_encode('WTF!');
}
?>
It returns 'WTF!'—no pun intended. What am I missing?
Try this example, it should return 'action test' OR Error,
JS Code:
fetch(ConfigApp.URL + 'transactions.php', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
action: 'action test',
p: 'addSession',
}),
})
.then(response => response.json())
.then(responseJson => {
console.warn(responseJson)
})
.catch(function(error) {
console.warn(Strings.no_result + error.message);
});
PHP transactionsv.php:
<?php
//Make sure that it is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
throw new Exception('Request method must be POST!');
}
//Make sure that the content type of the POST request has been set to application/json
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
if(strcasecmp($contentType, 'application/json') != 0){
throw new Exception('Content type must be: application/json');
}
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
//Attempt to decode the i ncoming RAW post data from JSON.
$decoded = json_decode($content, true);
if(!is_array($decoded)){
$json_string = json_encode(false);
print ($json_string);
die();
}elseif(!isset($decoded["p"])){
$decoded = $decoded[0];
}
switch ($decoded["p"]) {
case 'addSession':
print (json_encode($decoded['action']));
break;
default:
$json_string = json_encode(false);
print ($json_string);
break;
}

javascript retreive fetch response from a php

I'm try to implement the paypal express checkout.
So I implement the button and write the result in my database. Nothing exceptional, it's the script they gave.
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Call your server to save the transaction
return fetch('recordDatabase.php', {
method: 'post',
mode: "same-origin",
credentials: "same-origin",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({
orderID: data.orderID,
time: details.create_time,
status: details.status,
nom: details.payer.name.given_name,
prenom: details.payer.name.surname,
pays: details.payer.address.country_code,
valeur:details.purchase_units[0].amount.value
})
})
});
}
}).render('#paypal-button-container');
</script>
The php to record in the database:
<?php
$link = connect();
$date = date('Y-m-d H:i:s');
//Receive the RAW post data.
$contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(! is_array($decoded)) {
//echo "error";
} else {
$name = $decoded['nom'];
$time = $decoded['time'];
$id = $decoded['orderID'];
$stat = $decoded['status'];
$pays = $decoded['pays'];
$val = $decoded['valeur'];
$secQuery = "INSERT INTO myDatabase(PSEUDO,PASSWORD,CONNECTION,INSCRIPTION,ANNIVERSAIRE,MAIL,IDPAYPAL,STATPAYPAL,NOMPAYER,PAYS,VALEUR) VALUES ('essai','123456',0,'$date','$time','email#mail','$id','$stat','$name','$pays','$val') ";
if (mysqli_query($link,$secQuery)) {
//echo "ok";
} else {
//echo "error";
}
}
} else {
//echo "error";
}
So, the record in my database works fine, but my question is:
How can I retrieve the echo error or ok in the javascript to confirm the user that everything is fine, or if an error happen.
I tried another solution, to redirect the user from the php and add to the php:
header("Location: confirmation web page"); or
echo "<script>window.location = 'confirmation web page'</script>";
but both solution doesn't work. No redirection happen
Correct if i'm wrong, recordDatabase.php is your php file that is storing the transactions.
So, the return fetch('recordDatabase.php', { is returning the response from this file, your echo 'ok';,echo 'error';, the fetch is asyncronous, so it'will return a promise.
Add header('Content-Type: application/json'); to your php file so it returns a json response.
Also change your echo to echo '{"status":"ok"}'; and echo '{"status":"error"}';
Now modify your fetch function,
return fetch('recordDatabase.php', {
//same info here
})
.then((response) => response.json())
.then((responseData) => {
if(responseData.status == "ok"){
alert("it worked");
}else{
alert("it didn't work");
}
})
return fetch('codes/paypalapi.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID
})
});
it will work perfectly
i had the same situation
I have just solved your case , just try this code and see how it works
Paypal Script API
<script>
paypal.Buttons({
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01'
}
}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
alert('Transaction completed by ' + details.payer.name.given_name+' ApplicationId <?php echo $id; ?> :payerID'+data.payerID);
// Call your server to save the transaction
return fetch('payments.php', {
method: 'post',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
orderID: data.orderID,
time: details.create_time,
status: details.status,
nom: details.payer.name.given_name,
prenom: details.payer.name.surname,
pays: details.payer.address.country_code,
valeur:details.purchase_units[0].amount.value
})
}).then(data => data.ok && data.json()).then(response => {
alert(response.status);
});
});
}
}).render('#paypal-button-container');
</script>
PHP script (payments.php)
<?php
header('Content-Type: application/json');
$date = date('Y-m-d H:i:s');
//Receive the RAW post data.
$contentType = isset($_SERVER["CONTENT_TYPE"]) ?trim($_SERVER["CONTENT_TYPE"]) : '';
if ($contentType === "application/json") {
//Receive the RAW post data.
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
//If json_decode failed, the JSON is invalid.
if(! is_array($decoded)) {
//echo "error";
} else {
$name = $decoded['nom'];
$time = $decoded['time'];
$id = $decoded['orderID'];
$stat = $decoded['status'];
$pays = $decoded['pays'];
$val = $decoded['valeur'];
echo '{"status":"ok"}';
}
} else {
echo '{"status":"error"}';
}
?>

Symfony form AJAX return empty object

I'm trying to create AJAX form with Symfony, but my form return empty object. When I send manualy writed text or array everything works fine. Where is the bug? I do something wrong with form or javascript code is the problem?
/**
* Renders the "new" form
*
* #Route("/", name="demo_new")
* #Method("GET")
*/
public function newAction(Request $request) {
$entity = new Demo();
$form = $this->createForm(DemoType::class, $entity);
return $this->render('default/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
)
);
}
/**
*
* #Route("/", name="demo_create")
* #Method("POST")
*
*/
public function createAction(Request $request) {
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array('message' => 'You can access this only using Ajax!'), 400);
}
$entity = new Demo();
$form = $this->createForm(DemoType::class, $entity, array(
'action' => $this->generateUrl('demo_create'),
'method' => 'POST',
));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
return new JsonResponse(
[
'message' => 'Success!',
'data' => $data
], 200);
}
$response = new JsonResponse(
array(
'message' => 'Error',
'form' => $this->renderView('default/new.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
))), 400);
return $response;
}
}
and Javascript code:
function initAjaxForm()
{
$('body').on('submit', '.ajaxForm', function (e) {
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize()
})
.done(function (data) {
if (typeof data.message !== 'undefined') {
console.log(data.data);
console.log(data.message);
}
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (typeof jqXHR.responseJSON !== 'undefined') {
if (jqXHR.responseJSON.hasOwnProperty('form')) {
$('#form_body').html(jqXHR.responseJSON.form);
}
$('.form_error').html(jqXHR.responseJSON.message);
} else {
alert(errorThrown);
}
});
});
}
Had same issue today with version 2.8 gonna leave this here in case it end up healping someone else i've added this to my form builder
/**
* {#inheritdoc}
*/
public function getBlockPrefix()
{
return '';
}

Categories

Resources