Why am I getting HTML response from jquery ajax call - php

I am trying to use jQuery UI autocomplete in my Laravel project to show some suggestions as the user is typing in. Here is the script triggered when the user types in:
$(".autocomplete").autocomplete({
source: function(request, response) {
$.ajax({
url: '/autocomplete',
dataType: "json",
data: {
term : request.term,
field : $(this.element).prop("id")
},
success: function(data) {
console.log(data);
response(data);
},
error: function(result, status, error) {
console.log(result);
console.log(status);
console.log(error);
}
});
},
min_length: 0, });
Here is my route in web.php
Route::get('/autocomplete', 'SitesController#autocomplete');
And finally my controller which retrieves results from the database.
public function autocomplete(Request $request) {
$term = \Request::get('term');
$field = \Request::get('field');
$sites = Site::where($field, 'ILIKE', '%'.$term.'%')
->distinct()
->get([$field]);
$data = [];
foreach($sites as $key => $site) {
$data[] = $site->$field;
}
return \Response::json($data);
}
This is currently not working, but when I directly add the above code to my route files, it does work well.
Route::get('/autocomplete', function()
{
$term = \Request::get('term');
$field = \Request::get('field');
$sites = Site::where($field, 'ILIKE', '%'.$term.'%')
->distinct()
->get([$field]);
$data = [];
foreach($sites as $key => $site) {
$data[] = $site->$field;
}
return \Response::json($data);
});
My script is returning a HTML response, and here is the error I get from the console:
SyntaxError: Unexpected token < in JSON at position 0
at parse (<anonymous>)
at ajaxConvert (VM258 app.js:18060)
at done (VM258 app.js:18530)
at XMLHttpRequest.<anonymous> (VM258 app.js:18832)
I can't see why my script is not returning JSON but HTML, while it does when I put my script in the web.php file.

As suggested by aynber, looking closely at the returned HTML page, I realized it was an error page that I throw thanks to a middleware, when someone is trying to access a page without having the rights. And my controller was of course checking for this middleware first. I made an exception for the autocomplete function and now everything is working fine, though I feel I'm not handling my middlewares the good way...

in app/Exceptions/Handler.php file you can do something like this
public function render($request, Exception $e)
{
if ($request->wantsJson()) {
$response = ... // put your response data here
return response()->json($response);
}
...
}

Related

I'm making an dependent drop-down of countries states and cities in Laravel 9 using jQuery and Ajax but getting an 500 internal server

I'm making an dependent drop-downn of countries states and cities in laravel using jQuery and Ajax. I'm doing it on localhost Xampp. First i use jQuery for country. when country change jQuery get value and send to Controller. But when i send value from RegistrationFormComponent to CountryStateCity Controller and try to show what value i get. I got an error ( POST http://127.0.0.1:8000/getstate 500 (Internal Server Error) ). i don't know why im getting this error.
Route:
Route::get('/register', [CountryStateCityController::class, 'getcountry']);
Route::POST('/getstate ', [CountryStateCityController::class, 'getstate']);
JQuery and Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$('#country').change(function () {
var cid = this.value; //$(this).val(); we cal also write this.
$.ajax({
url: "getstate",
type: "POST",
datatype: "json",
data: {
country_id: cid,
},
success: function(result) {
// if(cid == "success")
// alert(response);
console.log(result);
},
errror: function(xhr) {
console.log(xhr.responseText);
}
});
});
});
Controller
class CountryStateCityController extends Controller
{
public function getcountry() {
$country = DB::table('countries')->get();
$data = compact('country');
return view('RegistrationForm')->with($data);
}
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
public function getcity() {
}
}
I think i tryed every possible thing. But didn't work. Please tell me how can i get rid of this problem. And please also tell me how can i send data from component to controller using jquery and ajax and get value form controller and take data from database and send back to component.
This is written incorrectly.
public function getstate(Request $request) {
$state = State::where('countryid'->$cid)->get();
return response()->json($state);
}
It should look like this.
public function getstate(Request $request) {
$state = State::where('countryid', '=', $request->country_id)->get();
return response()->json($state);
}
please check controller function
public function getstate(Request $request) {
$state = State::where('countryid' `=` ,request->$countryid)->get();
return response()->json($state);
}

Getting 500 error code while fetching data from DB using Ajax in Laravel

I am getting a 500 error code while fetching data from the database using Ajax in Laravel with the following function:
public function search(Request $request)
{
if ($request->ajax()) {
$query = $request->get('query');
$data = Constant_model::get_icons('fontawesomeicons', 'id', 'DESC', 20, $query);
}
return response($data->jsonSerialize(), Response::HTTP_OK);
}
get_icons function is:
public static function get_icons($table, $order_column, $order_type, $limit, $search = '')
{
$result = DB::table($table)
->select('*')
->orderBy($order_column, $order_type)
->where('icon_name', 'like', '%'.$search.'%')
->paginate($limit);
return $result;
}
I am trying to get the data using Ajax with the following Javascript:
$.ajax({
url: "/icons/search",
method: "GET",
data: {
search: query
},
dataType: 'json',
error: function (error) {
console.log(error);
},
success: function(response) {
alert(response);
}
});
Class App\Http\Controllers\Response. You forgot to use Response in above your code.
Put that in:
use Response;
Or just use a helper, if you don't want to import it:
return response()->json(...);
Now in your case, you must return it, like this:
return response()->json($data->jsonSerialize(), Response::HTTP_OK);

Ajax GET request is empty despite correct query string parameter

Using a simple Ajax GET request to retrieve some data, it successfully checks if($request->ajax()) {} but then fails any validation because there is no data in the Request $request variable. This happens only on the production server, on localhost everything works fine.
The console shows the intended URL https://example.com/employeeInfo?id=1, then error 422 (Unprocessable Entity). Output from error: function(jqxhr, status, exception) { alert('Exception:', exception); } gives an empty alert message.
View
<script>
(function ($) {
$(document).ready(function() {
$(".team-pic").off("click").on("click", function() {
$id = $(this).data('id');
// Get data
$.ajax({
type: 'GET',
url: 'employeeInfo',
data: {'id':$id},
success: function(data){
var obj=$.parseJSON(data);
// Show output...
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
});
});
}(jQuery));
</script>
Route
Route::get('/employeeInfo', 'EmployeeController#get');
Controller
public function get(Request $request) {
if($request->ajax()) {
$this->validate($request, [
'id' => 'required|integer',
]);
// Id
$employee = Employee::find(request('id'));
// Create output
$data = ...
echo json_encode($data);
}
}
If I were you, I would use a RESTful API with route model binding, specifically the explicit binding.
RouteServiceProvider.php
public function boot()
{
parent::boot();
Route::model('employee', App\Employee::class);
}
Route
Route::get('api/employees/{employee}', 'EmployeeController#get');
Controller
public function get(Employee $employee)
{
// The id being valid is already done by forcing it to be an Employee
// It is also an ajax call because it is going to the api route
// This will json_encode the employee object.
return $employee;
}

How to retrieve a parameter from ajax to laravel API Controller

I have an API that requires a string parameter. I want to take the query parameter to the controller and process there. I tried $ajax_data = Input::get('query'); but it didnt work. Searched the same question but cant find a decent answer. Current error is $ajax_data is empty.
My ajax request:
const sendAPIRequest = function (csrf, f) {
$.ajax({
async: false,
url: 'api/apitest',
method: 'get',
data:{
query:"select?facet=on&q=*:*&rows=1&json.facet={Categories:{type:terms,field:price,limit:3}}"
},
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + tkid);
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('X-CSRF-TOKEN', csrf.trim());
},
success: function (data) {
f(data);
},
error: function(xhr) {
//Do Something to handle error
}
});
};
My Controller API part:
public function apitest(){
$ajax_data = Input::get('query');
$user_type = UserAuthorizationHelper::user_authorization();
if ($user_type == Authorities::EDIT_ORGANISATIONS) {}
$query = new GuzzleHttp\Client();
try {
$response = $query->request('GET',SolrController::$url.$ajax_data);
} catch (GuzzleHttp\Exception\GuzzleException $e) {}
$data = $response->getBody()->getContents();
return response()->json(json_decode($data));
}
You are having a problem in this line:
$ajax_data = Input::get('query');
When you are making a request, Request object is sent with the data.
So, instead of Input replace it with Request's object, and you will get the desired output.
Something like this:
// Don't forget to import the Request's namespace
public function apitest(Request $request)
{
$ajax_data = $request->get('query');
// ... Rest of your code
}

Export CSV using Laravel via Ajax

I have a export csv function, it worked fine with laravel. But now I want to call export function via ajax and use method post, but I there is no respone. I can send a variable from laravel controller to response, but can not send a file download.
Here is my code :
route.php
Route::get('/title/show', 'TitleController#show');
Route::post('/title/show', 'TitleController#exportFromDB');
show.blade.php
<script>
$(document).ready(function () {
$('#exportFromDB').click(function () {
$.ajax({
url: "",
type: "post",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: {},
success: function (response) {
var a = document.createElement("a");
a.href = response.file;
a.download = response.name;
}
})
})
})
TitleController.php:
$dataExport['Oversea'] = $dataOversea;
$this->titleRepository->export('csv', $properties, $dataExport);
TitleRepository.php
public function export($type, $properties, $data)
{
if (in_array($type, self::EXPORT_TYPE)) {
try {
return Excel::create($properties['_title'], function ($excel) use ($data, $properties) {
$excel->setTitle($properties['_title']);
$excel->setCreator($properties['_creator'])
->setCompany($properties['_company']);
$excel->setDescription($properties['_description']);
$excel->sheet('Sheet', function ($sheet) use ($data) {
foreach ($data as $item) {
$sheet->fromArray($item);
}
});
})->export($type);
} catch (Exception $error) {
throw $error;
}
}
}
How can I fix them ? Thank !
Try this -
Don't write the code for export in your controller method, instead just save the excel file in your public folder.
Your controller method should return the filename.
On your ajax success do this -
location.href = path/to/file/property_title.xls
So replace your this line
->export($type);
with
->store($type, 'public/reports/', true);
I see your ajax url null value
Change it to
url : "{{ action('TitleController#exportFromDB') }}"
After that, response is data you return in controller
success: function (response) {}
I installed the maatwebsite/excel package and was able to do it without writing any javascript. All you need to do is setup a link (or typical form post if you prefer) to an action like so:
public downloadItemsExcel() {
$items = Item::all();
Excel::create('items', function($excel) use($items) {
$excel->sheet('ExportFile', function($sheet) use($items) {
$sheet->fromArray($items);
});
})->export('xls');
}
This works for csv/excel files alike. There is no reload of a page in the browser.
First you have to change POST method to GET.
For ajax you can do it like this:
$(document).ready(function () {
$('#exportFromDB').click(function () {
$.get('/title/show, function(data){
window.location = '/title/show=' + data;
});
})
})

Categories