I would like to retrieve some database data where the query is executed initially by an AJAX call.
JAVASCRIPT
$('form[incidentForm]').on('submit', requestResponders );
var requestResponders = function(e) {
e.preventDefault();
getResponders(latitude, longitude, function(data) {
console.log(data);
});
}
function getResponders(latitude, longitude, callback) {
var geoInformation = [];
geoInformation.push({name:'latitude', value:latitude});
geoInformation.push({name:'longitude', value:longitude});
$.ajax({
type: "POST",
url: '../searchResponders',
data: geoInformation,
success: function(responders) {
callback(responders);
}
})
};
ROUTES
Route::post('searchResponders','RespondersController@getAvailableResponders');
PHP
public function getAvailableResponders(Request $request) {
$data = $request->all();
$responder = ResponderManagement::searchResponders($data);
return $responder;
}
public function searchResponders($geoInformation) {
$lat = $geoInformation['latitude'];
$lng = $geoInformation['longitude'];
$results = DB::select(DB::raw("SELECT STATEMENT));
return $results;
}
When I use POSTMAN to check the functionality, everything works fine. I get the wished for response and a json is returned with the database entries searched for.
When I use the AJAX call, I receive an empty array.
Therefore I guess, that due to the async behaviour, the return value is already returned, before the query in the DB has finished.
But I don't see why. I the ajax call, only on success I call the callback method to show the data. So I would guess the database query should have finished by that time already.
Can someone support me here please?
UPDATE 1: I updated my function now
public function searchResponders($geoInformation) {
$lat = $geoInformation['latitude'];
$lng = $geoInformation['longitude'];
$results = DB::select(DB::raw("SELECT STATEMENT));
echo json_encode($results);
}
But the returned value when logged in the console is still empty. whereas in the POSTMAN POST call everything is returned
Update 2 I grabbed a screenshot showing the content of the AJAX call in a chrome debugger. But this seems fine to me? Can someone help me out here? The response is still empty, but the direct call works fine.
UPDATE 3 I tested, if the success block is being called, which is the case. but when I log the content of the response data in the ajax request itself, it is already empty. So when the ajax request is being made to the URL with POST and the data to be sent, it returns empty. But isn't this the same approach as make the POST request by POSTMAN for example? There a response is being made.