Affine frequency division multiplexing (AFDM) is a chirp-based multicarrier waveform that was recently proposed for communication over doubly dispersive channels. Given its chirp nature, AFDM is expected to have superior sensing capabilities compared to orthogonal frequency division multiplexing (OFDM) and is thus a promising candidate for integrated sensing and communication (ISAC) applications. In this paper, we derive a closed-form expression for the ambiguity function of AFDM waveforms modulated with $M$-ary quadrature amplitude modulation (QAM) data symbols. We determine the condition on the chirp rate of the AFDM waveform that minimizes the sidelobes in the delay/range domain in the presence of random $M$-ary QAM symbols, thereby improving overall sensing performance. Additionally, we find an approximate statistical distribution for the magnitude of the derived ambiguity function. Simulation results are presented to evaluate the sensing performance of the AFDM waveform for various system parameters and to compare its peak-to-sidelobe ratio (PSLR) and integrated sidelobe ratio (ISLR) with those of OFDM.