I am sending a FormData object to an endpoint. A phone number needs to be formatted as this JSON:
"phone": [{"type":"main", "value":"#"}, ...] or it gets rejected. A single object with a two-pair of keys and values in an array.
const doStuff = () => {
const formData = new FormData()
**Have tried below for setting key/value of phone object**
// Attempt 1
formData.set('phone', [{ type: 'main', value: '313-555-2121' }])
// Returns:
"phone":"[Object Object]"
// Attempt 2
formData.set(
'phone',
JSON.stringify([{ type: 'main', value: '313-555-2121' }])
)
// Returns
"phone":"[{\"type\":\"main\",\"value\":\"313-555-2121\"}]"
// Format as single "fields" object and stringify (results in fields: {...stuff}), API needs this.
const formattedForApi = JSON.stringify({fields: Object.fromEntries(formData.entries())})
// MAKE POST REQUEST...
}
The API errors on both of my attempts above. Complaining of an invalid first value which needs to be "main". Am I missing something with how stringify is affecting the data that is actually being sent?
For those wondering, the API is Podio
Digging into the PHP SDK code, it seems you're supposed to send the fields as plain old JSON and definitely not double-encoded
const formattedForApi = JSON.stringify({
fields: {
phone: [
{
type: "main",
value: "313-555-2121",
},
],
},
});
fetch(`/item/app/${app_id}/`, {
method: "POST",
body: formattedForApi,
headers: {
authorization: `OAuth2 ${token}`,
"content-type": "application/json",
},
});
Sending arrays as JSON in FormData is possible, but it requires encoding the arrays into strings before adding them to the FormData object. Here's an example in JavaScript:
const formData = new FormData();
const array = [1, 2, 3];
// Encode the array into a string
const encodedArray = JSON.stringify(array);
// Add the encoded array to the FormData object
formData.append("array", encodedArray);
// Send the FormData object in an HTTP request
fetch("https://example.com/api", {
method: "POST",
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
On the server-side, you can decode the string back into an array and use it as needed. The specific implementation will depend on the server-side language you're using.
Related
Im trying to delete an array of id's by implementing a handler that takes a query parameter. I previously implemented a delete api function that takes one id and deletes it. However, now I have a new endpoint that I created that will clear the whole array. The new endpoint is:
The id's in the endpoint above are just dummy ones to show you how it is supposed to take the id's.
The configIds are passed as query parameters,and the response would be something like this:
So what I did was add the new endpoint to the existing delete api function that currently takes one configId. So:
async function deleteConfig(configId) {
const options = {
method: 'DELETE',
headers: {
'content-type': 'application/json'
},
url: configId.includes(',') ? `/api/v1/algo/configs?configIds=${configId}` : `${ALGOS_API_ROOT}/configs/${configId}`
};
return axios(options);
However, I am getting error here:
api/v1/private/api/v1/algo/configs?configIds=41,40,38,23,22 404 (Not Found)
As you can see, the id's are being passed in. But theres an error. Any help would be appreciated. Thanks!
Send the array of id's in the body of the request.
async function deleteConfig(configId) {
const options = {
method: 'DELETE',
headers: {
'content-type': 'application/json'
},
url: `${ALGOS_API_ROOT}/configs`,
data: {
ids: [1, 2, 3]
}
};
return axios(options);
}
Given a simple fetch request i.e.
fetch('https://api.com/endpoint', {
method: "POST"
});
Is it possible / how can following object be converted to query params / query string to append to the fetch request? Most methods online recommend using new URLSearchParams helper, however it doesn't seem to work with nested objects and when converted to string these nested objects are returned as [Object object] string. Ideal solution should not rely on any third party packages.
{
side: 'buy',
symbol: 'AAPL',
type: 'market',
qty: '2',
time_in_force: 'gtc',
order_class: 'bracket',
take_profit: {
limit_price: '200'
},
stop_loss: {
stop_price: '200'
}
}
Form your fetch request like this:
fetch('https://api.com/endpoint', {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(dataYouWannaPost)
});
I am to post an Axios request because using get results in a 414 error.
Here's the object:
rows= {
0 : {
"name":"Thor",
"status":"active",
"email":"somuchlightning#kaboom.io",
},
1 : {
"name":"Mesa",
"status":"active",
"email":"big-mesa#tundra.com",
},
2 : {
"name":"Jesper",
"status":"stdby",
"email":"jes#slap.net,
},
}
This is just a sample of the object's format. There is 400+ elements in the real one, thus post instead of get. I am having trouble properly building the form-data on this one. Here's what I have:
let data = new FormData();
Object.keys(rows).forEach(key => data.append(key, rows[key])); // <--- this doesn't do
data.set('target', target); // <---- this comes through just fine
axios({
method: 'post',
url: 'byGrabthorsHammer.php',
data: data,
headers: {'Content-Type': 'multipart/form-data'}
}).then(function(response) {
if (response.error) {
console.log('failed to send list to target');
console.log(response);
} else {
console.log('response: ');
console.log(response);
}
});
What comes through is just [Object][Object]' when ivar_dump($_POST);`. This is not what I want. How could I rewrite this properly so I get the data to the other side (like GET...).
Yow bro, POST Are for inserting new stuff, instead of doing a post you need a patch
axios.patch it is basically the same. And it won’t fix your issue.
To fix the issue you need to set the Content-Type to application/json, then on yow
axios.post(url, data: JSON.stringify(bigObject))
.then(Rea=>Rea)
You could try stringifying the data. JSON.stringify(data)
I have the following associative array and i try to send it to the server via AJAX.
Checking my console, in the network tab, it's posted but nothing is parsed.
Array creation:
var FiltersArray = [];
FiltersArray['category'] = this.category.val();
FiltersArray['Type1'] = this.type1.val();
FiltersArray['Type2'] = this.type2.val();
Assoc array (console.log):
[category: "6", Type1: "998", Type2: "20100100"]
Request:
$.ajax({
type: POST,
url: 'something.php',
data: {
data: FiltersArray
}
}).done(function(data) {
console.log('Server Response: ' + data);
})
Complete code:
$(document).ready(function() {
var filters = {
category: $("#categoryInp"),
type1: $("#type1Inp"),
type2: $("#type2Inp"),
button: $("#FilterBtn"),
returnArray: function() {
var FiltersArray = [];
FiltersArray['category'] = this.category.val();
FiltersArray['Type1'] = this.type1.val();
FiltersArray['Type2'] = this.type2.val();
return FiltersArray;
},
sendRequest: function(type, URL) {
$.ajax({
type: type,
url: URL,
data: JSON.stringify(this.returnArray()),
beforeSend: function() {}
}).done(function(data) {
console.log('Server Response: ' + data);
}).fail(function() {
alert("An error occurred!");
});
}
};
filters.button.on('click', e => {
console.log(filters.returnArray());
filters.sendRequest('POST', 'Modules/Products.order.module.php');
});
});
There is no such thing as an associative array in JavaScript.
There are objects, which hold key:value pairs of data.
There are arrays, which are a type of object that provides special behaviour when the key name is an integer.
jQuery distinguishes between arrays and other kinds of objects when you pass one in data.
If you pass an array it will not do anything with key:value pairs where the key is not an integer.
Use a plain object and not an array for this.
Aside: Variable names beginning with a capital letter are traditionally reserved for storing constructor functions in JavaScript. Don't use that naming convention for other kinds of data.
var filters = {};
filters['category'] = this.category.val();
filters['Type1'] = this.type1.val();
filters['Type2'] = this.type2.val();
It would be easier to just collect all the data as you create the object though:
var filters = {
category: this.category.val(),
Type1: this.type1.val(),
Type2: this.type2.val()
};
Aside
data: {
data: FiltersArray
}
This will create a (seemingly pointlessly) complex data structure that you'll need to access in PHP as $_POST['data']['category'].
You probably want just:
data: filters
Aside
data: JSON.stringify(this.returnArray()),
This will send JSON instead of form encoded data.
If you do that then you'll also need to:
Set the contentType of the request to indicate that you are sending JSON
Explicitly parse the JSON in PHP
So you probably don't want to do that.
So I have this code:
axios({
method: 'post',
url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: {
json,
type,
}
})
Originally I had the normal axios.post but I changed to this because I thought it might have been a header problem. However I am still detecting nothing in my $_REQUEST nor $_POST. However, it is receiving data in file_get_contents("php://input").
Any idea what is wrong?
Edit
Okay I think I know what's wrong. It's posting it as a json object so it can only be read in the php://input. How do I change it to a normal string in axios?
From the documentation (I haven't preserved links in the quoted material):
Using application/x-www-form-urlencoded format
By default, axios serializes JavaScript objects to JSON.
PHP doesn't support JSON as a data format for populating $_POST.
It only supports the machine-processable formats natively supported by HTML forms:
application/x-www-form-urlencoded
multipart/form-data
To send data in the application/x-www-form-urlencoded format instead, you can use
one of the following options.
Browser
In a browser, you can use the URLSearchParams API as follows:
var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);
Note that URLSearchParams is not supported by all browsers, but there
is a polyfill available (make sure to polyfill the global
environment).
Alternatively, you can encode data using the qs library:
var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));
Or you could customise your PHP so it can handle JSON as per this answer on another question.
var params = {
data1: 'string',
}
axios.post(url, params).then(function(response) {
//code here
});
or
axios.post(url, {data1: 'string' }).then(function(response) {
//code here
});
api
$_POST = json_decode(file_get_contents("php://input"),true);
echo $_POST['data1'];
To make things easier and universal if you ever decided to switch between AJAX libraries or server languages. With axios use the native JS FormData.
If you have your data in an object, you can convert it to FormData like this:
var myDataObj = {id:1, name:"blah blah"}
var formData = new FormData();
for (var key in myDataObj) {
formData.append(key, myDataObj[key])
}
Then you send the data:
axios.post('/sub/process.php', formData, {
params: { action: "update-user" },
headers: { 'Content-Type': 'multipart/form-data' },
baseURL: 'http://localhost',
}).then(data =>
console.log(data)
).catch(err => {
console.log(err)
return null
})
Notice, you can also send some info using params in axios that you can retrieve using $_GET. Also notice that I am using the baseURL in case you have different servers for the web page and your API endpoint.
You need to understand also that before axios send the real request, it performs a preflight request. A preflight request, is a mechanism in CORS by the browser to check if the resource destination is willing to accept the real request or not. Afterall, why would a request be sent when the target host is not willing to receive it anyway?
You have to make sure that your server has the right headers for your axios request, otherwise the preflight request will detect the incompatibility and stop your request:
//this is if you are using different different origins/servers in your localhost, * to be update with the right address when it comes to production
header('Access-Control-Allow-Origin: *');
//this is if you are specifying content-type in your axios request
header("Access-Control-Allow-Headers: Content-Type");
Now, you will able to access your sent data in the $_POST variable:
echo "<pre>";
print_r($_POST);
echo "</pre>";
Additionally, axios allows you to send data in different formats. you can send a json for example like this:
axios.post('/sub/process.php', { id: "1", name:"blablah" }, {
params: { action: "update-item" },
headers: { 'Content-Type': 'application/json' },
baseURL: 'http://localhost',
}).then(data =>
console.log(data)
).catch(err => {
console.log(err)
return null
})
In the PHP side, this can be accessed as follows:
$data = json_decode(file_get_contents("php://input"),true);
echo "<pre>";
print_r($data);
echo "</pre>";
Using PHP std object
Using PHP std object structure to get the variables of the post.
On the client:
axios.post(url, {id: 1 , Name:'My Name' }).then(function(response) {
console.log(response.data);
});
On the server
$obj = json_decode(file_get_contents('php://input'));
$id = $obj->id;
$Name = $obj->Name;
//test by returning the same values
$retObj=(object)["id"=>$id,"Name"=>$Name]
echo json_encode($retObj);
Both jQuery and Axios using same PHP file
if you have a file receiving post both from axios and jquery you may use:
if($_SERVER['REQUEST_METHOD']==='POST' && empty($_POST)) {
$_POST = json_decode(file_get_contents('php://input'),true);
}
to convert the Axios json-serialized posts to the $_POST array
This code works on browser/node both today.
I think this is more practical.
I tested this code on node.js and passed the data variable to PHP8 using $_POST['param1'] and it worked perfectly.
function axqs(d){
let p = new URLSearchParams();
Object.keys(d).forEach(function(key){
p.append(key, this[key]);
}, d);
return p
}
let data = {
'param1': 'value1',
'param2': 'value2',
}
let p = axqs(data)
axios.post('/foo', p)
Just wanted to share my insights, I was facing a similar problem and solved it by the following code set
JS
const instructions_str = {
login: {
"type": "devTool",
"method": "devTool_login",
"data": {
"username": "test",
"password": "Test#the9"
}
},
tables: {
"type": "devTool",
"method": "devTool_get_all_tables",
"data": ""
}
};
const body = {
firstName: 'Fred',
lastName: 'Flintstone',
name: "John",
time: "2pm",
instructions : JSON.stringify(instructions_str)
};
function decodeData(data) {
const serializedData = []
for (const k in data) {
if (data[k]) {
serializedData.push(`${k}=${encodeURIComponent(data[k])}`)
}
}
return serializedData.join('&')
};
const body2 = decodeData(body);
axios.post('URL', body2)
.then(response => {
console.log("contextApi got it", response);
}).catch(error => {
console.log("contextApi error.response", error.response);
});
PHP
// set content return type
header('Content-Type: application/json');
// Setting up some server access controls to allow people to get information
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: POST, GET');
// This way I can check and see what I sent
$postVars_array = $_POST ?? parse_str(file_get_contents("php://input"),$postVars_array) ?? [];
echo json_encode($postVars_array);
I also found this github page very helpful https://github.com/axios/axios/issues/1195