Array as Ajax request data?

Array as Ajax request data?

Rawland_HustleRawland_Hustle Posts: 94Questions: 16Answers: 0

I want to send the id's from the selected rows to an API with the Ajax option but no matter what I try, I can't send the id's as an array.

Below is an example of what I've tried. It will result in the following url: getStatistics.php?ids=1&ids=2&ids=3&ids=4. What I really want is this: getStatistics.php?ids=1,2,3,4

var selectedIds = [1,2,3,4];
"ajax": {
               "url": "getStatistics.php",
               "traditional": true,
               "data": {"ids": selectedIds  }
}

This question has accepted answers - jump to:

Answers

  • allanallan Posts: 61,822Questions: 1Answers: 10,129 Site admin
    Answer ✓
    {"ids": selectedIds.join(',')  }
    

    Allan

  • Rawland_HustleRawland_Hustle Posts: 94Questions: 16Answers: 0

    Thanks for your answer! Unfortunately I am not able to test it right now. But I am curious though; how come I must join items in an array? It seems redundant.

  • Rawland_HustleRawland_Hustle Posts: 94Questions: 16Answers: 0

    I might have figured it out. Is it because the variable needs to be converted in to a string?

  • Rawland_HustleRawland_Hustle Posts: 94Questions: 16Answers: 0

    Now I've tested it and unfortunately it doesn't work. Now the url looks like this:

    getStatistics.php?ids=1%2C2%2C3%2C4

    How do I escape the commas?

  • Rawland_HustleRawland_Hustle Posts: 94Questions: 16Answers: 0

    Apparently one didn't have to escape the commas so I'm good!

    Thanks a lot for your help!

  • allanallan Posts: 61,822Questions: 1Answers: 10,129 Site admin
    Answer ✓

    I might have figured it out. Is it because the variable needs to be converted in to a string?

    Exactly that. The way jQuery submits arrays is to send each element as name[] which many server-side environments will treat as an array automatically for you.

    If you want a comma separated string, you need to give it that.

    Allan

This discussion has been closed.