jh95
jh95

Reputation: 399

How to use a foreach loop with AJAX call?

I have a foreach loop that is called from my AJAX code. It appears that the foreach loop is being skipped right over. I would ultimately like to make it so that the foreach loop will execute a query using each value in the array, but I am first trying to test the the foreach loop works (which it does not). The alert (from my AJAX) that I am receiving is just the original array and not the one with the added items.

PHP:

   $data = array();
   if(isset($_POST['myArray']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH']){ 
    $data = $_POST['myArray']; 
    foreach ($data as $item) {
        $data[] = $item;
    }
    echo json_encode($data);
    die();      
} 

AJAX:

$(document).ready(function(){
    $('#btn-addkegs').click(function() {
        var arr = kegs;
        var myArray =  JSON.stringify(arr);

        $.ajax({
            url: "addkegs.php",
            method: "POST",
            dataType: "json",
            data: {myArray: myArray},
            success: function (result) {
            alert("Your kegs have been added! These include: " + result);
            textarea.value = "";
            kegs = [];
         }
                    });

            });
        });

As for the line var arr = kegs;, the value of the array 'kegs' is set through an input field and other AJAX, but all that works fine. I think that my problem is with my PHP code.

Upvotes: 0

Views: 1820

Answers (2)

jh95
jh95

Reputation: 399

Answer from a comment by @David:

In your browser's debugging tools, take a look at the network requests. Examine the AJAX request and its response. If the result is entirely wrapped in quotes, then it's just a string and not an array. You may need to JSON-decode $_POST['myArray'] server-side to interpret it as an array.

I needed to change $data = $_POST['myArr']; to $data = json_decode($_POST['myArr']);.

Upvotes: 0

Ramon Schmidt
Ramon Schmidt

Reputation: 168

If you are send via post only values... like in comments : 1,2,3 your $_POST['myArray'] was receive literaly what you sent to.

So, data variable will receive the array that seems like this ['1','2','3']

Well... Since you are not creating a variable $data as an Array, and yes, only putting an array inside it.

The PHP doesnt consider the $data[] variable as same as $data.

So, the PHP was magicaly overwriting the values from each same values.

So, I think if you want to repeat the values in the same array, you must reference the array with the array_push

$data = $_POST['myArray']; 
foreach ($data as $item) {
    array_push($data, $item);
}

Now when you return this array, you will have a response like {1,2,3,1,2,3}

Upvotes: 0

Related Questions