0

I am creating Web application in which I have two different list. I have convert list into array and that array I want to pass from JavaScript to PHP for further analysis.

This is an Example which is similar to my original code

test_2.html

<form method="post" id="theform" action="test_2.php">
        <ul id="control">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ul>
        <ul id="treatment">
            <li>6</li>
            <li>7</li>
            <li>8</li>
            <li>9</li>
            <li>10</li>
        </ul>
    <button>Submit</button>
</form>

<script>
    window.onload = function () {
        var form = document.getElementById('theform');
        var  lst = [];
        var lst2 = [];
        form.addEventListener('submit', function () {
            var lis1 = document.querySelectorAll('#control li');
            for (var i = 0; i < lis1.length; i++) {
                lst.push(+lis1[i].innerText);
            }

            var lis2 = document.querySelectorAll('#treatment li');
            for (var i = 0; i < lis2.length; i++) {
                lst2.push(+lis2[i].innerText);
            }
            var array = [lst, lst2]

            $.ajax({
                type: "POST",
                url: "php/test_2.php",
                data: {"data":array},
                datatype: "json",
                success: function(response){
                    alert("response " + response);
                }
            });
    }
</script>

test_2.php

$sub_array = var_dump($_POST['data']);
echo $sub_array;

The problem is I am not able to pass the array. I have tried my thing and also did refer many question :-

Get all LI elements in array

how to use JSON.stringify and json_decode() properly

Passing Javascript array to PHP file

Get response from PHP file using AJAX and many more

  • _Side note_ : `var_dump()` returns `void`. So, `$sub_array = var_dump(...)` doesn't make sense. – Syscall Mar 02 '21 at 10:30
  • Why are you trying to submit a _static_ list of values in the first place? If the user has no ability of changing any of these values - then you must have known them all at the point these lists were created already. Which presumably happened on the server(?). So why do you need to submit values _to_ the server now, that the server should already know? – CBroe Mar 02 '21 at 10:33
  • you could use json stringify to convert your array to string in JavaScript and then in php use json_decode to convert it back. – Farhad Mar 02 '21 at 10:35
  • @Farhad I have tried my system goes laggy and Doesn't respond to page – Nastin Gaming Mar 02 '21 at 10:39
  • @CBroe This is just an example. list is totally dynamic – Nastin Gaming Mar 02 '21 at 10:41
  • Dynamic based on _what_? Where does it get created then - on the client side? – CBroe Mar 02 '21 at 10:41
  • @CBroe client has to drag the list into list after submit list value should be pass in the array. – Nastin Gaming Mar 02 '21 at 10:44
  • First of all, your code as shown contains a syntax error - so go fix that first of all, as long as your code is not even able to _execute_, you can’t expect it to _achieve_ much either. Second, you did nothing to prevent the default submission of the form - so this will submit the formal normally, causing a new HTTP request, which cancels all your JS code and attempted AJAX request. – CBroe Mar 02 '21 at 10:51

3 Answers3

1

Try Adding prevent default on submit function. It will halt the form submission and the Ajax will fire.

<form method="post" id="theform">
        <ul id="control">
            <li>1</li>
            <li>2</li>
            <li>3</li>
            <li>4</li>
            <li>5</li>
        </ul>
        <ul id="treatment">
            <li>6</li>
            <li>7</li>
            <li>8</li>
            <li>9</li>
            <li>10</li>
        </ul>
        <button>Submit</button>
    </form>
    
    <script>
        window.onload = function () {
            var form = document.getElementById('theform');
            var lst = [];
            var lst2 = [];
            form.addEventListener('submit', function (e) {
                e.preventDefault();
                var lis1 = document.querySelectorAll('#control li');
                for (var i = 0; i < lis1.length; i++) {
                    lst.push(+lis1[i].innerText);
                }
    
                var lis2 = document.querySelectorAll('#treatment li');
                for (var i = 0; i < lis2.length; i++) {
                    lst2.push(+lis2[i].innerText);
                }
                var array = [lst, lst2];
    
    
                $.ajax({
                    type: "POST",
                    url: "php/test_2.php",
                    data: {'data':array},
                    datatype: "json",
                    success: function (response) {
                        alert("response " + response);
                    }
                });
            });
        }
    </script>
0

You have some syntax error in Javascript and calling 2 times the page text_2.php, one in <form> and the second one into ajax call.

test_2.html

<form method="post" id="theform">
    <ul id="control">
        <li>1</li>
        <li>2</li>
        <li>3</li>
        <li>4</li>
        <li>5</li>
    </ul>
    <ul id="treatment">
        <li>6</li>
        <li>7</li>
        <li>8</li>
        <li>9</li>
        <li>10</li>
    </ul>
    <button>Submit</button>
</form>

<script>
    window.onload = function () {
        var form = document.getElementById('theform');
        var lst = [];
        var lst2 = [];
        form.addEventListener('submit', function () {
            var lis1 = document.querySelectorAll('#control li');
            for (var i = 0; i < lis1.length; i++) {
                lst.push(+lis1[i].innerText);
            }

            var lis2 = document.querySelectorAll('#treatment li');
            for (var i = 0; i < lis2.length; i++) {
                lst2.push(+lis2[i].innerText);
            }
            var array = [lst, lst2];


            $.ajax({
                type: "POST",
                url: "php/test_2.php",
                data: {'data':array},
                datatype: "json",
                success: function (response) {
                    alert("response " + response);
                }
            });
        });
    }
</script>

test_2.php

<?php

var_dump($_POST['data']);
Mariano
  • 473
  • 3
  • 12
0

JSON.stringify(array) to pass array in JSON format.

Use preventDefault() because preventDefault() will stop HTML form from submitting and will allow $.ajax to submit form instead. In your case you are not using preventDefault(), so ajax is not firing and form is submitting by HTML form action.

Also note I passed e inside callback function of addEventListener. use that to call preventDefault(). (You can use any name)

form.addEventListener('submit', function (e) {
                e.preventDefault(); //This will halt the submission
                var lis1 = document.querySelectorAll('#control li');
                for (var i = 0; i < lis1.length; i++) {
                    lst.push(+lis1[i].innerText);
                }
    
                var lis2 = document.querySelectorAll('#treatment li');
                for (var i = 0; i < lis2.length; i++) {
                    lst2.push(+lis2[i].innerText);
                }
                var array = [lst, lst2];
    
                $.ajax({
                    type: "POST",
                    url: "php/test_2.php",
                    data: {"data":JSON.stringify(array)}, //This will convert JSON to array
                    datatype: "json",
                    success: function(response){
                        alert("response " + response);
                    }
                });
            });

Inside PHP use,

$data = json_decode($_POST["data"]);