I'm assuming you're making a POST request with a JSON payload. First, you want to make sure your payload is formatted JSON correctly, use: http://pro.jsonlint.com/
Secondly, you can send the payload using JSON.stringify and you will want to set the contentType:
data: JSON.stringify(data), contentType: "application/json; charset=utf-8"
If you run this and look at your network tab in Dev Tools in Chrome, it will error out, but you will at least see the payload formatted to send to the server: http://prntscr.com/f8hf6s
var data = [{
"key": "myKey",
"keyName": "myKeyName",
"value": "value",
"valueName": "valueName"
},
{
"key": "mySecondKey",
"keyName": "mySecondKeyName",
"value": "secondValue",
"valueName": "secondValueName"
}
];
var url = "http://swapi.co/api/";
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function() {
alert("Error");
},
success: function() {
alert("OK");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Answer from Woodrow on Stack OverflowTry this one:
var a = {};
a['test'] = 1;
a['test2'] = 2;
// or
var a = {};
a.test = 1;
a.test2 = 2;
// or
var a = {
test : 1,
test2 : 2
};
$.ajax({
url: baseUrl+"chat.php",
data: a,
type: 'post',
success: function(data) {
alert(data);
}
});
You may then access the data in your PHP script like this:
$_POST['test'];
$_POST['test2'];
I used this:
var newArray = new Array();
newArray.push("item1");
newArray.push("item2");
newArray.push("item3");
$.ajax({
type: "POST",
url: urlToPost,
data: JSON.stringify(newArray),
contentType: "application/json"
});
html - How to post array / data structure via javascript? - Stack Overflow
Sending a JavaScript array to PHP via POST - Stack Overflow
jQuery post array
javascript - axios post array data
Short backstory: I learned Angular straight out of uni and thought it might be useful to get some basic knowledge about how the web works on a fundamental level. So I decided to build a small MPA with Go as a backend language.
Now I got to a problem that would be trivial to solve in Angular but I am having trouble solving with server-side rendering:
Imagine a traditional form where I can add and remove items (kind of like a shopping cart) with javascript and once I am done I can click on "Save" and all items are send to the server with a POST request. The special thing is that the items are complex objects with multiple properties, not just strings.
I would prefer to use a form and just submit it, but it feels like this type of complex data does not go well with a form. I know that PHP can handle this kind of structure (https://stackoverflow.com/questions/34313657/html-form-post-an-array-of-objects), but I don't think this is standard, since there doesn't seem to be a way to do this in Go. So is my only choice to send JSON? But how do I transform my input values to JSON?
So the question is this: what is the best practice when I need to send an array of objects to the server and how would a person have solved this 10 or 15 years ago?
I generally use $.ajax for this purpose but since you have asked not to use jquery, so in that case you need to make XHR Request to the endpoint specified in you node application.
Client Side
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if(xmlhttp.status == 200){
console.log('request successfull : ', xmlhttp.responseText);
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("post", "~/process_post", true);
xmlhttp.send(JSON.stringify(..........)); //your custom data
Server Side Node
app.post('/process_post', urlencodedParser, function (req, res) {
console.log("Got request: " + res.body);
});
Just looking for some another question already asked on Stackoverflow, I find this useful for you.
Use $.ajax
Suppose if your using array called sample like in below
var sample=[1,2,3,4];
then your ajax call should be like this
$.ajax({
url: "test.html",
data: sample,
}).done(function(result) {
//do the stuffs with the result here
});
This call will send the sample array to test.html (as per our example) Then the response will be stored in result variable
Let me know if it is helpful
That's not how POST request works. Read more about Ajax, but for now, that's how you should do it.
var songlist = ['song1', 'song2', 'song3'];
var sendData = function() {
$.post('test.php', {
data: songlist
}, function(response) {
console.log(response);
});
}
sendData();
// test.php
<?php
$songData = $_POST['data'];
print_r($songData);
?>
Run code snippetEdit code snippet Hide Results Copy to answer Expand
1) $.post('url') - Ajax request is done by $.post() method and you have given "testing.php" as url which is invalid.
2) window.location = 'test.php' - This is used for redirecting to specific page and you have redirected to 'test.php' without any parameter/data. Thats why its showing "Notice: Undefined index: data"
3) Try to understand how ajax works. Follow it -
var songlist = ['song1', 'song2', 'song3'];
var sendData = function() {
$.post('test.php', {
data: songlist
}, function(response) {
console.log(response);
});
}
sendData();
// test.php
<?php
if(isset($_POST)){
if(isset($_POST['data'])){
$songData = $_POST['data'];
print_r($songData);
}}
?>
Try this one:
var a = {};
a['test'] = 1;
a['test2'] = 2;
// or
var a = {};
a.test = 1;
a.test2 = 2;
// or
var a = {
test : 1,
test2 : 2
};
$.ajax({
url: baseUrl+"chat.php",
data: a,
type: 'post',
success: function(data) {
alert(data);
}
});
You may then access the data in your PHP script like this:
$_POST['test'];
$_POST['test2'];
I used this:
var newArray = new Array();
newArray.push("item1");
newArray.push("item2");
newArray.push("item3");
$.ajax({
type: "POST",
url: urlToPost,
data: JSON.stringify(newArray),
contentType: "application/json"
});
This issue popped up for me as well, and I solved it with new FormData().
Having an array:
const product_id_list = ['pid1234', 'pid1235']
const bodyFormData = new FormData();
product_id_list.forEach((item) => {
bodyFormData.append('product_id_list[]', item);
});
axios.post('https://test.com/api/get_product', bodyFormData)
Doing it this way sent it the request as application/x-www-form-urlencoded, and the proper data in the body.
You can use the native axios to create a request. You can pass your payload with the data key.
import axios from 'axios';
let payload = {
product_id_list: ['pid1234', 'pid1235']
};
axios({
url: 'https://test.com/api/get_product',
method: 'post',
data: payload
})
.then(function (response) {
// your action after success
console.log(response);
})
.catch(function (error) {
// your action on error success
console.log(error);
});
You can try running your axios code from your browser here.
If you want to pass a JavaScript object/hash (ie. an associative array in PHP) then you would do:
$.post('/url/to/page', {'key1': 'value', 'key2': 'value'});
If you wanna pass an actual array (ie. an indexed array in PHP) then you can do:
$.post('/url/to/page', {'someKeyName': ['value','value']});
If you want to pass a JavaScript array then you can do:
$.post('/url/to/page', {'someKeyName': variableName});
This is fairly straightforward. In your JS, all you would do is this or something similar:
var array = ["thing1", "thing2", "thing3"];
var parameters = {
"array1[]": array,
...
};
$.post(
'your/page.php',
parameters
)
.done(function(data, statusText) {
// This block is optional, fires when the ajax call is complete
});
In your php page, the values in array form will be available via $_POST['array1'].
references
- jQuery post()
- jQuery ajax()
Be sure to stringify before sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.
Works:
$.ajax({
url: _saveAllDevicesUrl
, type: 'POST'
, contentType: 'application/json'
, data: JSON.stringify(postData) //stringify is important
, success: _madeSave.bind(this)
});
I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.
Try the following:
$.ajax({
url: _saveDeviceUrl
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: {'myArray': postData}
, success: _madeSave.bind(this)
//, processData: false //Doesn't help
});
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
Ok, from your question I understand that you want to manipulate the POST Body like a json array then use qs library by making extended true
app.use(bodyParser.urlencoded({ extended: true }));
You can send an string instead of array and keep the extended option in false.
From your front js:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
$.ajax("/send", {
data: { "strArr": fruits.join() },
type: "POST",
async: true,
......
From your server js:
router.post('/send', function(req, res) {
var fruits = req.body.strArr.split(",");
console.log(fruits); // This is an array
});
You javascipt object properties do not have indexers, so you need to use the ajax contentType: "application/json" option and stringify the object
var myArray = [{"id": 1, "name", "John"},{"id": 2, "name", "Joe"},{"id": 3, "name", "Bill"}]
$.ajax({
type: 'post',
url: '@Url.Action("Update", "MyController")', // don't hardcode your url's!
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ people: myArray }),
success: function (data) {
....
}
})
Side note. The following object would post back
var myArray = { people[0].id: 1, people[0].name: "John", people[1].id: 2, people[1].name: "Joe" }
using
$.post('@Url.Action("Update", "MyController")', myArray, function() {`
My personal favorite is using JSON.NET (available through NuGet).
You may define on your Action that it would expect a JObject or JArray.
Then in the Action you just cast your input to your expected type.
From js perspective you just do your post normally.
Example:
public ActionResult Update(JArray input)
{
var persons = input.Select(x=>x.ToObject<Person>()) // This will return an `Enumerable<Person>`
//Do your other stuff here
return Json(new {Success = true});
}
public class Person
{
public int id {get;set;}
public string name {get;set;}
}