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

Danny971's avatar

Issue with AJAX form submission using jQuery

I'm currently working on a web application that involves submitting a form using AJAX and jQuery. However, I'm facing difficulties in getting the form submission to work as expected. Here's my code:

  <div class="form-group row">
  <div class="col-lg-8">
    <div class="d-flex align-items-center">
      <h4 class="text-primary mr-2">DECISION:</h4>
      <select class="form-control" id="decisionDropdown" name="decisionDropdown" onchange="toggleReasonDropdown()" >
        <option value="OPTION">Please select</option>
        <option value="APPROVE">APPROVE</option>
        <option value="DECLINE">DECLINE</option>
      </select>
    </div>
  </div>
</div>


                                                        
                                                    </div>
                                                </div>

                                                <div class="col-xl-8 col-sm-8 border-right-1 prf-col">
                                                    <div class="profile-email">

                                                    <h4 class="text-primary">ADDRESS : <span class="text-muted"> {{$clients -> address}} </span></h4>

                                                    <h4 class="text-primary">REQUESTED DATE : <span class="text-muted"> {{\Carbon\Carbon::parse($pendingcases-> first() ->daterequested)->format('m/d/Y h:i A')}} </span> </h4>

                                                    <h4 class="text-primary">PHONE : <span class="text-muted">{{ $clients -> phone}}  </span></h4>

                                                    <h4 class="text-primary">ADVOCATE : <span class="text-muted">{{ $clients -> Advocate_FirstName}}  {{$clients -> Advocate_LastName}} </span></h4>
                               
                                                     
                                                    <div class="form-group row">
  <div class="col-lg-8" id="reasonDropdown" style="display: none;">
    <div class="d-flex align-items-center">
      <h4 class="text-primary mr-2">REASON:</h4>
      <select class="form-control" id="val-skill" name="val-skill">
            <option value="">Please select</option>
            <option value="html">Previously Helped</option>
            <option value="css">Not Eligible</option>
        </select>
    </div>
  </div>
</div>

function submitForm() {
  $(document).ready(function() {
    $('#submitButton').click(function(e) {
      e.preventDefault();
   


      // Get the form values
      const decision = $('#decisionDropdown').val();
      const reason = $('#val-skill option:selected').text(); // Retrieve the selected option's reason text
      const caseId = $(this).data('case-id'); 
      // Perform actions with the decision and reason values
      //alert('Decision: ' + decision + '\nReason: ' + reason);

      // Prepare the data to be sent
      const formData = {
        decision: decision,
        reason: reason,
        caseID: caseId
      };

    
 
      // Perform the AJAX request
      $.ajax({
        url: '/fulfillment',
        type: 'POST',
        data: formData,
        dataType: 'json',
        headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },

        success: function(response) {
          console.log('Form submission successful:', response);
          // Perform any additional actions after successful submission
        },
        error: function(error) {
          console.error('Form submission failed dettaway:', error);
          // Handle the error or display an error message
        }
      });

    });
  });
}

 Route::post('/fulfillment', [CaseController::class, 'fulfillment'])->name('fulfillment.store');

 public function fulfillment(Request $request) {
  // if the case will be approved then the the first step is to delete the case from pending case and transfer it to fullfill case table
    echo"hello world app ";

    // get the case id  or which is the same as the pending case id

    $caseID = $request ->input('caseID');
    dd($caseID);
    }
0 likes
20 replies
Danny971's avatar

@kevinbui the route is not being triggered therefore the

fulfillment function is not running

Danny971's avatar

@kevinbui the error message i get is on the consol log which is Form submission failed dettaway

Form submission failed dettaway: Objectabort: ƒ (e)always: ƒ ()catch: ƒ (e)done: ƒ ()fail: ƒ ()getAllResponseHeaders: ƒ ()getResponseHeader: ƒ (e)overrideMimeType: ƒ (e)pipe: ƒ ()progress: ƒ ()promise: ƒ (e)readyState: 4responseJSON: {message: 'CSRF token mismatch.', exception: 'Symfony\Component\HttpKernel\Exception\HttpException', file: 'C:\xampp\htdocs\pos_cfr\vendor\laravel\framework\src\Illuminate\Foundation\Exceptions\Handler.php', line: 396, trace: Array(40)}responseText: "{\n "message": "CSRF token mismatch.",\n setRequestHeader: ƒ (e,t)state: ƒ ()status: 419statusCode: ƒ (e)statusText: "unknown status"then: ƒ (t,n,r)[[Prototype]]: Object error @ profile?family_id=87:1631

kevinbui's avatar

@Danny971 The error is CSRF token mismatch then. You might want to have a look at the docs. Do you have that meta tag in your html?

Danny971's avatar

@kevinbui so this in incorrect

// Perform the AJAX request $.ajax({ url: '/fulfillment', type: 'POST', data: formData, dataType: 'json', headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },

kevinbui's avatar

@Danny971 I believe that line is correct. Do you have the following line in your blade file/html?

<meta name="csrf-token" content="{{ csrf_token() }}">
Danny971's avatar

@kevinbui yes i do . I just updated my javascript code

function submitForm() {
  $(document).ready(function() {
    $('#submitButton').click(function(e) {
      e.preventDefault();
   


      // Get the form values
      const decision = $('#decisionDropdown').val();
      const reason = $('#val-skill option:selected').text(); // Retrieve the selected option's reason text
      const caseId = $(this).data('case-id'); 
      // Perform actions with the decision and reason values
      //alert('Decision: ' + decision + '\nReason: ' + reason);

      // Prepare the data to be sent
      const formData = {
        decision: decision,
        reason: reason,
        caseID: caseId
      };

      const csrfToken = $('meta[name="csrf-token"]').attr('content');
      const headers = {
        'X-CSRF-TOKEN': csrfToken
      };

    
 
      // Perform the AJAX request
      $.ajax({
        url: '/fulfillment',
        type: 'POST',
        data: formData,
        dataType: 'json',
        headers:headers,

        success: function(response) {
          console.log('Form submission successful:', response);
        },
        error: function(error) {
          console.error('Form submission failed dettaway:', error);
         
        }
      });

    });
  });
}

and get a new error 

profile?family_id=87:1636 Form submission failed dettaway: {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}abort: ƒ (e)always: ƒ ()catch: ƒ (e)done: ƒ ()fail: ƒ ()getAllResponseHeaders: ƒ ()getResponseHeader: ƒ (e)overrideMimeType: ƒ (e)pipe: ƒ ()progress: ƒ ()promise: ƒ (e)readyState: 4responseText: "hello world app <script> Sfdump = window.Sfdump |setRequestHeader: ƒ (e,t)state: ƒ ()status: 500statusCode: ƒ (e)statusText: "Internal Server Error"then: ƒ (t,n,r)[[Prototype]]: Object

the hello word app is in the controller. it a basic test .    echo"hello world app ";

it might be an internal server error.  there might be an issue on the server side while executing the fulfillment logic in the CaseController
kevinbui's avatar

@Danny971 Great! We have solved the CSRF token issue. Now you see this new error message because of the dd method in you controller action. Pls remove the following line and return some real data:

dd($caseID);
Danny971's avatar

@kevinbui

profile?family_id=87:1636 Form submission failed dettaway: 
{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
abort
: 
ƒ (e)
always
: 
ƒ ()
catch
: 
ƒ (e)
done
: 
ƒ ()
fail
: 
ƒ ()
getAllResponseHeaders
: 
ƒ ()
getResponseHeader
: 
ƒ (e)
overrideMimeType
: 
ƒ (e)
pipe
: 
ƒ ()
progress
: 
ƒ ()
promise
: 
ƒ (e)
readyState
: 
4
responseText
: 
"hello world app "
setRequestHeader
: 
ƒ (e,t)
state
: 
ƒ ()
status
: 
200
statusCode
: 
ƒ (e)
statusText
: 
"OK"
then
: 
ƒ (t,n,r)
[[Prototype]]
: 
Object



i also removed the dd();
Danny971's avatar

@kevinbui I did and it worked i got the following response in the browser console after removing the dd(); and echo statement . I added return 0 and got the following

submitForm called profile?family_id=87:1632 Form submission successful: 0

1 like
Danny971's avatar

@kevinbui @nolastname

now that the submit button triggers the route and excute the contoller function . any ideas why my updated function isnt working

  public function fulfillment(Request $request) {
  // if the case will be approved then the the first step is to delete the case from pending case and transfer it to fullfill case table
  
   

    $caseID = $request ->input('caseID');
    

    // Retrieve the case from the pending cases table (adjust this according to your actual pending cases table model)
    $pendingCase = pendingcases::find($caseID);
   
    if($pendingCase) {
      $fulfillmentCase = new fullfillmentcases();

      // transfer data from pending cases to fulfillment table

      $fulfillmentCase -> family_id = $pendingCase ->family_id;
      $fulfillmentCase -> firstname = $pendingCase ->firstname;
      $fulfillmentCase -> lastname  = $pendingCase ->lastname;
      $fulfillmentCase -> dateapproved = $pendingCase ->daterequested;
    
      $fulfillmentCase -> save();
    return response()->json(['message' => 'Form submission successful  ', 'PendingCase ' => $pendingCase,'Case ID :' => $caseID]);
    } else {
      return response()->json(['message' => 'Form submission failed']);
    }

  }

here is the error message 

Form submission failed dettaway:[object Object]

	error	@	profile?family_id=87:1636
c	@	gl.min.js:2
fireWith	@	gl.min.js:2
l	@	gl.min.js:2
(anonymous)	@	gl.min.js:2
load (async)		
send	@	gl.min.js:2
ajax	@	gl.min.js:2
(anonymous)	@	profile?family_id=87:1624
dispatch	@	gl.min.js:2
v.handle	@	gl.min.js:2
NoLAstNamE's avatar

@Danny971 Open your browser's dev tools. Goto the Network tab. Submit your form. Click the endpoint of that form from the Network tab logs.

And paste the response here.

Danny971's avatar

@NoLAstNamE

exception
: 
"ErrorException"
file
: 
"C:\xampp\htdocs\pos_cfr\app\Http\Controllers\CaseController.php"
line
: 
34
message
: 
"Undefined variable $fulfillmentCase "
trace
: 
[{,…}, {file: "C:\xampp\htdocs\pos_cfr\app\Http\Controllers\CaseController.php", line: 34,…},…]
NoLAstNamE's avatar

@Danny971 If you know how to read (I know you can). Go to your controller and fix that undefined variable.

Danny971's avatar
Danny971
OP
Best Answer
Level 4

@NoLAstNamE I did already . This was causing the error

$fulfillmentCase -> save(); and then I fixed it to this

$fulfillmentCase->save();

Please or to participate in this conversation.