-1

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.

Sapnesh Naik
  • 11,011
  • 7
  • 63
  • 98
BSS
  • 53
  • 2
  • 9

2 Answers2

1

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,
)); ?>
Sysix
  • 1,572
  • 1
  • 16
  • 23
  • Thanks man. Tested the code..it really work. Was wondering if I am pushing two array variable, does that means I can use the same mention too? – BSS May 18 '17 at 15:17
  • your multiple array seem very weird, why should you do 'issues' => $issue ? what does the front part means ? – BSS May 19 '17 at 18:13
  • so you can call in javascript `data.issues.key01` to get your value. maybe you must parse the json with `JSON.parse` – Sysix May 19 '17 at 18:35
0
  $(document).ready(function(){

  $("#id_form").on("submit", function() {
    if(window.localStorage!==undefined) {
        var JSvar = $(this).serialize();
      $.ajax({
        url: "sql_update_bill.php",
        type: "POST",
        data: Jsvar,
 
       });
      };
    });
  });
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 31 '22 at 07:38