Skip to content Skip to sidebar Skip to footer

Pass Javascript Array To PHP Using AJAX

I have to pass Javascript array variable to PHP , so here php and javascript code both are in same page . when i give console inside isset($_POST['kvcArray'])) -- > it is not pr

Solution 1:

Based on your edit couple of notes about your code: 1st - put all you javascript function in 1 place, lets say just before the closing body tag - like this:

<script>
    $(document).ready(function(){
      // all your function here ! in 1 place
    });
</script>
</body>
</html>

2nd - not so important but still, move all the php code at the top of your file:

<?php
  // all the php here
?>
<!DOCTYPE html>
<html>
<head>
...
...

As far as I understand you're making request to the same page where you form with check boxes is. So you can have something like this:

<?php
    if (isset($_POST['kvcArray'])) {
        echo "<pre>";
        echo "<b>".__FILE__."</b><br/>";
        var_dump(json_decode($_POST['kvcArray'], true));
        echo "</pre>";
        die();
    }
?>

<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox1" name="options[]" value="1"><label for="checkbox1"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox2" name="options[]" value="2"><label for="checkbox2"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox3" name="options[]" value="3"><label for="checkbox3"></label></span><br />
<span class="custom-checkbox"><input type="checkbox" class="checkbox" id="checkbox4" name="options[]" value="4"><label for="checkbox4"></label></span><br />
<input type="submit" class="button" name="insert" value="insert" />

Note that I have edited your js code, the way you're constructing your array and also no need to use "url" inside ajax when posting to same page!

<script type="text/javascript">
    $( document ).ready(function() {
        $( ".button" ).click(function() {

            var val = [];
            $("input:checked").each(function (index,value) {
                    val[index] = this.value;
            });

            var myJSONText = JSON.stringify(val);
            $.ajax({
                data: {'kvcArray': myJSONText},
                url: 'index.php',
                type: 'POST',
                success: function(result) {
                    //alert("Success");
                }
            });
        });
    });
</script>

This code has been tested and works on 100%


Post a Comment for "Pass Javascript Array To PHP Using AJAX"