First of your solution does work, but It is not a good practice to mix client-side code with server-side code. It is a best practice to put javascript in seperate .js files(no PHP in it)
I would first create an API(write documentation) like for example
GET
http://localhost/getProfile?username=$username
POST
http://localhost/getProfile/$username
It will return JSON-object using json_encode. You could use json-p for cross domain communication. Then from for example Jquery you can easily get the data.
This way your javascript would stay clean.