2

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!");
        }
    });
}
2
  • 1
    you don't have an array, array is clearly defined as a string, try creating an array instead Commented Aug 21, 2015 at 7:39
  • How? I've never done this before in JavaScript so I don't know HOW Commented Aug 21, 2015 at 7:40

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Can you help me with one more stuff. Ive got this loop for (i = 0; i < kasce.length; i++) { var checkIF = document.getElementById(i); Am i writing this corectly document.getElementById(i)? Because im getting error :/
@McLaren: That would be correct if you had elements with id="0", id="1", etc., in your document. I assume you don't. :-) The code in your question accessing kasce is correct, assuming you have multiple elements with name="impTaskCh". (Except you need to declare i, see the [new] end of the answer above.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.