简体   繁体   English

如何将JS变量应用于Laravel Form Action

[英]How to apply a JS variable to a Laravel Form Action

I need to pass an AJAX variable into my view such that the form action executes correctly. 我需要将AJAX变量传递到我的视图中,以便正确执行form action Using Laravel 5.4. 使用Laravel 5.4。 and my (abbreviated) view looks like this: 我的(缩写)视图如下所示:

<div id="product_form"  class="form-horizontal">

    {{ Form::open(['action' => 'ProductController@update_product', // PRODUCT_ID MUST GO HERE]) }}


    <div class=" form-group">
        <div class="col-sm-2  col-md-2">{{ Form::label('product_name', 'Product Name:') }}</div>
        <div class="col-sm-4 col-md-4">{{ Form::text('product_name',null) }}</div>
        <div class="col-sm-2 col-md-2">{{ Form::label('product_id', 'Product Code') }}</div>
        <div class="col-sm-4 col-md-4">{{ Form::text('product_id', null) }}</div>
    </div>

My Ajax function is passing all the values into the form fields correctly, however I am struggling to get the product_id into the correct place in the action statement. 我的Ajax函数将所有值正确地传递到表单字段中,但是我正在努力将product_id放入action语句中的正确位置。 Laravel expects to see a variable. Laravel希望看到一个变量。

Ajax Code (abbreviated): Ajax代码(缩写):

 select: function( event, ui ) {
        var product_id = ( ui.item.value );

        $.ajax({
            url: "product_fullsearch/"+product_id,
            dataType: "json",
            type:"GET",
            success: function (data) {
                $('#product_name').val(data[0].product_name);
                $('#product_id').val(data[0].product_id);
                $("#supplier_name").val(data[0].supplier_name);
                $("#supplier_id").val(data[0].supplier_id);
            }
        });//END AJAX

    } 

I saw this Pass JS variable to form action on SO and gave it a go, but I could not get it to work in a Laravel context. 我看到此Pass JS变量在SO 上形成动作 ,并使其通过,但我无法使其在Laravel上下文中工作。

What am I dong wrong ? 我在做什么错? Many thanks ! 非常感谢 !

I thought of an alternative way of solving the problem: 我想到了另一种解决问题的方法:

Instead of attempting to pass a variable into the form action , I changed the Route such that it no longer required an id . 我没有尝试将变量传递到form action ,而是更改了Route,使其不再需要id Then in the controller I simply pull the id value from the $request array like this: 然后在控制器中,我像这样从$request数组中简单地提取id值:

$id = $request->product_id;

I this way the update works: 我这样更新工作:

 $id = $request->product_id;

    Product::updateOrCreate(array('product_id' => $id),
        array(
            'product_name' => $request->product_name,
            'product_id'=>$id,
        ));

I hope this helps someone else. 我希望这可以帮助其他人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM