If done correctly, that will work, unless javascript needs some escaping before the PHP can be read. My code editor (Notepad++) highlights the inserted PHP correctly, but I don't know for sure as I am not proficient in js and how it interacts with PHP.
I would need to see exactly what you did to tell what went wrong.