0

I have a checkbox list of items. I need to update my database to which items were selected. The list of items is displayed dynamically.

The problem is how can i pass list of ID's through ajax?

here is my ajax code:

function update(form,div,PhpFile,type)
{
if (request)
    {
        var obj = document.getElementById(divId);
        request.open("POST",PhpFile);
        //setting the header
        request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

        request.onreadystatechange = function()
        {   
            if (request.readyState == 4 &&
                    request.status == 200){
                obj.innerHTML =request.responseText;
            }
        }

        if(type=='news')
            request.send(?????);

    }
}

I've marked with ??? the space that I don't know what to put there.

Of course I can update each of the check boxes individually but it is a very bad solution.

arthur
  • 539
  • 1
  • 7
  • 21

3 Answers3

1

PHP 5 can decode JSON and in JS you will need to use a library. This seems to be a popular answer.

Serializing to JSON in jQuery

And JSON in PHP http://www.php.net/manual/en/function.json-decode.php

Community
  • 1
  • 1
ian.shaun.thomas
  • 3,468
  • 25
  • 40
  • Or just use `JSON.stringify(theArrayVar)`, that way you don't need to include a huge lib. JSON is widely supported, even IE won't complain – Elias Van Ootegem Apr 10 '12 at 19:04
0

I think you can serialize the array in JavaScript, pass it as a string with AJAX, and then unserialize it in PHP. Either that or convert the array values to a delimited string (comma or pipe separated) and then explode that string in PHP. That leaves your transmitted data human readable, which is nice for debugging.

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
0

Convert the array to JSON with JSON.stringify(), send it, then convert the JSON string back to an object in PHP with json_decode().

Jonathan M
  • 17,145
  • 9
  • 58
  • 91