1. When the dog saw me, he wagged his tail.

2. When he saw me, the dog wagged his tail.
--------------------------
Which one is grammatical? Are both ok?

Both are fine.

Both sentences are grammatically correct. The only difference between them is the order of the subject and the object. In the first sentence, "the dog" is the subject, and "me" is the object. In the second sentence, "he" is the subject, and "the dog" is the object.

The choice between the two depends on what you want to emphasize in the sentence. If you want to emphasize that it was the dog who wagged his tail, then the first sentence, "When the dog saw me, he wagged his tail," would be more appropriate. On the other hand, if you want to emphasize that it was you who the dog wagged his tail at, then the second sentence, "When he saw me, the dog wagged his tail," would be more suitable.

So, both sentences are grammatical and have the same meaning, but the word order allows you to place emphasis on different elements of the sentence.