hook_query_alter, AJAX, views_get_view : have to submit twice A view is embedded in a page template via this code. It's AJAX enabled and uses exposed filters which I have to mess around with for business purposes :

$view = views_get_view('rechercher', $reset);
$view-&gt;set_display('default');
$view-&gt;set_use_ajax(TRUE);

$set_exposed_input  = array();
if (isset($_GET['commune'])) {
  $set_exposed_input['field_commune_value'] = filter_xss($_GET['commune']);                
}
if (arg(1) == 646 &amp;&amp; ! isset($_GET['raz'])) {
  $set_exposed_input['field_type_vente_value'] = 'LOCA';
} elseif (arg(1) == 645 &amp;&amp;  ! isset($_GET['raz'])) {
  $set_exposed_input['field_type_vente_value'] = 'VENT';
}
if ($set_exposed_input) {
  $view-&gt;set_exposed_input($set_exposed_input);
}
$view-&gt;execute();
print $view-&gt;render();


It works perfectly.

Now the query must be altered via hook_query_alter :

function my_module_views_query_alter(&amp;$view, &amp;$query) {

  // Unrelevant stuff here

  if ($view-&gt;name == 'rechercher') {
    $view-&gt;query-&gt;add_table('field_data_field_cp');    
    $view-&gt;query-&gt;add_where(1, 'field_data_field_cp.field_cp_value', '%' . $_SESSION['filtres']['field_commune_value'] . '%', 'LIKE');    
  }  


As soon as I uncomment this code, I have to submit the view twice to have the results refreshed.

Except for this, the view behaves as expected (query returns the right data, etc.).

I guess it's some kind of cache and/or form caching issue but can't figure what exactly.

Any help would be appreciated.



EDIT : Some more details

Please forget AJAX : it has nothing to do with it, as the behaviour is exactly the same without it.

One more info : the query is correctly altered on the first filters form submission. Dumping proves it.

So it boils down to something that happens AFTER query altering. The mistery remains as to what and when.
It was some kind of mess with the $_SESSION variable, which I used for independant reasons.

I corrected my code this way :

  if ($view-&gt;name == 'rechercher') {
    $view-&gt;query-&gt;add_table('field_data_field_cp');    

// Old code
// $view-&gt;query-&gt;add_where(1, 'field_data_field_cp.field_cp_value', '%' . 
// $_SESSION['filtres']['field_commune_value'] . '%', 'LIKE');

// New code
    $view-&gt;query-&gt;add_where(1, 'field_data_field_cp.field_cp_value', '%' . $view-&gt;exposed_data['field_commune_value'] . '%', 'LIKE');    
  } 


... and everything seems to be fine, AJAX and all. 

Thanks to Clive for the help.