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 OverflowIn 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
}
});
How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array? - Stack Overflow
What is the "best practice" for sending an array of objects to the server?
Send an array of JavaScript objects via POST - Stack Overflow
javascript - Send Array in post request using node.js using application/x-www-form-urlencoded - Stack Overflow
As mentioned, use serializeArray(). To add your extra parameter, just append it to the array as shown below.
function setupForm(){
$("#add").submit(function(event) {
event.preventDefault();
var data = $(this).serializeArray();
// add extra parameters (don't forget brackets)
data.push({ name: 'loc[]', value: 44 });
data.push({ name: 'loc[]', value: 44 });
$.ajax({
type: "POST",
url: "http://localhost:3000/services",
data: data,
success: function() {
alert('success');
}
});
});
}
If you want to continue using your method of just building the query string, you would have to add &loc[]=44&loc[]=44 but it is better in the long run to just use one of the serialize functions.
Given the data you are using, I would advise sending the data in the POST requests' body. This will retain the datatypes (array, bools, etcs) thanks to JSON.
$.post("http://localhost:3000/services", {
name: $("#name").val(),
loc: [44, 44]
...etc
}, function(){alert('success');}
);
Backend should work fine without alterations. You might need to add body-parser to your middleware stack. The body-parser middleware will transform the body into a javascript object that you can push right into your database.
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()
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?
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);
}}
?>
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