Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send array with alphanumeric keys with Ajax to PHP script

I need to receive names of keys and values from alphanumeric array sended 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 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'm doing this way:

 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'm doing this way:

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} ,
    });   
}

there is Uncaught SyntaxError: Unexpected token [ in this line 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 without syntax error Uncaught SyntaxError: Unexpected token [

like image 730
Sruj Avatar asked Aug 11 '26 10:08

Sruj


1 Answers

If you have a form element surrounding the fields, the easiest way to do that would be 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 address selections of individual form controls.

like image 109
jeroen Avatar answered Aug 12 '26 22:08

jeroen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!