When things happen not the way we prayed for, it could mean that what we prayed was not in God's will. This is one of the many possibilities. Other possibilities are that we did not have enough faith in God when we prayed. As James says, we should ask in faith with no doubt. He said further that the person who doubts 'is like a wave of the sea that is driven and tossed by the wind. For that person must not suppose that he will receive anything from the Lord' (James 1:7-8, ESV).
Lack of faith, or prayer with doubt that arises out of a double-mind could be one reason why prayers are not answered. However, the possibility remains for prayers in full faith to be unanswered. It could be that what we prayed for is not in the will of God.
I can think of the case of Paul where he says that he prayed three times for the 'thorn in the flesh' to be removed. It could be ailment that he prayed for healing. However, God did not answer his prayer for healing but just assured him of His constant sustaining grace: 'My grace is sufficient for you, for my power is made perfect in weakness' (2 Cor 12:9, ESV).
What went wrong with Paul's prayers? It seems that he was praying for something that was not in God's will.
So, what should we do when things happen against our expectations even after earnest prayers? We should surrender to his supreme will and move in the direction he shows hoping that God has chosen us the best. Again we exercise our faith in God. The faith that all gifts that God, 'the father of lights' sends are good (James 1:17).