Debug School

rakesh kumar
rakesh kumar

Posted on

How to perform store and update form data using same form in jquery

step1: create a button in html

<button type="button"  class="btn btn-sm btn-secondary report-button" data-id="{{$data->id}}">
  Status
 </button>
Enter fullscreen mode Exit fullscreen mode

step2: when i click button i call ajax route and fetch the data from server side

$('.report-button').click(function() {
                var paymentId = $(this).data('id');            
                $('#influencer_result').html('');

                $.ajax({
                type: 'GET', // You can adjust the HTTP method as needed
                url: "{{ route('report-task', ['id' => ':paymentId']) }}".replace(':paymentId', paymentId),
Enter fullscreen mode Exit fullscreen mode

step3: my laravel route

Route::get('report-task/{id}', [App\Http\Controllers\Admin\PaymentController::class, 'reportstatus'])->name('report-task');
Enter fullscreen mode Exit fullscreen mode

step4: fetching a data from database and send response in json to client side in laravel controller function

  public static function reportstatus($id)
    {
        $task = new sharedata();
        $approvetask = $task->get_task($id);
        $influencer_email = null;
        $influencer_name = null;
        $Paytm = new Paytm();
        $Paytmdata = $Paytm->get_paytm();
        log::info($Paytmdata);
        $admin_id = $approvetask->admin_id;
        $payment_id = $approvetask->payment_id;
        log::info("approvetask aata hain");
        log::info($id);
        log::info($admin_id);
        log::info($approvetask);

        foreach ($Paytmdata as $key => $value) {
            if ($value['id'] == $payment_id) {
                $influencer_email = $value['influencer_email'];
            }

        }
        foreach ($Paytmdata as $key => $value) {
            if ($value['id'] == $payment_id) {
                $influencer_name = $value['influencer_name'];
            }

        }
        log::info($influencer_email);
        return response()->json([
            'approvetask' => $approvetask,
            'influencer_email' => $influencer_email,
            'influencer_name' => $influencer_name,
        ]);

    }
Enter fullscreen mode Exit fullscreen mode

step5: after getting json data from server side if data already filled at least one time, in client side get the value and set data form element input type and dropdown

$('.report-button').click(function() {
                var paymentId = $(this).data('id');            
                $('#influencer_result').html('');

                $.ajax({
                type: 'GET', // You can adjust the HTTP method as needed
                url: "{{ route('report-task', ['id' => ':paymentId']) }}".replace(':paymentId', paymentId),
               success: function(data)
                 {
                console.log('view-button ka data aata hain');
                    var approvetask = data.approvetask;
                    var infl_email = data.influencer_email;
                    var infl_admin = data.influencer_admin_id;
                    var status = data.approvetask.status;
                    console.log('approvetask:', approvetask);
                    console.log('infl_email:', infl_email);
                    var task_id = data.approvetask.id;
                    var admin_id = data.approvetask.admin_id;
                    var user_name = data.approvetask.user_name;
                    var work_url = data.approvetask.work_url ? data.approvetask.work_url : "";
                    var work_desc = data.approvetask.work_desc ? data.approvetask.work_desc : "";
                    var share_id = data.approvetask.id;
                    var influencer_email = data.approvetask.influencer_email;
                    var payment_id = data.approvetask.payment_id;
                    console.log('task_id:', task_id);
                    console.log('user_name:', user_name);
                    // var emailString = infl_email.join(',');
                    // var emailStringadmin = infl_admin.join(',');
                    $('#work_url').val(work_url);
                    $('#write_up').val(work_desc);
                    $('#influencer_email').val(infl_email);
                    $('#status').val(status);
                    $('#influencer_admin_id').val(infl_admin);
                    $('#payment_id').val(payment_id);
                    $('#share_id').val(share_id);
                    console.log('status:', status);
                    if (status === 'not approved') {
                        $('.form-horizontal').css('height', '150px');
                        $('#approves-data').modal('show');
                $('#urlinfluencertask').html(`
                   <option value="" class="form-control text-dark">Select status</option>
                   <option value="Todo">Todo</option>
                    <option value="Approve">Approve</option>
                    <option value="Reject">Reject</option>
                    <option value="completed">completed</option>
                    <option value="InProgress">In Progress</option>
                    <option value="onhold">onhold</option>
                `);

            } else if (status === 'Approve') {
                $('.form-horizontal').css('height', '150px');
                $('#approves-data').modal('show');
                $('#urlinfluencertask').html(`              
                   <option value="completed">completed</option>
                    <option value="InProgress">In Progress</option>

                `);               
                   }

                else if (status === 'Reject') {
                    $('#rejects-data').modal('show');

                }
                else if (status === 'completed') {
                    $('.form-horizontal').css('height', '300px');
                    $('#approves-data').modal('show');
                    $('#urlFields').show();
                    $('#urlinfluencertask').html(`
                    <option value="completed">completed</option>
                    <option value="InProgress">In Progress</option>


                `);

                }
                else if (status === 'InProgress') {
                    $('.form-horizontal').css('height', '300px');
                    $('#approves-data').modal('show');
                    $('#urlFields').show();
                    $('#urlinfluencertask').html(`

                    <option value="completed">completed</option>

                    `);


                }else if (status === 'onhold') {
                    $('.form-horizontal').css('height', '150px');
                    $('#approves-data').modal('show');
                    $('#urlinfluencertask').html(`
                    <option value="Approve">Approve</option>
                    <option value="InProgress">In Progress</option>
                    <option value="completed">completed</option>

                    `);       
                }
                else {
                    $('.form-horizontal').css('height', '150px');
                    $('#approves-data').modal('show');
                $('#urlinfluencertask').html(`

                   <option value="" class="form-control text-dark">Select status</option>
                   <option value="Todo">Todo</option>
                    <option value="Approve">Approve</option>
                    <option value="Reject">Reject</option>
                    <option value="completed">completed</option>
                    <option value="InProgress">In Progress</option>
                    <option value="onhold">onhold</option>

                `);

                }


                       },
      error: function(error) {
        // Handle any errors that occur during the AJAX request
        console.log('Error:', error);
      }
    });
  });
Enter fullscreen mode Exit fullscreen mode

step7: display the data if it has data is there in database other wise show empty data

 <form method="post" id="task_form" style="margin-left:-30px;" class="form-horizontal" enctype="multipart/form-data">
                                            @csrf

                                            <div  class="form-group">
                                                <h4>Status</h4>
                                                <label class="control-label ">Status</label>                                                
                                                    <select name="urlinfluencertask"   id="urlinfluencertask" class="w-100 p-2">

                                                    </select>
                                            </div>

                                            <div class="form-group" id="urlFields">
                            <span id="urlErrorMessage" class="text-danger"></span>
                            <label for="video_upload" class="control-label" style="color: black;" required>Work Link :</label>
                            <input type="text" name="video_upload" id="video_upload" class="form-control" value="" placeholder="" required>    
                            <label for="text_area" class="control-label" style="color: black;">Description :</label>
                            <textarea  id="write_up" name="write_up" id="write_up" rows="4" cols="4"  class="form-control" placeholder="" required></textarea>
                                                </div>                                         
                                            <!-- Sending admin_id and admin_email in hidden input box -->
                                            <input type="hidden" value="{{ Auth::user()->id }}" name="admin_id" id="admin_id" />
                                            <input type="hidden" value="{{ Auth::user()->email }}" id="admin_email" name="admin_email" />
                                            <input type="hidden"  name="influencer_email" id="influencer_email">
                                       <input type="hidden"  name="influencer_admin_id" id="influencer_admin_id">
                                       <input type="hidden" name="action" id="action" />
                                        <input type="hidden" name="hidden_id" id="hidden_id" />
                                        <input type="hidden" name="share_id" id="share_id" />

                                        <button type="submit" name="action_button" id="action_button" class="btn btn-sm py-1 btn-primary me-2" value="Add">Submit</button>
                                    <input type="hidden"  name="payment_id" id="payment_id">
                                    </div>                                  
                                    </form>
                                </div>                                
                            </div>
                        </div>
                    </div>
Enter fullscreen mode Exit fullscreen mode

first time for create operation

 var work_url = data.approvetask.work_url ? data.approvetask.work_url : "";
var work_desc = data.approvetask.work_desc ? data.approvetask.work_desc : "";
Enter fullscreen mode Exit fullscreen mode

Image description

update operation
Image description

step8: if we fill first time data then we perform store operation otherwise we perform update operation

$('#task_form').on('submit', function(event) {
      event.preventDefault();
      var url = $('#video_upload').val();

        // Regular expression to check if the URL starts with http:// or https://
     // Get the selected value from #urlinfluencertask
     var formData = new FormData(this);
formData.append('_token', $('meta[name="csrf-token"]').attr('content'));
     var selectedValue = $('#urlinfluencertask').val();
console.log('Selected Value:', selectedValue);

      if ($('#action_button').val() == 'Add') {
        console.log('add button click ho rha ha');
        $.ajax({
            url: "{{ url('sharemytask/store') }}",
          method: "POST",
          data: new FormData(this),
          contentType: false,
          cache: false,
          processData: false,
          dataType: "json",
          headers: {
            "Authorization": "Bearer " + localStorage.getItem('a_u_a_b_t')
          },
          beforeSend: function() {
            if (!$('#image_uploads').val()) {
              $('#img-error').text("Please Fill Required Field Again");
            }
          },

          success: function(data) {
            // Handle the response from the server
            console.log(data);
            var html = '';
            if (data.success) {
              html = '<div class="alert alert-success"style="padding-top:4pt;padding-bottom:4pt;">' + 'share data stored successfully' +
                '</div>';
              $('#sample_form').html(html);
              // sample_form.reset();            
              var influencer=data.influencer;
              var publisher=data.publisher;              
              var influencer_status=data.influencer_status;              
              if (influencer_status !== "completed") 
              {                
                $('#approves-data').modal('hide');
                $('#task-submit').modal('show');
                $('#influ_status').html(`
            <h5 class="text-center" style="margin: 0; color: red;">
                Influencer (${influencer}) has successfully assigned the status (${influencer_status}) to publisher (${publisher}) . Please login  in the publisher (${publisher}).
            </h5>
            `);
              }
              else
              {
                var work_url = data.work_url;
var maxCharacters = 50; // Set your desired maximum number of characters

// Limit the length of the work_url variable
var limitedWorkUrl = work_url.length > maxCharacters ? work_url.substring(0, maxCharacters) + '...' : work_url;

                var work_desc=data.work_desc;
                console.log(work_url)
                console.log(work_desc)
                $('#approves-data').modal('hide');
                $('#task-submit').modal('show');
                var existingContent = `
                    <h5 class="text-center" style="margin: 0; color: red;">
                        Influencer( ${influencer}) has successfully assigned the status( ${influencer_status} )to publisher (${publisher}). Please login in the publisher (${publisher}).
                    </h5>
                    <p>Work URL: ${limitedWorkUrl}</p>
                    <p>Description: ${work_desc}</p>
                `;

// Append a new paragraph

                $('#influ_status').html(existingContent);

              }


            } else if (data.success) {
              html = '<div class="alert alert-success">' + 'Update Successfully' +
                '</div>';
              $('#sample_form').html(html);
              console.log("")
              // sample_form.reset();
              setTimeout(function() {
                // $('#addPriceModal').modal('hide');
                // $('#priceTable').DataTable().ajax.reload();
                location.reload(true);
              }, 2000);
            } else {
              html = '<div class="alert alert-danger">' + 'Share Data UnSuccessfully' +
                '</div>';
              $('#sample_form').html(html);
            }
          },
          error: function(xhr, status, error) {
            console.log(error);
          }
        });

      };
    })
Enter fullscreen mode Exit fullscreen mode

step9: store or update data through same controller function

  public function sharedataupdate(Request $request)
    {
        Log::info('Inside sharedataupdate method');
        Log::info($request);
        $input = $request->all();
        $path = $request['image_upload'] !== null ? time() . '-' . $request['image_upload']->getClientOriginalName() : null;
        $request['image_upload'] !== null ? $request['image_upload']->move(base_path() . '/storage/app/public/images', $path) : null;
        $video= $request['video_upload'];
        $taskid=$request['task_id'];

  $sharemytask= DB::connection('payments')->table("sharedatas")->where('id',$taskid)->update(array('Video_link' =>$video,'image_link' => $path));

  $data= DB::connection('payments')->table("sharedatas")->where('id',$taskid)->first();
  $influencer_mail=$data->influencer_email;
  $data_profile= DB::table("addprofiles")->where('user_email',$influencer_mail)->first();
  $influencer_name=$data_profile->user_name;
  return response()->json([
                       'message' => "task disapprove successfully", 
                       'success' => "task disapprove successfully", 
                       'publisher' => $request['user_name'], 
                       'influencer' => $influencer_name, 
                   ]);

    }
Enter fullscreen mode Exit fullscreen mode

==================================================

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Store and Update Form</title>
    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

<form id="profileForm">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">

    <label for="email">Email:</label>
    <input type="text" id="email" name="email">

    <!-- Hidden input to store the ID -->
    <input type="hidden" id="dataitem_id" name="dataitem_id" value="">

    <!-- Hidden input to store the action type (Add or Update) -->
    <input type="hidden" id="action_add_profile_button" name="action_add_profile_button" value="Add">

    <!-- Submit button for the form -->
    <button type="submit" id="submitBtn">Submit</button>
</form>

<!-- Manage button outside the form -->
<button type="button" id="manageBtn" data-id="your_id">Manage</button>

<script>
    $(document).ready(function () {
        // Function to check if data exists based on the provided ID
        function checkIfDataExists(dataItemId) {
            // Simulated AJAX request (replace with your actual implementation)
            return $.ajax({
                url: '/path/to/your/server/endpoint',
                type: 'GET',
                data: { id: dataItemId },
                dataType: 'json'
            });
        }

        // Click event for the "Manage" button
        $('#manageBtn').on('click', function () {
            // Get the ID from the data attribute
            var dataItemId = $(this).data('id');

            // Set the ID in the hidden input field
            $('#dataitem_id').val(dataItemId);

            // Check if data exists for the provided ID
            checkIfDataExists(dataItemId)
                .done(function (response) {
                    // Check the response from the server
                    if (response.exists) {
                        // Existing data - simulate with some values
                        var existingName = "John Doe";
                        var existingEmail = "john@example.com";

                        // Set form fields with existing data
                        $('#name').val(existingName);
                        $('#email').val(existingEmail);
                        $('#action_add_profile_button').val("Update");
                    } else {
                        // No existing data
                        // Clear form fields for a new entry
                        $('#name').val('');
                        $('#email').val('');
                        $('#action_add_profile_button').val("Add");
                    }
                })
                .fail(function (error) {
                    // Handle AJAX error
                    console.error("AJAX request failed:", error);
                });
        });

        // Form submission
        $('#profileForm').on('submit', function (event) {
            event.preventDefault();

            // Get form data
            var formData = $(this).serialize();

            // Check if it's an update or add operation
            if ($('#action_add_profile_button').val() === "Update") {
                // Perform update logic (you can replace this with your own logic)
                console.log("Performing update:", formData);
            } else {
                // Perform add logic (you can replace this with your own logic)
                console.log("Performing add:", formData);
            }
        });
    });
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)