Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

aheerwagen's avatar

Empty Ajax Request & Invalid argument supplied for foreach() error

The Issue

Request being sent via ajax is empty within the controller, results in Invalid argument supplied for foreach() error.

The majority of requests are submitted with no problems and have the data that is expected in the request. The error occurs seemingly randomly and we have been unable to reproduce the error even with replicating inputs of a user that receives in errors.

The issue starting occurring after updating Laravel Forge to PHP 7.1 from PHP 7.0. Once we noticed the error we downgraded to PHP 7.0 but the error persisted.

What we know

  • There seems to be no relation between
    • Browser
    • Browser version
    • User input
  • Request is submitted via ajax
  • There is no data in the request at the top of the controller

Relevant code where data is being sent via ajax

var signatureImageUrl = $("#jSignature").get(0).toDataURL();

$.ajax({
    method: "POST",
    url: "submit",
    contentType: "application/x-www-form-urlencoded; charset=UTF-8",
    data: {
        "visit_data": $("form").serializeArray(),
        "signature_img_url": signatureImageUrl,
    }
});

Relevant code where the error is being thrown within the controller

public function submit(Request $request) {
    try {
        foreach ($request->input('visit_data') as $index => $visitComponent) {
            // Iterates over data
        }
    } catch (\ErrorException $e) {
        // Handles error
    }
0 likes
2 replies
Cronix's avatar

It could be they submit the form before the javascript has loaded/executed, or javascript is disabled.

Since your js is creating custom data elements that it's sending in the ajax request, it wouldn't process bc 'visit_data' wouldn't exist, but the real form names/values would.

I'd suggest not using custom data values (like you are in your ajax request) and submit the form as is, and append 'signature_img_url' to it. That way it would work with or without js.

// serialize the form so ajax will send the same data as form, and append signature_img_url
data: $("form").serialize() + '&signature_img_url=' + signatureImageUrl

Then in your controller, process the form as normal. Since 'signature_img_url' is being added to the ajax request, I'd conditionally check that.

// check to make sure it exists first
if ($request->has('signature_img_url')) {
    $user->signature_img_url = $request->signature_img_url;
}

Please or to participate in this conversation.