Let $A, B$ be two commutative rings. Let $p$ be a prime ideal of A. Now, suppose we have two ring homomorphisms $f:A \rightarrow B$ and $g: B \rightarrow A_{p}$ such that $g \circ f$ is the canonical map from $A$ to $A_{p}$.
Then is it true that $A_{p}$ is isomorphic to $B_{g^{-1}(pA_P)}$?
If yes, how can we prove it? I think it is at least true if $f$ is an injective map. Also, I think I can show that the canonical map from $A_p$ to $B_{g^{-1}(pA_P)}$ is injective.
No, not even when $f$ is injective. For example, take a field $F$ and then take $F \hookrightarrow F[x] \to F$, where the first map is the inclusion and second map is the identity on $F$ and sends $x \mapsto 0$. $F$ is a commutative ring and in particular, we can localize at the prime ideal $(0)$, which just gives $F$ again. But if you take the inverse image of $(0)$ in $F[x]$, you get the prime ideal $(x)$, and surely $F$ and $F[x]_{(x)}$ are not isomorphic because $x/1$ is not invertible in $F[x]_{(x)}$, so $F[x]_{(x)}$ isn't a field.
If you think about it in terms of the universal property, then given a map $h: A \to C$ such that $h(s)$ is a unit in $C$ for all $s \not \in p$, you should get a unique factorization $A \to A_p \to C$. But if you add anything else to $A_p$, you then get free choices as to where the extra stuff can go, so you don't get universality. I suppose you could have "versality" (there exists a non-unique map etc.) but that's a different notion.
EDIT: As per your comment, suppose $f$ is surjective. Then the answer is yes. We can replace $f: A \to B$ with $f: A \to A/I$ for some ideal $I$ in $A$. In particular, for $a \in I$, we have that the image of $a$ in $A_p$ is $0$, or in other words, there exists some $s \not \in p$ such that $sa = 0$. But as $p$ is prime, this means that $a \in p$, so $I$ is contained in $p$.
So say $h: A \to C$ satisfies $h(s) \in C^\times$ for all $s \not \in p$. Given $a \in I$ we can find $s \not \in p$ such that $as = 0$, so $$h(a) = h(a)h(s)h(s)^{-1} = h(as)h(s)^{-1} = 0,$$ which means that $h$ is actually defined on $A/I$ and descends uniquely to a map on $(A/I)_{p/I}$. By the universal propety, this proves that $(A/I)_{p/I}$ is isomorphic to $A_p$.
Note this certainly can happen with $I \neq 0$ and $A_p \neq 0$ (for example, take $A = \mathbb Z/6 \mathbb Z$ with $p = I = 2\mathbb Z/6\mathbb Z$).