Reputation: 1112
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,
Upvotes: 3
Views: 7143
Reputation: 1592
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
Upvotes: 4