Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

how to submit form using ajax and Jquery in laravel

To submit a form using Ajax in Laravel, follow the steps below:

Step 1: Create a Form
Create a form in your Laravel application using the standard HTML form syntax, but include a CSRF token field to protect against cross-site request forgery attacks. For example:

<form id="myForm" action="{{ route('submit_form') }}" method="POST">
    @csrf
    <input type="text" name="name" />
    <input type="email" name="email" />
    <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Image description

Step 2: Add jQuery Library
Add the jQuery library to your Laravel application. You can include it via a CDN or by downloading the library and including it in your application.

Step 3: Write Ajax Code
In your view file, write the Ajax code to submit the form data. This code will be triggered when the user clicks the submit button. For example:

<script>
    $(document).ready(function() {
        $('#myForm').submit(function(e) {
            e.preventDefault();
            $.ajax({
                type: "POST",
                url: "{{ route('submit_form') }}",
                data: $('#myForm').serialize(),
                success: function(response) {
                    alert(response.message);
                },
                error: function(response) {
                    alert(response.responseJSON.message);
                }
            });
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

Image description

In this code, we are using jQuery to bind the submit event to the form. We are then preventing the default form submission behavior using e.preventDefault(). We then use the $.ajax() function to send a POST request to the server with the form data. We pass in the URL to the Laravel route that will handle the form submission, and we serialize the form data using $('#myForm').serialize(). We also provide a success callback function and an error callback function to handle the server response.

Step 4: Handle Form Submission in Controller
In your Laravel controller, handle the form submission by validating the form data and performing any necessary actions. For example:

public function submitForm(Request $request)
{
    $validatedData = $request->validate([
        'name' => 'required',
        'email' => 'required|email',
    ]);

    // Perform necessary actions with the form data

    return response()->json([
        'message' => 'Form submitted successfully!'
    ]);
}
Enter fullscreen mode Exit fullscreen mode

Image description

In this code, we are using Laravel's built-in validation to ensure that the name and email fields are not empty and that the email field contains a valid email address. We then perform any necessary actions with the form data, such as saving it to a database. Finally, we return a JSON response with a success message.

That's it! With these steps, you should now be able to submit a form using Ajax in Laravel.

in html form
Image description
in jquery and ajax

 $('#mykeyForm').submit(function(e) {

            $.ajax({
                type: "POST",
                url: "{{ route('webtoken.store') }}",
                data: $('#mykeyForm').serialize(),

                success: function(response) {
                    console.log("mykeyForm success hoga"); 
                    if(response.message=='notunique')
                    {
                        $('#unpublish_Modal').modal('show');

                    }

                },
                error: function(response) {
                    console.log("mykeyForm error  hoga"); 
                    alert(response.responseJSON.message);
                }
            });
        });
Enter fullscreen mode Exit fullscreen mode

in route

Route::post('webtoken/store', [App\Http\Controllers\Api\WebAccessApiController::class, 'storeWebToken'])->name('webtoken.store');

Enter fullscreen mode Exit fullscreen mode

in laravel

 public function storeWebToken(Request $request)
    {
        $key_pair = openssl_pkey_new(array(
            'private_key_bits' => 1024,
            'private_key_type' => OPENSSL_KEYTYPE_RSA,
          ));      
          // Get the private key string
          openssl_pkey_export($key_pair, $private_key);      
          // Get the public key string
          $public_key = openssl_pkey_get_details($key_pair);
          $public_key = $public_key["key"];      
          // Use the private key to sign some data
          $encoded_public_key = base64_encode($public_key);
          $email = $request->input('email_address');
          $admin_id = $request->input('admin_id');
          $currentDate = Carbon::now()->toDateString();
          $key = Str::random(10);
          $admin_email = $request->input('admin_email');
          $u_org_slugname = $request->input('u_org_slugname');
          $u_org_organization_id = $request->input('u_org_organization_id');
          $u_org_role_id = $request->input('u_org_role_id');
          $input = $request->all();
             log::info("yanha daya axfs");
            log::info($input);
            $merge =  $email.'.pem';
            $merge1 =  $email.'privatekey'.'.pem';
            $newkey='key'.$key;
           $mywebtoken= Mywebaccesstoken::where('u_org_organization_id',$u_org_organization_id)->where('token',$merge)->first();
             if(!$mywebtoken){
            log::info("else yanha daya axfs");
            $myModel = new Mywebaccesstoken;
            $myModel->token = $merge;
            $myModel->admin_id = $admin_id;
            $myModel->keydate = $currentDate;
            $myModel->keyid = $newkey;
            $myModel->pubkey = $encoded_public_key;
            $myModel->keydate =   $currentDate;             
            $myModel->admin_email = $admin_email;
            $myModel->u_org_slugname = $u_org_slugname;
            $myModel->u_org_organization_id = $u_org_organization_id;
            $myModel->u_org_role_id = $u_org_role_id;   

            $myModel->save();                
                $data = "Hello, world!";
                openssl_sign($data, $signature, $private_key, OPENSSL_ALGO_SHA256);      
            $validToken = sha1(time()) . rand();
            $privatekey = array(
              'admin_id' => $admin_id,
              'email' => $admin_email,
              'token' => $merge,  
              'private_key' => $private_key,        
            );
            $file = 'oldkey.pem';
            file_put_contents($file, $private_key);
            file_put_contents($merge1, $private_key);
            $to = $admin_email;
            $subject = 'PrivateKey';
            $from = 'contact@wizbrand.com';
            $attachmentName = $merge1;
            log::info("yanha yanha daya axfs");
            Mail::send([], [], function ($message) use ($to, $subject, $from, $file, $attachmentName) {
                $message->to($to)
                    ->subject($subject)
                    ->from($from)
                    ->attach($file, ['as' => $attachmentName]);
            });
            Mail::to($privatekey['email'])->send(new privatekey($privatekey, $validToken)); 
            $result = openssl_verify($data, $signature, $public_key, OPENSSL_ALGO_SHA256);

            // download function start here
            ob_clean();
            $file = storage_path('app/private_key.pem');
            log::info("baad yanha daya axfs");
            // Download the file
            return response()->download($file, $merge1, [
                'Content-Type' => 'application/octet-stream',
                'Content-Disposition' => 'attachment',
            ]);
            log::info("last yanha daya axfs");
            header('Content-Description: File Transfer');
            header('Content-Type: application/x-pem-file');
            header("Content-Disposition: attachment; filename=public.pem");
            exit(readfile('privatekey.pem'));  
                // Download the file
                $data = [
                  'mytoken_engineer' => $merge,  'date' => $currentDate
              ];       

              return response()->json([
                'message' => 'Form submitted successfully!',
                'mytoken_engineer' => $merge,
                'date' => $currentDate
            ]);

        }

        else{

            return response()->json([
                'message' => 'notunique',

            ]); 
        }

    }
Enter fullscreen mode Exit fullscreen mode

Another Methods

send the data to controller using ajax and jquery without form action

html code

 @foreach($paginator as $item)

            <div class="col-md-12 col-lg-12">
                <div class="card" style="padding: 27px;">
                    <div class="card-body">
                        <div class="imageDiv">
                            @if($item->file_pic == NULL)
                            <img style="overflow: hidden;" src="{{url('assets/images/users/default.png')}}" width="75" height="75">
                            @else
                            <img src="/storage/images/{{ $item->file_pic }}" width="75" height="75" alt="">
                            @endif
                        </div>
                        <!-- style="border-radius: 50%;" -->
                        <div class="link">
                            <h4><a href="{{ url('influencer/'.$item->slug) }}" target="_blank">{{ $item->user_name }}</a></h4>
                        </div>
                        <div class="bio" style="margin-left:-70px">
                            @if(!empty($item->digital_marketer))
                            <span>{{$item->digital_marketer}},</span>
                            @else
                            <span>Web Developer,</span>
                            @endif
                            <span>{{$item->city_name}},</span>
                            <span>{{$item->state_name}}</span>
                        </div>
                        <div class="rating" style="margin-left:-85px">
                            <span>{{$item->country_name}}</span>
                        </div>
                        <div class="social">
                            <div class="row">
                                @php $count = 0; @endphp
                                @foreach ([
                                'facebook', 'twitter', 'instagram', 'linkedin', 'youtube',
                                'wordpress', 'tumblr', 'quora', 'pinterest', 'reddit',
                                'telegram', 'fb_grp', 'linkedin_grp', 'koo', 'scoopit',
                                'slashdot', 'roposo', 'chingari', 'mitron'
                                ] as $socialMedia)
                                @if(!empty($item->$socialMedia))
                                @if ($count % 5 == 0 && $count > 0)
                            </div>
                            <div class="row">
                                @endif
                                @php $count++; @endphp
                                <a href="{{$item->$socialMedia}}" target="_blank">
                                    @if (in_array($socialMedia, ['koo', 'scoopit', 'slashdot', 'roposo', 'chingari', 'mitron','fb_grp','linkedin_grp','telegram']))
                                    <!-- Check for specific icons -->

                                    @else
                                    <!-- Use the specified colors for these icons -->
                                    <i class="fab fa-{{ $socialMedia }}" style="color:
                                    @if ($socialMedia == 'instagram') rgb(221, 42, 123);
                                    @elseif ($socialMedia == 'youtube') red;
                                    @elseif ($socialMedia == 'wordpress') black;
                                    @elseif ($socialMedia == 'tumblr') #9900e6;
                                    @elseif ($socialMedia == 'quora') #990000;
                                    @elseif ($socialMedia == 'pinterest') red;
                                    @elseif ($socialMedia == 'reddit') #ff6600;
                                    @elseif ($socialMedia == 'telegram') blue;
                                    @elseif ($socialMedia == 'fb_grp') blue;
                                    @elseif ($socialMedia == 'linkedin_grp') blue;
                                    @endif
                                 "></i>
                                    @endif
                                </a>
                                @endif
                                @endforeach
                            </div>
                        </div>                        
                             <input type="hidden" value="{{ Auth::user()->id }}" name="admin_id" id="admin_id" />                   
                            <input type="hidden" value="{{ $item->user_name }}" name="slug" id="slug" />
                            <input type="hidden" value="{{ $item->user_email }}" name="influencer_email"
                                id="influencer_email" />
                            <input type="hidden" value="{{ Auth::user()->email }}" name="admin_email" id="admin_email">
                            <input type="hidden" value="{{ Auth::user()->name }}" name="user_name">
                            <input type="text" value="{{ $item->id }}" name="item"  id="item">
                            <button type="submit"  
                             class="btn btn-sm  btn-primary addToCartBtn" data-item-id="{{ $item->id }}"  style="position: relative;float:right">Add To Cart</button> 
                    </div>
                </div>
            </div>
            @endforeach
Enter fullscreen mode Exit fullscreen mode

Ajax and Jquery Code

 $('.addToCartBtn').on('click', function() {
        event.preventDefault();
     console.log('add carting button click ho rha ha');    
       console.log('add button click ho rha ha');

        console.log('add carting button click ho rha ha');
        var admin_id = $('#admin_id').val();
            var slug = $('#slug').val();
            var influencer_email = $('#influencer_email').val();
            var admin_email = $('#admin_email').val();
            var user_name = $('[name="user_name"]').val();
            var item_id = $('#item').val();
            console.log(item_id);
            var formData = new FormData();
            formData.append('admin_id', admin_id);
            formData.append('slug', slug);
            formData.append('influencer_email', influencer_email);
            formData.append('admin_email', admin_email);
            formData.append('user_name', user_name);
            formData.append('item_id', item_id);
       $.ajax({
         url: "{{route('addcarts.store') }}",
         method: "POST",
         data: formData,
         contentType: false,
         cache: false,
         processData: false,
         dataType: 'json', // Specify the expected data type
         headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') // Add CSRF token if needed
    },
         beforeSend: function() {          

         },
         success: function(data) {
           // Handle the response from the server
           console.log(data);
           var html = '';
           if (data.success) {         
            console.log('add success success click ho rha ha');
            $('#approve-modal').modal('show');
           }
           else 
           {

           }
         },
         error: function(xhr, status, error) {           
           console.log(error);
         }
       });     
   })
Enter fullscreen mode Exit fullscreen mode

In controller

public function addcarts(Request $request)
    {
        Log::info('In addcarts store');
        Log::info('Data received via AJAX:', $request->all());
        $itemId = $request->input('item_id');
            Log::info($itemId);
            $input = $request->all();
            $cartID = null;
            $admins_id= $request->admin_id;
            $addcart= addcart::where('admin_id', $admins_id)
            ->orderBy('created_at', 'desc') // Order by 'created_at' column in descending order
            ->get();           
           if(!$addcart->isEmpty())
           {
            $carts_id =$addcart->pluck('cart_id')->toArray();
            $pays=  Paytm::where('cart_id', $carts_id[0])->where('admin_id',$admins_id)->get();
            if (!$pays->isEmpty())
             {
                $cartsID = 'CART-' . Str::random(4);    
                $cartID = $cartsID. '-' . $admins_id;                  
            }
            else{
                $addcarts_id =$addcart->pluck('cart_id')->toArray();
                $cartID = $addcarts_id[0];
            }
           }
            else{
                Log::info("last cart id hain na"); 
                $cartsID = 'CART-' . Str::random(4);    
                $cartID = $cartsID. '-' . $admins_id;

            }

            return response()->json([
                'message' => "task disapprove successfully", 
                'success' => true,
            ]);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)