1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Validate and submit laravel from external JavaScript file

Discussão em 'Outras Linguagens' iniciado por coder123, Novembro 4, 2024 às 17:23.

  1. coder123

    coder123 Guest

    I have a laravel project I am making a slight change to but moving from angular framework, there is some confusion I am running into when trying to validate and submit a form from external js file.

    I have 2 forms in the laravel blade folder. One form id is payment, which is the original form that collects user information. This form is what I am trying to validate and submit in the external js file. I will provide the form below.

    payment form in blade file:

    <form method="POST" id="payment" enctype="multipart/form-data">
    @if ($errors->any())
    <div class="alert alert-danger">
    <ul>
    @foreach ($errors->all() as $error)
    <li>{{ $error }}</li>
    @endforeach
    </ul>
    </div>
    @endif
    @csrf
    <div class="container">
    <div class="row">
    <div class="col-12 mb-5">
    <div class="table">
    <div class="shop-title-box">
    <h3>{{$keywords["Serving Method"] ?? __('Serving Method') }}</h3>
    </div>
    <table class="cart-table shipping-method">
    <thead class="cart-header">
    <tr>
    <th>#</th>
    <th>{{$keywords["Method"] ?? __('Method') }}</th>
    </tr>
    </thead>
    <tbody>

    @foreach ($smethods as $sm)
    <tr>
    @if(!empty($packagePermissions) && in_array($sm->name, $packagePermissions))
    <td>

    <input type="radio" name="serving_method" class="shipping-charge"
    value="{{$sm->value}}"
    @if(empty(old()) && $loop->first)
    checked
    @elseif(old('serving_method') == $sm->value)
    checked
    @endif
    data-gateways="{{$sm->gateways}}">
    </td>
    <td>
    @php
    $smname = str_replace(' ','_',$sm->name);
    @endphp

    <p class="mb-1">
    <strong>{{ $keywords[$smname] ?? __($sm->name) }}</strong></p>
    <p class="mb-0"><small>{{ __($sm->note) }}</small></p>
    </td>

    @else
    <td class="d-none">
    <input type="radio" name="serving_method" class="shipping-charge"
    value="{{$sm->value}}"
    @if(empty(old()) && $loop->first)
    checked
    @elseif(old('serving_method') == $sm->value)
    checked
    @endif
    data-gateways="{{$sm->gateways}}">
    </td>
    @endif
    </tr>
    @endforeach
    </tbody>
    </table>
    @error('serving_method')
    <p class="text-danger mb-0">{{ convertUtf8($message) }}</p>
    @enderror
    </div>
    </div>
    </div>
    <input type="hidden" name="ordered_from" value="website">
    <div class="form-container" id="home_delivery">
    @includeIf('user-front.qrmenu.partials.home_delivery_form')
    </div>
    <div class="form-container d-none" id="pick_up">
    @includeIf('user-front.qrmenu.partials.pick_up_form')
    </div>
    <div class="form-container d-none" id="on_table">
    @includeIf('user-front.qrmenu.partials.on_table_form')
    </div>
    <div class="row">
    <div class="col-12">
    <div class="field-label">{{$keywords["Order Notes"] ?? __('Order Notes') }} </div>
    <div class="field-input">
    <textarea name="order_notes" cols="30" rows="10"></textarea>
    </div>
    </div>
    </div>
    <div id="paymentInputs"></div>
    </div>
    <div class="bottom">
    <div class="container">
    <div class="row">
    <div class="col-xl-8 col-lg-8 col-md-12 col-sm-12">
    <div class="table">
    <div class="shop-title-box">
    <h3>{{$keywords["Order Summary"] ?? __('Order Summary') }}</h3>
    </div>
    @if (!empty($cart))
    <table class="cart-table">
    <thead class="cart-header">
    <tr>
    <th class="prod-column"
    width="10%">{{$keywords["Product"] ?? __('Product') }}</th>
    <th width="70%">{{$keywords["Product Title"] ?? __('Product Title') }}</th>
    <th>{{$keywords["Quantity"] ?? __('Quantity') }}</th>
    <th>{{$keywords["Total"] ?? __('Total') }}</th>
    </tr>
    </thead>
    <tbody>
    @foreach ($cart as $key => $item)
    @php
    $id = $item["id"];
    if(session()->has('user_lang')){
    $lang = App\Models\User\Language::where('code',session()->get('user_lang'))->where('user_id',getUser()->id)->first();
    }else{
    $lang = App\Models\User\Language::where('is_default',1)->where('user_id',getUser()->id)->first();
    }
    $product = Product::query()
    ->join('product_informations', 'product_informations.product_id', 'products.id')
    ->where('product_informations.language_id', $lang->id)
    ->where('products.user_id', $user->id)
    ->where('products.id', $id)
    ->first();
    @endphp
    <tr class="remove{{ $id }}">
    <td class="prod-column" width="10%">
    <div class="column-box">
    <div class="prod-thumb">
    <a
    href="{{ route('user.front.product.details', [getParam(), $product->slug, $product->product_id]) }}"
    target="_blank">
    <img class="lazy"
    data-src="{{ Uploader::getImageUrl(Constant::WEBSITE_PRODUCT_FEATURED_IMAGE,$item['photo'],$userBs) }}"
    alt="" width="100">
    </a>
    </div>
    </div>
    </td>
    <td width="70%">
    <div class="title">
    <a
    href="{{ route('user.front.product.details', [getParam(), $product->slug, $product->product_id]) }}"
    target="_blank">
    <h5 class="prod-title">
    {{ strlen($product->title) > 27 ? mb_substr($product->title, 0, 27, 'UTF-8') . '...' : $product->title }}
    </h5>
    @if (!empty($item["variations"]))

    @php
    $variations = $item['variations'];
    $prokeywords = json_decode($product->keywords, true);
    $addonkeywords = json_decode($product->addon_keywords, true);
    $sessionLang = session()->get('user_lang');

    @endphp

    <p><strong>{{$keywords["Variation"] ?? __("Variation")}}
    :</strong> <br>
    @php
    $variations = $item["variations"];
    @endphp
    @foreach ($variations as $vKey => $variation)
    @php

    $vname = $userCurrentLang->code . '_' . str_replace('_', ' ', $vKey);
    $voption = $userCurrentLang->code . '_' . $variation['name'];

    $variationName = isset($prokeywords['variation_name'][$vname]) ? $prokeywords['variation_name'][$vname] : '';
    $optionName = isset($prokeywords['option_name'][$voption]) ? $prokeywords['option_name'][$voption] : '';
    @endphp
    @if(!empty($variationName))
    <span
    class="text-capitalize font-weight-bold {{ $userCurrentLang->rtl == 1 ? 'text-right' : '' }}">{{ $variationName }}:</span>
    <span
    class="{{ $userCurrentLang->rtl == 1 ? 'text-right' : '' }}">{{ $optionName }}</span>

    @if (!$loop->last)
    <span
    class="{{ $userCurrentLang->rtl == 1 ? 'text-right' : '' }}"> ,</span>
    @endif
    @endif
    @endforeach
    </p>
    </a>
    @endif
    @if (!empty($item['addons']))
    <p>
    <strong>{{$keywords["Addons"] ?? __("Addons") }}
    :</strong>
    @php
    $addons = $item["addons"];
    @endphp
    @foreach ($addons as $addon)
    @php
    $addonkeywords = json_decode($product->addon_keywords, true);
    if (!empty($sessionLang)) {
    $aname = $sessionLang . '_' . $addon['name'];
    } else {
    $aname = $userCurrentLang->code . '_' . $addon['name'];
    }

    @endphp

    {{ $addonkeywords['addon_name'][$aname] }}
    @if (!$loop->last)
    ,
    @endif
    @endforeach
    </p>
    @endif
    </div>
    </td>
    <td class="qty">
    {{ $item['qty'] }}
    </td>
    <input type="hidden" value="{{ $id }}" class="product_id">
    <td class="sub-total">
    {{ $userBe->base_currency_symbol_position == 'left' ? $userBe->base_currency_symbol : '' }}
    {{ $item['total'] }}
    {{ $userBe->base_currency_symbol_position == 'right' ? $userBe->base_currency_symbol : '' }}
    </td>
    <script>
    window.userBe = "{{ json_encode($userBe) }}";
    </script>
    </tr>

    @endforeach
    @else
    <div class="py-5 bg-light text-center">
    <h5>{{$keywords["Cart is empty"] ?? __('Cart is empty!') }}</h5>
    </div>
    @endif
    </tbody>
    </table>
    <div class="text-center my-4">
    <a href="{{ route('user.front.index',getParam()) }}"
    class="main-btn main-btn-2">{{$keywords["Return to Website"] ?? __('Return to Website') }}</a>
    </div>
    </div>
    </div>
    <div class="col-xl-4 col-lg-4 col-md-12 col-sm-12">
    @includeIf('user-front.qrmenu.partials.order_total')
    </div>
    </div>
    </div>
    </div>
    </form>


    I also have another clover payment form that has and iframe for payment. This form uses the html used here and references the form submission and processing is managed in an external js file names clover-checkout.js which is:

    $.ajax({
    url: "http://localhost:4000/api/cloverPay/getapikey",
    type: "GET",
    headers: {
    'Access-Control-Allow-Origin': '*',
    'Content-Type': 'application/json',
    'Authorization': 'Bearer JSON.parse(window.userBe.replace(/&quot;/g,'"')).token
    },
    success: function (result) {
    setupCloverIframe(result.pakms);
    },
    error:function(data)
    {
    console.log('error ', data);
    }
    });
    function setupCloverIframe(pakms) {
    const clover = new Clover(pakms.apiAccessKey, {
    merchantId: pakms.merchantId
    });
    const elements = clover.elements();
    const styles = {
    body: {
    fontFamily: 'Roboto, Open Sans, sans-serif',
    fontSize: '16px',
    },
    input: {
    fontSize: '16px',
    width: '80%',
    },
    };
    const cardNumber = elements.create('CARD_NUMBER', styles);
    const cardDate = elements.create('CARD_DATE', styles);
    const cardCvv = elements.create('CARD_CVV', styles);
    const cardPostalCode = elements.create('CARD_POSTAL_CODE', styles);

    cardNumber.mount('#card-number');
    cardDate.mount('#card-date');
    cardCvv.mount('#card-cvv');
    cardPostalCode.mount('#card-postal-code');

    const cardResponse = document.getElementById('card-response');

    const displayCardNumberError = document.getElementById('card-number-errors');
    const displayCardDateError = document.getElementById('card-date-errors');
    const displayCardCvvError = document.getElementById('card-cvv-errors');
    const displayCardPostalCodeError = document.getElementById('card-postal-code-errors');

    // Handle real-time validation errors from the card Element.
    cardNumber.addEventListener('change', function (event) {
    console.log(`cardNumber changed ${JSON.stringify(event)}`);
    });

    cardNumber.addEventListener('blur', function (event) {
    console.log(`cardNumber blur ${JSON.stringify(event)}`);
    });

    cardDate.addEventListener('change', function (event) {
    console.log(`cardDate changed ${JSON.stringify(event)}`);
    });

    cardDate.addEventListener('blur', function (event) {
    console.log(`cardDate blur ${JSON.stringify(event)}`);
    });

    cardCvv.addEventListener('change', function (event) {
    console.log(`cardCvv changed ${JSON.stringify(event)}`);
    });

    cardCvv.addEventListener('blur', function (event) {
    console.log(`cardCvv blur ${JSON.stringify(event)}`);
    });

    cardPostalCode.addEventListener('change', function (event) {
    console.log(`cardPostalCode changed ${JSON.stringify(event)}`);
    });

    cardPostalCode.addEventListener('blur', function (event) {
    console.log(`cardPostalCode blur ${JSON.stringify(event)}`);
    });

    // TODO: Register event handlers
    const form = document.getElementById('payment-form');
    form.addEventListener('submit', function (event) {
    event.preventDefault();

    clover.createToken()
    .then(function (result) {
    if (result.errors) {
    Object.values(result.errors).forEach(function (value) {
    console.log(value);
    });
    } else {
    let un = window.location.pathname.split('/')[1];

    $.post('/dinengo/processOrderAndPayment/' + result.token + '/' + un, function (response) {
    // handle your response here
    $('#payment')[0].submit();
    alert("result.token");
    });
    }
    }).catch(function (data) {
    console.log(data);
    });
    });

    const paymentReqData = {
    country: 'US',
    currency: 'usd',
    total: {
    label: 'Demo total',
    amount: 1099,
    },
    requestPayerName: true,
    requestPayerEmail: true,
    };

    const paymentRequest = clover.paymentRequest(paymentReqData);
    const paymentRequestButton = elements.create('PAYMENT_REQUEST_BUTTON', {
    paymentReqData
    });
    // Check the availability of the Payment Request API first.
    paymentRequest.canMakePayment().then(function (result) {
    if (result) {
    paymentRequestButton.mount('#payment-request-button');
    } else {
    document.getElementById('payment-request-button').style.display = 'none';
    }
    });
    paymentRequestButton.addEventListener('paymentMethod', function (ev) {
    alert(JSON.stringify(ev));
    })

    // Submit the form with the token ID.
    function cloverTokenHandler(token) {
    // Insert the token ID into the form so it gets submitted to the server
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'cloverToken');
    hiddenInput.setAttribute('value', token);
    form.appendChild(hiddenInput);
    alert(token);
    // Submit the form
    // form.submit();
    }

    function processCloverIframPayment(event) {
    event.preventDefault();
    debugger;
    console.log('in button click ', event);

    clover.createToken()
    .then(function (result) {
    if (result.errors) {
    Object.values(result.errors).forEach(function (value) {
    console.log(value);
    });
    } else {
    debugger;
    let un = window.location.pathname.split('/')[1];

    $.post('/dinengo/processOrderAndPayment/' + result.token + '/' + un, function (response) {
    // handle your response here
    //alert(result.token);
    $('#payment').submit();
    });
    }
    }).catch(function (data) {
    console.log(data);
    });
    }

    }



    There are a couple things I am trying to accomplish but an running into trouble. Firstly, I want to have it so that in the external js, it validates that the form with id 'payment' has no errors before processing the form with id "payment-form". Once that payment-form is completed, then I want to submit and process the form with id payment which is the original laravel form.

    Although I can click the form payment from the external js, I need a way to first validate that the payment form is valid, process payment, then successfully submit the laravel payment form.

    Note: currently, when $('#payment').submit(); is called, it returns and error I believe due to it not having context anymore. Can someone help me resolve this issue as well as understand the cause and solution.

    Also, The error handling should be intact. If an error exists, it should set that error as it did previously when submitting the form.

    Continue reading...

Compartilhe esta Página