Send array with alphanumeric keys from Ajax to PHP script
I need to get the names of the keys and values from an alphanumeric matrix sent by ajax to php.
from this:
<input class="input" name="one" value="1" onchange="myFunction()">
<input class="input" name="two" value="2" onchange="myFunction()">
<input class="input" name="three" value="3" onchange="myFunction()">
which is parsed from the loop
{% for x in y %}
<input class="input" name="{{ x.k }}" value="{{ x.v }}" onchange="myFunction()">
{% endfor %}
I need to print_r () something like this:
Array
(
['one'] => 1,
['two'] => 2,
['three'] => 3,
)
if i do like this:
function myFunction() {
var elementy = document.getElementsByClassName('input');
var data = {};
var key = elementy[0].name;
var value = elementy[0].value;
data = { key: value};
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: {data:data} ,
});
}
print_r ($ data) return:
Array
(
[key] => 1
)
if i do like this:
function myFunction() {
var elementy = document.getElementsByClassName('input');
var data = {};
data = {elementy[0].name : elementy[0].value};
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: {data:data} ,
});
}
in this line Uncaught SyntaxError: Unexpected token [
data = {elementy[0].name : elementy[0].value};
I need to do something like this:
function myFunction() {
var data = [];
var elementy = document.getElementsByClassName('input');
for (var i = 0; i < elementy.length; i++){
data[elementy[i].name] = elementy[i].value;
}
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: {data:data}
});
}
but no syntax error Uncaught SyntaxError: Unexpected token [
source to share
If you have an element form
surrounding fields, the easiest way to do this is to serialize the form:
data: $('form').serialize()
^^^^ if you have more forms, address it by its ID or something similar
If you don't have a form, you can also use:
data: $('.input').serialize()
as serialize
can also be used to select individual form controls.
source to share
instead
function myFunction() {
var data = [];
var elementy = document.getElementsByClassName('input');
for (var i = 0; i < elementy.length; i++){
data[elementy[i].name] = elementy[i].value;
}
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: {data:data}
});
}
it should be
function myFunction() {
var data = {};
var elementy = document.getElementsByClassName('input');
for (var i = 0; i < elementy.length; i++){
data[elementy[i].name] = elementy[i].value;
}
$.ajax({
url: "{{ path('test') }}",
type: "POST",
data: {data:data}
});
}
source to share