"Then Joshua sent them off, and they went to the place of ambush and lay in wait between Bethel and Ai, to the west of Ai - but Joshua spent that night with the people. Early the next morning Joshua mustered his army, and he and the leaders of Israel marched before them to Ai. The entire force that was with him marched up and approached the city and arrived in front of it. They set up camp north of Ai, with the valley between them and the city. Joshua had taken about five thousand men and set them in ambush between Bethel and Ai, to the west of the city. So the soldiers took up their positions - with the main camp to the north of the city and the ambush to the west of it. That night Joshua went into the valley." NIV translation
Israel went out to face Ai again but this time the entire army went with the leaders in the front. They had an ambush set and Joshua went to check on the men that night.
"When the king of Ai saw this, he and all the men of the city hurried out early in the morning to meet Israel in battle at a certain place overlooking the Arabah. But he did not know that an ambush had been set against him behind the city." NIV translation
The king of Ai had watched as Joshua went into the valley so he knew there was an ambush there. He did not know about the trap that was set behind the city and so the men left the city unprotected and went out to face Israel. This is a reminder to us that the devil does not know everything.
"Joshua and all Israel let themselves be driven back before them, and they fled toward the wilderness. All the men of Ai were called to pursue them, and they pursued Joshua and were lured away from the city. Not a man remained in Ai or Bethel who did not go after Israel. They left the city open and went in pursuit of Israel." NIV translation
Israel followed the plan that God had given them and the men of Ai and Bethel fell for it. It appeared that Israel was going to be routed again but that is because they did not see the whole picture.