McLaren
McLaren

Reputation: 776

Problems with sending array through ajax

Hello stackoverflow community, I need help with my JavaScript. How can I transfer array with id of kasce?

When I'm printing array in ajax_import.php file, it prints nothing. So probably my array is empty.

Here is my code:

function SubmitImp() {
    var import_tasken = document.getElementById("import_tasken");
    //import_tasken.style.display = "none";
    var kasce = document.getElementsByName("impTaskCh");
    var array = "";
    for (i = 0; i < kasce.length; i++) {
        array[i] = kasce[i].getAttribute('id');
    }
    $.ajax({
        type: "POST",
        url: 'modules/projects/ajax/ajax_import.php',
        data: {
            data: array,
        },
        success: function(data)
        {
            alert("Viskas ok!");
        }
    });
}

Upvotes: 2

Views: 50

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075019

A couple of problems there.

First, you're not sending an array, you're sending a blank string.. Here, you put a string in array:

var array = "";

Later, you do this:

array[i] = kasce[i].getAttribute('id');

...which is trying to assign a new value to a single character of the string. You can't do that, strings are immutable in JavaScript; the line ends up not changing the string at all.

array[i] is a single character in the string. You're trying to assign a string to it.

To make array an array, use:

var array = [];

Next, and this may not be a problem, here:

data: {
    data: array,
}

...you're telling jQuery to send a URI-encoded parameter called data with the value array. jQuery will call toString on array, which with a true array ends up being Array#join. That may well be what you want, you'll get something like this:

firstId,secondId,thirdId

Your PHP should look for it as $_POST['data'].


Side note: You're falling prey to The Horror of Implicit Globals because you never declare your i variable. You want to declare it.

Upvotes: 2

Related Questions