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:

<?phpif (isset($_POST['kvcArray'])) {
        echo"<pre>";
        echo"<b>".__FILE__."</b><br/>";
        var_dump(json_decode($_POST['kvcArray'], true));
        echo"</pre>";
        die();
    }
?><spanclass="custom-checkbox"><inputtype="checkbox"class="checkbox"id="checkbox1"name="options[]"value="1"><labelfor="checkbox1"></label></span><br /><spanclass="custom-checkbox"><inputtype="checkbox"class="checkbox"id="checkbox2"name="options[]"value="2"><labelfor="checkbox2"></label></span><br /><spanclass="custom-checkbox"><inputtype="checkbox"class="checkbox"id="checkbox3"name="options[]"value="3"><labelfor="checkbox3"></label></span><br /><spanclass="custom-checkbox"><inputtype="checkbox"class="checkbox"id="checkbox4"name="options[]"value="4"><labelfor="checkbox4"></label></span><br /><inputtype="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!

<scripttype="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"