Bangladesh made a confident start in the second innings thanks to a fluent batting by their top-order after Chris Woakes and Adil Rashid shared 99 runs in the ninth wicket to give England a vital 24-run first innings lead.
The hosts wiped out the deficit quickly and went for almost five runs in an over in the final session to put the pressure back on England before Ansari's late strike restored some parity for the visitors.
But Imrul Kayes, unbeaten on 59 overnight, and Mahmudullah shared 86 runs for the third wicket to help the home side restore their advantage.
They were leading England by 128 runs at the end of the second day's play with seven wickets in hand, which must have given them hopes for setting a decent target for England to chase in the fourth innings.
More From This Section
Woakes made 46 while Rashid added an unbeaten 44 to lift England 244 from a precarious 144-8 giving them a handy 24-run lead in the first innings.
Their die-hard batting overshadowed the bowling heroics of Bangladesh's teenage off-spinner Mehedi Hasan who finished with 6-82, his second five-wicket haul in as many matches.
Mehedi broke the partnership with the second new ball when he forced an edge from Woakes at slip and five balls later left-arm spinner Taijul Islam, who claimed 3-65, wrapped up England's innings.
Replay confirmed the ball was above the waist prompting the umpires to call Woakes back.
Resuming on 50-3, England found themselves in deep trouble in the morning session before Joe Root offered some resistance with 56 off 122 balls.
Jonny Bairstow, who made 24, gave him some support in their 45-run sixth wicket stand.
Mehedi, who claimed seven wickets in Bangladesh's 22-run loss in the first Test, including 6-80 in a single innings, again drew first blood, bowling overnight batsman Moeen Ali for 10 in the third over.
Mehedi returned for his second spell to hit Bairstow plumb in front in his first ball, ending their resistance.
Taijul removed Root almost identically to expose England's tail after Mehedi complete his five-wicket haul with the wicket of Ansari.