3

Im developing a search bar in yii2 using ajax. The problem is the Yii::$app->request->isAjax property always returns false

This is my action:

public function actionAjaxsearch() { if(Yii::$app->request->isAjax) { $keywords = Yii::$app->request->queryParams; Yii::$app->response->format = \yii\web\Response::FORMAT_JSON; return [ 'data' => $keywords, 'code' => 200 ]; } else throw new \yii\web\HttpException(404, 'Page not found.'); 

And this is my script:

$('#search-box').keyup(function( event ){ event.preventDefault(); $.ajax({ url: 'http://localhost/items/ajaxsearch', data: {keywords: $( '#search-box' ).val()}, type: 'GET', dataType: 'json', }).done(function(){ console.log('success'); }).fail(function( data ){ alert( data ); }).always(function(){ alert('finished'); }) }); 

If i dont use the if with Yii::$app->request->isAjax the controller just render the JSON with the data.

P.D The content of #search-box is succesfully passed.

Edit to @SilverFire

Dont have some in the dump

["HTTP_X_REQUESTED_WITH"] => not defined, ["HTTP_ACCEPT"]=> string(74) "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8", ["CONTENT_TYPE"] =>not defined, ["HTTP_CONTENT_TYPE"] =>not defined, ["REQUEST_METHOD"]=> string(3) "GET", ["HTTP_X_HTTP_METHOD_OVERRIDE"] =>not defined, 
4
  • Could you show your $_SERVER dump? Commented Dec 9, 2015 at 11:39
  • @SilverFire you need to see any specific variable? I'm programming on dev server in my work. So I prefer not show all $_SERVER Commented Dec 9, 2015 at 11:46
  • Fair enough. Could you show HTTP_X_REQUESTED_WITH, HTTP_ACCEPT, CONTENT_TYPE, HTTP_CONTENT_TYPE, REQUEST_METHOD, HTTP_X_HTTP_METHOD_OVERRIDE Commented Dec 9, 2015 at 11:50
  • Edited the question. Commented Dec 9, 2015 at 11:58

1 Answer 1

4

Well, your browser for some reasons does not send the HTTP_X_REQUESTED_WITH headers to the server.

It guess it might be related to: Missing X-Requested-With: XMLHttpRequest (causes 200 OK But Shows as Error?) and Cross-Domain AJAX doesn't send X-Requested-With header

Sign up to request clarification or add additional context in comments.

3 Comments

I've tried to add the X-Requested-With header in the ajax request but still doesn't work.
Do you see this header on PHP side after you've added it in the ajax request?
It's the only way how server could guess that it's an Ajax request, so the problem relates at most XHR requests. Could you show a screenshot or text dump from the browser debug console with the detailed info about the request?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.