How should PHP receiving end look like when using JS Fetch - javascript

just a quick question.
eventReceive: function(info) {
//get the bits of data we want to send into a simple object
var eventData = {
title: info.event.title,
start: info.event.start,
};
//send the data via an AJAX POST request, and log any response which comes from the server
fetch('<?php \E::get('obj_curr_module')->build_action_path('dev_guideline_ui_calendar','add_event'); ?>', {
method: 'POST',
headers: {
'Accept': 'application/json'
},
body: encodeFormData(eventData)
})
.then(response => console.log(response))
.catch(error => console.log(error));
},
My eventData is set as JS format. After using the function encodeFormData, i was wondering how should my php receiving end file looks like in order to retrieve the eventData pass on in the body?
My encodeFormData function is as below,
const encodeFormData = (data) => {
var form_data = new FormData();
for (var key in data) {
form_data.append(key, data[key]);
}
return form_data;
};

Related

passing binary data to rest-api

I want to upload a thumbnail to viemo api , and based on Vimeo doc, I must include the thumbnail file as binary data in the request body, I have to upload the thumbnail from the client side "fontend" and will send the request from the rest-api "backend" the problem is my rest-api can't receive the binary data, properly because I'm using express.js, is there any way to handle the binary data in the backend.
the steps as following:
client side sent thumbnail data => backend receive the data through the request body and send it to => endpoint
client side request
const handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('selectedFile', new Blob([selectedFile], { type: 'application/json' }));
formData.append('uploadLink', uploadLink);
const headers = {
'Content-Type': 'application/json',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
};
try {
axios
.post(`${backendPostPath}/thumbnail-upload`, formData, {
headers,
})
.then((response) => {
applyThumbnial();
console.log(`${uploadLink}link for upload`);
});
} catch (error) {
console.log(error);
}
};
backend request can't receive the body request of frontend post as binary data,
const ThumbnailUpload = async (req, res) => {
const { uploadLink } = req.body;
const { selectedFile } = req.body;
console.log(uploadLink);
const clientServerOptions = {
uri: `${uploadLink}`,
encoding: null,
body: JSON.stringify({
name: uploadLink,
file: selectedFile,
}),
method: 'PUT',
headers: {
'Content-Type': 'application/json',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
Authorization: getVimeoAuthorization(),
},
};
request(clientServerOptions, function (error, response) {
if (error) {
res.send(error);
} else {
const body = JSON.parse(response.body);
res.send(body);
}
});
};
is there any way to make the backend request body fetch the binary data, as I getting the data as "undefined"
Sorry for late update, I solved this issue by using the same put request form the client side, as the put request don't require Vimeo access token, so you can use the same put request i mentioned above, and remove authentication from the header, like following
const handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append('selectedFile', new Blob([selectedFile], { type: 'image/jpg, image/png' }));
// formData.append('uploadLink', uploadLink);
const headers = {
'Content-Type': 'image/jpg, image/png',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
};
try {
axios
.put(`${uploadLink}`, formData, {
headers,
})
.then((response) => {
console.log(`${uploadLink}link for upload`);
});
} catch (error) {
console.log(error);
}
};

How can I POST an image to DB via react native with the fetch API?

So I am trying to POST an image to a server via React Native and the fetch API.
fetch(`${API}/uploadAvatar`, {
method: "POST",
headers: {
Authorization: bearer,
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
},
body: JSON.stringify({ file: result.uri }),
})
.then((response) => response.json())
.then((json) => {
console.log({ json });
// this console.log outputs:
// "The format of the file should be jpg, png, jpeg.",
})
.catch((err) => {
console.log({ err });
});
}
result returns this:
{
"cancelled": false,
"height": 1776,
"type": "image",
"uri": "file:///var/mobile/Containers/Data/Application/18F84F29-CB72-4615-A68F-A00422D9B119/Library/Caches/ExponentExperienceData/%2540heythere%252Fkeep-up/ImagePicker/959E8BDE-FCF4-40C6-AF18-8F9EA852760D.jpg",
"width": 1776,
}
Those are the calls on POSTMAN where you can see they work.
What am I doing wrong?
Your postman shows that you're using form-data to upload the image, but in your code you're simply making a JSON post call without sending any form-data. You need to create a new FormData instance, and append data to it. In your case, you want to send the result.uri with the key file, this can be done using formData.append('file', result.uri). Then you gotta send the formData instance as your body (with method as POST, in your case)
let formData = new FormData();
formData.append('file', result.uri);
fetch("api/SampleData", {
body: formData,
method: "post"
}).then((response) => response.json())
.then((json) => {
console.log({
json
});
})
.catch((err) => {
console.log({
err
});
});
You can post images to the server with the help of Form Data by creating a JSON object of the file path, file name, and file type and append the object into the Form Data instance with the parameter. The path of the file is Platform-specific therefore you have to add conditions for the path. Please refer to the code snippet.
let Data = new FormData();
Data.append('file',
{
uri: Platform.OS === 'android' ? result.uri: result.uri.replace('file://',''),
type: result.type,
name: result.uri.replace(/^.*[\\\/]/, '')
});
fetch("api/SampleData", {
body: Data,
method: "post",
headers: {'Content-Type': 'multipart/form-data'}
}).then((response) => response.json())
.then((json) => {
console.log({
json
});
})
.catch((err) => {
console.log({
err
});
});

Controller method won't got parameters

I made a post ajax request to server side.
the request reached to the server but the recieved parameters are empty/null.
no idea why this is happening, the problem is probably in the server. tried many solutions but nothing changed.
I hope some of you can help me.
fetch('Home/AddMovie', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
movie: data_object
}),
}).then(res => res.text())
.then(text => {
})
.catch((error) => {
console.error('Error:', error);
});
[HttpPost]
public void AddMovie(Movie movie)
{
var movies = new List<Movie>();
var newJson = "";
using (StreamReader r = new StreamReader(JsonFilePath))
{
string json = r.ReadToEnd();
movies = JsonConvert.DeserializeObject<List<Movie>>(json);
movies.Add(movie);
newJson = JsonConvert.SerializeObject(movies, Formatting.Indented);
}
System.IO.File.WriteAllText(JsonFilePath, newJson);
}
This will work out
public void AddMovie([FromBody] Movie movie) { }
Edit:
Remove JSON.stringify() Just assign the object itself

PHP returns NULL after sending FormData from React JS (Fetch, method: POST)

I want to read the content of var in PHP when I send data by fetch from React JS (method: POST) and I can see only null(instead of "szynka") returned by $peopleAmount. Console.log() returns data correctly, but in PHP console log i see this: Image.
App.js
var formData3 = new FormData();
var szynka = "szynka";
//var json_params = JSON.stringify(szynka);
formData3.append('peopleAmount', szynka);
fetch('http://localhost/api/index.php', {
method: 'POST',
headers : {
},
body: formData3
})
.then((res) => res.json())
.then(response => {
console.log(response);
})
index.php
if(isset($_POST))
{
$peopleAmount = $_POST['peopleAmount'];
echo json_encode($peopleAmount);
}

Problems passing parameters through the put method using fetch

I'm having problems trying to pass parameters by the put method using fetch
For this I am trying the following
fetch(`brands/${id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({name: 'dummy text'})
})
.then(response => response.json())
.then(json => {
if (json.status === 'ok') {
// do some relevant logic
return false;
}
showErrors(json.errors);
})
.catch(error => console.error(error.message));
I am also trying using the FormData interface
const formData = new FormData();
formData.append('name', 'some dummy text');
fetch(`brands/${id}`, {
method: 'PUT',
body: formData
})
.then(response => response.json())
.then(json => {
if (json.status === 'ok') {
// Some relevant logic
return false;
}
showErrors(json.errors);
})
.catch(error => console.error(error.message));
But I am getting the same result (name parameter is not in the controller)
Inspected the network tab I can see that ajax has been called and in the params tab I can see that the variables are passed. But when trying to access these parameters from the controller they do not appear.
I appreciate your help
In backend when printing the parameters received in this query, the name parameter is not listed.
In backend the relevant parts in the controller definition are the following
The update method can only be invoked through the put method
static allowedMethods = [
save: 'POST',
update: 'PUT'
]
Here I hope that the name parameter has a value, but the parameter does not exist
def update() {
try {
Brand brand = brandService.update(params.id, params.name)
render(contentType: 'application/json') {
[status: 'ok', brand: brand]
}
} catch(ValidationException e) {
render(contentType: 'application/json') {
[status: 'fail', errors: e.errors]
}
}
}
Running your form through this little helper might do the trick:
form2Obj(form) {
const obj = {};
new FormData(form).forEach((val, key) => obj[key] = val);
return obj;
}

Categories

Resources