jqueryajax.post

How to pass a PHP Array into jQuery AJAX $.post


Objective:
I have php array variable, and I need to put this array ($key and $value) into the jQuery AJAX $.post, and send it to another php(next.php) page.

PHP array Variable:

$issue['key01']='value01';  
$issue['key02']='value02';

jQuery Ajax:

<head>
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function() {
    $("#ButtonCreate").click(function() {
    $.post("next.php",
                {
                ?????????
                },        
    function(data, status)  {
            document.getElementById("ResultBack").innerHTML = data;
    });
});
});
</script>
</head>


<body>
    <button id="ButtonCreate">Proceed DB Initialize</button>
    <p id="ResultBack"></p>
</body>

Problem and my finding:
The code has no issue if I directly use the string name and value. If I use non-array php variable, I still know how to do it. But I don't have any idea on how to pass a php array variable.

I can think of using php foreach command to run through the array, but its really headache. there is even a if-command to decide to put comma(,) in between the variable. Conclusion is a long and stupid way.

Please advice Thanks.


Solution

  • you can use json_encode to make a valid javascript object

    $("#ButtonCreate").click(function() {
        $.post("next.php", <?php echo json_encode($issue); ?>,        
        function(data, status)  {
            document.getElementById("ResultBack").innerHTML = data;
        });
    });
    

    if you would like to send 2 array via ajax, you can create a new array like this:

    <?php echo json_encode(array(
        'issues' => $issue,
        'foo' => $foo,
    )); ?>