[英]laravel ajax, How to send form having value='put' successfully?
[英]how to send a value of foreach loop form using ajax in laravel?
我正在嘗試將值從表單發送到 controller 但錯誤都是 forms 作為第一個表單發送值,但我希望每個表單在按下發送按鈕時發送其中的數據。
刀片代碼:
@foreach($car_lists as $car_list)
<li class="item odd cars_data">
<form style="display:flex;" id="addcurrency" >
<input type="hidden" name="amount" value="{{@session('amount')}} {{$car_list->price}}">
<span class="result"> {{$car_list->price}}</span>
<span class="d-flex align-items-center justify-content-center w-24px h-22px bg-gray-300 rounded cursor-pointer undefined result_symb addCurrency"><svg xmlns="http://www.w3.org/2000/svg" width="10px" height="11px" viewBox="0 0 10 11"><path id="GEL" d="M313.914-18v-1.689h-3.663a2.938,2.938,0,0,1-1.643-.46,3,3,0,0,1-1.089-1.3,4.608,4.608,0,0,1-.384-1.94,5,5,0,0,1,.343-1.987,2.543,2.543,0,0,1,1.112-1.225v3.372h.894v-3.64a2.492,2.492,0,0,1,.48-.044,2.936,2.936,0,0,1,.5.044v3.64h.894V-26.6a2.469,2.469,0,0,1,1.134,1.24,5.547,5.547,0,0,1,.343,2.132H315a6.022,6.022,0,0,0-.439-2.324,4.874,4.874,0,0,0-1.263-1.8,4.534,4.534,0,0,0-1.939-1.019V-29h-.894v.472l-.236-.007q-.081-.007-.236-.007-.347,0-.51.015V-29h-.894v.631a4.67,4.67,0,0,0-1.891.982,4.823,4.823,0,0,0-1.256,1.671A4.872,4.872,0,0,0,305-23.67a5.7,5.7,0,0,0,.229,1.61,4.62,4.62,0,0,0,.672,1.4,3.294,3.294,0,0,0,1.056.968v.058h-1.411V-18Z" transform="translate(-305 29)" fill="#272a37"></path></svg></span>
<button type="submit">submit</button>
</form>
</li>
@endforeach
那么如何解決這個問題,我將從每個表格發送到我的 controller 和 ajax?
ajax代碼:
$('#addcurrency').on('submit', function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var currency = $(this);
var currency_id = $(currency).closest('.cars_data').find('.car_id').val();
var data = $(currency).closest('.cars_data').find('#addcurrency').serializeArray();
$.ajax({
type: "POST",
url: "/convert",
data: data,
dataType: "json",
success: function(response){
$(currency).closest('.cars_data').find('.result').html(response.count);
}
});
});
我的 controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Car;
use AmrShawky\LaravelCurrency\Facade\Currency;
class CurrencyController extends Controller
{
public function convert(Request $request)
{
$converted = Currency::convert()
->from('GEL')
->to('USD')
->amount($request->amount)
->round(-2)
->get();
return response()->json(['count' => $converted]);
}
}
ids 必須是唯一的,否則只有第一個 id 有效。 您可以嘗試 class 而不是 id:
...
<form class='addcurrency'>
...
$('.addcurrency').on('submit'....
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.