Sergi Canos scored his first-ever hat-trick, in 23 minutes, to give Brentford a thrilling win.
The Bees went into the half-time break 1-0 down after a brilliant opportunist goal from Will Vaulks, who scored from inside his own half in the final minute of stoppage-time.
But it was the Canos show after the break.
He equalised with a superb looping volley from 25 yards that dropped in just under the bar.
Canos then cut in from the left wing, beat two defenders and fired a low shot inside the near post to put Brentford ahead.
He completed his treble by again cutting in from the left and beating one defender, before firing in a shot that Alex Smithies probably should have done better with as he failed to hold it.
Cardiff had created little in the half but suddenly cut the deficit when Vaulks fired in a shot at a corner that deflected off Ivan Toney and into the net.
Canos had another shot saved near the end, and the Bees saw the game out to stretch their unbeaten run to 15 games, 14 in the league, and stay fourth in the table.
Brentford: Raya, Dalsgaard, Henry, Jansson, Pinnock, Janelt, Jensen (Dasilva 90), Marcondes, Canos (Forss 91), Mbeumo (Fosu 77), Toney.