0

I was trying to send an associative array of warnings when a button is clicked. It will pass id and type of warning and trigger collect function which stores them into the array as key value pairs. Then I want to send it to another page. The problem is if it is simple array it will work when I call $_POST ['warn']; but if I change it to an associative array I will get error msg saying that warn is not defined. This is my JS code:

var warnings = [];
function collect(id,type){ warnings [id]  = type;}
$('#but1').click (function (){
  $.post ("url", {warn: warnings}function(r){alert (r);});
});

Is there a way to send the associative array as key value pairs using AJAX to my php page and get the array using $_POST?

4
  • 1
    You could use JSON.stringify(warnings) and then parse the JSON on your php page Commented Aug 30, 2016 at 20:56
  • You're using jQuery, so you're already doing it, the data will be parsed as www-urlencoded, you just have to access the correct keys in PHP Commented Aug 30, 2016 at 20:58
  • You're missing a comma between your data and your callback function in the $.post call, but that would have caused other issues, so I'm guessing that's a typo. Commented Aug 30, 2016 at 20:59
  • JavaScript does not have associative arrays. You should better not use an array, but a plain object. Initialise as warnings = {};. Commented Aug 30, 2016 at 21:01

1 Answer 1

0

Your warnings could be constructed like so in JavaScript:

var warnings = {

    warning1: {
        id: 1,
        type: 'info'
    },

    warning2: {
        id: 2,
        type: 'danger'
    }

}

Then send the warnings object as JSON to the server in PHP. You may parse it like so:

$json = json_decode(filter_input(INPUT_POST, 'warnings'));

Be sure that warnings corresponds to the data in your ajax call.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.