Sbelvadi's avatar

Laravel, Jquery, AJAX: How to return view on a Get request

Am new to Laravel, JQuery, Ajax. My requirement is the below: Based on a selected Customer and Purchase Order in the Invoice index.blade , when the User clicks on Add Invoice button, the Invoice create.blade.php view should be rendered pre-populated with the Customer ID and Purchase Order Nbr that was selected in the 'index.blade.php` to the User.

Issue: The response view is not rendered.

Code components/snippets I have so far:

Invoice - index blade
@extends('layouts.crudMaster')
@section('crud.breadcrumb')
    {!! Breadcrumbs::render('invoice') !!}
@stop

@section('crud.header')
    <div class="row">
        <div class="col-md-10">
            <h1>Invoice</h1>
        </div>
        <div class="col-md-2">
            {{--<a href="{{ route('invoice.create', '') }}" class="btn btn-md btn-block btn-primary my-btn-h1-allign ">
                <i class="fa fa-plus"></i> Add Invoice</a>--}}
            <button id="addNewInvoiceBtn" class="btn btn-md btn-block btn-primary my-btn-h1-allign "> Add Invoice</button>
        </div>
    </div>
@stop

Java script:

$('#addNewInvoiceBtn').on('click', function () {
        //e.preventDefault();
        var $custId = $('#selectCustomerForPOSelectList').val();
        var $poId = $('#purchaseOrderSelectItems').val();
        //alert("Customer ID: " +$customerId+ " po id: " +$purchaseOrderId );
        $.get('customer/' + $custId + '/purchase_order/'+ $poId + '/invoice/create', function (data) {
            //TODO - how do we show the response data
        });
    });

Routes.php:

Route::get('customer/{customer}/purchase_order/{purchase_order}/invoice/create', 'InvoiceController@createInvoiceByCustPO')
        ->name('customer.po.invoice.create');

InvoiceController.php

 public function createInvoiceByCustPO(Request $request, $custId, $poId )
    {
        /*$input = $request->all();
        dd($input);*/
        $customerId = $custId;
        $purchaseOrderId = $poId;
        Log::info('New: Create Invoice for user: ' . $customerId . ' and PO ID: ' . $purchaseOrderId);

       //Q: Can i return the view like this or do i need the $request->ajax() check here
            return view('data_entry.invoice.create')->with('companyCode', 'Qualitech Industries')
                ->with('customerName', $customerId)
                ->with('purchaseOrder', $purchaseOrderId);
        }

    }

I verified the below while debugging

  • The ajax call in the java script is invoking the appropriate route with the selected customer id and po id
  • the response from the return view - when i use the console.log(data) in the jquery ajax function closure logs the HTML string equivalent of the view - however the values of customer id/name and po id are not passed back in the HTML response string.

q's:

  1. Should I be using an AJAX Get in this case since the response would be shown in a Create view instead of the Index view?
  2. If I should not be using the AJAX call for the Add New Invoice, How should I go about capturing the values selected in the index.blade and setup up the route/controller call?
  3. What is the process to render a view with data when making jquery, ajax, get request in laravel?

Appreciate your help and direction. Thanks

0 likes
8 replies
usama.ashraf's avatar

@Sbelvadi your problem shows an interesting use-case.

With your view, you can pass data directly to your javascript and then use that to populate your view. Please do watch this:

https://laracasts.com/lessons/pass-data-to-your-javascript

Another way would be to have your view invoke an AJAX request when it loads. The AJAX request will then fetch the actual data required. But the package referenced in the video is much more elegant.

Sbelvadi's avatar

@consigliere: I did the following change:

public function createInvoiceByCustPO(Request $request, $custId, $poId )
    {
        /*$input = $request->all();
        dd($input);*/
        $customerId = $custId;
        $purchaseOrderId = $poId;
        Log::info('New: Create Invoice for user: ' . $customerId . ' and PO ID: ' . $purchaseOrderId);

        return View::make('data_entry.invoice.create')->with('companyCode', 'Qualitech Industries')
                ->with('customerName', $customerId)
                ->with('purchaseOrder', $purchaseOrderId)->render();


    }

No change

Should i update the AJAX call as well:

$('#addNewInvoiceBtn').on('click', function () {
        //e.preventDefault();
        var $custId = $('#selectCustomerForPOSelectList').val();
        var $poId = $('#purchaseOrderSelectItems').val();
        //alert("Customer ID: " +$customerId+ " po id: " +$purchaseOrderId );
        $.get('customer/' + $custId + '/purchase_order/'+ $poId + '/invoice/create', function (data) {
            //TODO - how do we show the response data
        });
    });
Sbelvadi's avatar

@usama.ashraf: Thanks for your response. @usama.ashraf and @consigliere: While thinking through this a little more, my use case is now: How do I render a different view (Invoice create.blade.php) with values passed in through the Get Request Ajax call (triggered by a button click on Invoice index.blade.php). Note: I dont want to show index, but render a completely different view that has customer id and PO id from the AJAX call?

usama.ashraf's avatar

Well that would somewhat beat the purpose of AJAX.

You can try this though. It'll load the new view in your main html tag:

$('html').load('your_ajax_url_to_controller');

or you could load your create view in some container of your current view:

$('#someContainer').load('your_ajax_url_to_controller');

IMO you'd be better off reloading the page on the GET request, not using AJAX.

davorminchorov's avatar
  1. Should I be using an AJAX Get in this case since the response would be shown in a Create view instead of the Index view?
  • I would do it with a normal post request and pass the data to the create view.
  1. If I should not be using the AJAX call for the Add New Invoice, How should I go about capturing the values selected in the index.blade and setup up the route/controller call?
  • Create a form like you always do when you post data to the server, and instead of saving the data to the database, return the request data from the previous page to the new page like so:
// routes.php
Route::post('/invoices/create', 'InvoicesController@create');

// InvoicesController.php
public function create(Request $request) 
{
    $customerId = $request->get('customer_id');
    $purchaseOrderNumber = $request->get('purchase_order_number');

    return view('invoices.create', compact('customerId', 'purchaseOrderNumber'));
}

// create.blade.php
<form method="post" action="/invoices">
    <input type="text" name="customer_id" value="{{ $customerId }}" />
    <input type="text" name="purchase_order_number" value="{{ $purchaseOrderNumber }}" />
</form>

or you could do a get request too if you want to show the values in the URL like search parameters. The choice is up to you.

There are other ways to deal with this, but this is one of them.

Please or to participate in this conversation.