I have a problem with Ajax. I have a controller where is get response from external API. In this controller are passing variables to API request. The result is passing to a view. On this view I have drop down list with currency's. I want when user select another currency the new request will be send to API and generate new view.
Below is file and code.
web.php
Route::get('/home', 'HomeController@nbp');
Route::post('/home','HomeController@nbp');
HomeController.php
public function nbp(Request $request)
{
$data = $request->all();
if($request->ajax() && $request->isMethod('post')){
$data = response()->json($data);
$data = $data->getContent();
$data = json_decode($data, true);
$currency = $data['currency'];
Debugbar::info($currency);
}else{
$currency = 'EUR';
}
$tabeA = 'a';
// Create a client with a base URI
$client = new GuzzleHttpClient(['base_uri' => 'http://api.nbp.pl/api/'],['headers'=>['content-type'=> 'application/json']]);
// Send a request
$response = $client->request('GET', 'exchangerates/rates/'.$tableA.'/'.$currency);
$response->getStatusCode();
// 200
//$contentType = $response->getReasonPhrase();
// 'application/json; charset=utf8'
$currency = json_decode($response->getBody());
$data = $currency->rates;
$data2 = $data[0]->mid;
if($request->ajax() && $request->isMethod('post')){
return view('home',compact('currency'))->render();
}else{
return view('home',compact('currency'));
}
}
script.js
$('#currencyNameA').change(function() {
$.ajax({
type:'post',
dataType: 'json',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
url: '/home',
data: { currency : $('#currencyNameA').val()},
success: function(data){
},
complete: function(data){
}
});
});
The request to API must be http://api.nbp.pl/api/$table/$currency
Example: http://api.nbp.pl/api/a/USD