I'm trying to send value from form to controller but the error is all forms send value as a first form but I want each form to send the data inside it when I press the send button.
blade code:
@foreach($car_lists as $car_list)
<li >
<form style="display:flex;" id="addcurrency" >
<input type="hidden" name="amount" value="{{@session('amount')}} {{$car_list->price}}">
<span > {{$car_list->price}}</span>
<span ><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
So how to I fix this that I'd send from each form to my controller with ajax?
ajax code:
$('#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);
}
});
});
my 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]);
}
}
CodePudding user response:
ids must be unique, otherwise only the first id works. you can try class instead of id:
...
<form class='addcurrency'>
...
$('.addcurrency').on('submit'....