I have a simple form page where I want to display the details of a client based on the selected client, I am a newbie to ajax and I've had this problem for quite some time and I really can't get to make it work.
Note: "Nume" is not a typo, its the way I included it in my db instead of name Also: id ='sel_depart' is the id of the selected client And, name="sel_emp" id="sel_emp" is where I want his details to be displayed (which is "iban")
This is my controller:
public function getClientspay( Request $request, $id){
$clientsid = $request->clientsid;
$clients = clients::select('*')->where('id', $clientsid)->get();
$response['data'] = $clients;
return response()->json($response);
}
This is my route:
Route::get('/getClientspay', [PlatiController::class,'getClientspay']);
This is the part of the form where I want to display it:
<div >
<label for="">Nume Client</label>
<label for="">Introduceti ID</label>
<select id ='sel_depart' name='sel_depart' >
@foreach ($clients as $clients)
<option name='search' value="{{$clients->id}}">{{$clients->nume}}</option>
@endforeach
</select>
<select name="sel_emp" id="sel_emp">
<option value="0"></option>
</select>
And this is my ajax request
$('#sel_depart').change(function(){
// Department id
var id = $(this).val();
// Empty the dropdown
$('#sel_emp').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'getClientspay',
type: 'get',
data: {_token: CSRF_TOKEN, clientsid: clientsid},
dataType: 'json',
success: function(response){
var len = 0;
if(response['data'] != null){
len = response['data'].length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i ){
var id = response['data'][i].id;
var iban = response['data'][i].iban ;
var option = "<option value='" id "'>" iban "</option>";
$("#sel_emp").append(option);
}
}
}
});
});
});
CodePudding user response:
use App\Models\Client;
public function getClientspay(Request $request, $id){
$client = Client::where('id', $id)->first(); // or Client::find($id);
return response()->json(['client' => $client]); // this will return specific user.
}
And remove your foreach loop for $clients inside your view. Just use $client. If you are using blade and don't need json just return $client variable to your view.
CodePudding user response:
I need more information. Please open Browser Developer Tools (usually F12) from the page with the form and check both "Console" and "Network" tabs while changing the select. From there it is possible to understand and fix your issue.