Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

afoysal's avatar

Debug $.ajax() in Laravel 7

My AJAX code is like below

$('select[id="state"]').on('change', function() {
				var stateID =  $(this).val();	
				alert(stateID);	// I am getting value here		
				if(stateID) {
					$.ajax({
						url: '/cities?code='+stateID,
						type: "GET",
						dataType: "json",
						success:function(data) {
							alert('hello');
							$('select[name="city"]').empty();
							$.each(data, function(key, value) {
								$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
							});
						}
					});
				}else{
					$('select[name="city"]').empty();
				}
			});

My route is like below

Route::get('countries/{countryCode}/cities/{id}', 'Ajax\LocationController@getSelectedCity');

My controller function is like below

public function getSelectedCity($countryCode, $cityId)
	{
		// Get the City by its ID
		$cacheId = $countryCode . '.city.with.admins' . $cityId;

		Log::info($cityId);  // Value is not logging here. No log file generate for this.

		$city = Cache::remember($cacheId, $this->cacheExpiration, function () use ($countryCode, $cityId) {
			return City::countryOf($countryCode)->with(['subAdmin1', 'subAdmin2'])->where('id', $cityId)->first();
		});
		
		if (!empty($city)) {
			$text = $city->name;
			if (isset($city->subAdmin2) && !empty($city->subAdmin2)) {
				$text .= ', ' . $city->subAdmin2->name;
			} else {
				if (isset($city->subAdmin1) && !empty($city->subAdmin1)) {
					$text .= ', ' . $city->subAdmin1->name;
				}
			}
			$cityArr = ['id' => $city->id, 'text' => $text];
		} else {
			$cityArr = ['id' => 0, 'text' => t('select_a_city', [], 'global', request()->get('languageCode'))];
		}
		return response()->json($cityArr, 200, [], JSON_UNESCAPED_UNICODE);
	}

I used use Illuminate\Support\Facades\Log; at the start of the controller.

How to debug $.ajax() in Laravel 7 ?

0 likes
7 replies
automica's avatar
automica
Best Answer
Level 54

@afoysal what do you see if you use the network tab of your browser? you should be able to see the response coming back from the server.

you can also add the following:

  error: function(xhr, status, error){
         var errorMessage = xhr.status + ': ' + xhr.statusText
         alert('Error - ' + errorMessage);
     }

which will allow you to catch the error if the request fails.

Regarding the logging, are you actually hitting the method at all? if you add a log method to another known working route, does that drop a line in the log file?

also the route you are calling in $.ajax is

url: '/cities?code='+stateID,

which doesn't match the route in

Route::get('countries/{countryCode}/cities/{id}', 'Ajax\LocationController@getSelectedCity');
1 like
afoysal's avatar

Thanks @automica . Actually I working in a purchased script. You can say I am copy pasting code. I am getting Error - 400: Bad Request from your code. Why it is happening ? Why I am getting this error.

What will be the route if I use url: '/cities?code='+stateID, this URL ?

Thanks.

automica's avatar

@afoysal your script looks like its attempting to make a dropdown of cities for a given state.

if you purchased the script, did you also get sql data with it?

I would expect a list of states, keyed by id and also a list of cities, keyed by id, and state_id.

the Laravel route for '/cities?code='+stateID,

would be something like

Route::get(cities/code/{state}', 'Ajax\CitiesController@getCitiesForState');

you'll need to create a cities controller and also create a method called getCitiesForState

1 like
afoysal's avatar

Thanks @automica . I changed my code like below

$('select[id="state"]').on('change', function() {
				var stateID =  $(this).val();
				if(stateID) {
					$.ajax({
						url: '/cities/'+7,
						type: "GET",
						success:function(data) {
							$('select[name="city"]').empty();
							$.each(data, function(key, value) {
								$('select[name="city"]').append('<option value="'+ key +'">'+ value +'</option>');
							});
						},
						error: function(xhr, status, error){
							var errorMessage = xhr.status + ': ' + xhr.statusText
							alert('Error - ' + errorMessage);
						}
					});
				}else{
					$('select[name="city"]').empty();
				}
			});

My route is like below

Route::get('/cities/{id}', 'LocationController@getSelectedCityajax');

My controller function is like below

public function getSelectedCityajax($id)
	{
		return response()->json(['success'=>$id]);
	}

But I am getting error Error - 400: Bad Request.

automica's avatar

@afoysal what happens if you hit that route via a browser

eg

localhost/cities/7
1 like
automica's avatar

@afoysal if you run

php artisan route:list

do you see a new route?

also

public function getSelectedCityajax($id)
	{

		dd($id);

		return response()->json(['success'=>$id]);
	}

does that return the city id you are passing in?

1 like

Please or to participate in this conversation.