One problem is that you're trying to make JS genarate PHP code, and then expecting that to work: it can't. PHP runs on the server, and only "does things" when asked for a page by the browser: PHP generates source code for the browser to deal with. That's all it does.
When the browser has the page, JS kicks in, and PHP is no longer anywhere to be found: see Difference between Javascript and PHP for more information on this, and I can strongly recommend reading up on that.
However, the real problem that you're describing (your page seemingly reloading but dying on the PHP code) is one caused by your use of document.write()
, which absolute doesn't do what you think it does, and you should not be using it in modern code.
document.write
is one of the earliest functions in JS and is super low level: it does not write text into a webpage, it writes bytes into the document bytestream so that the document parser can pick up data from the bytestream at the same time and parse it into a page tree.
While the page is still being processed, that seems safe: document.write
will simply inject bytes into the open bytestream, and the parser will parse that, and all will seem well. However, once the page tree is done and the document bytestream gets closed, things start to go very, very wrong:
Any call to document.write
will try to write into the open bytestream, and if it's closed, document.write
will simply open a bytestream: now you have an empty document bytestream. And because the document parser sees an open bytestream, it start building a page tree based on what's in it, and now your page is gone because that's what you told the browser to do.
It's also not the case that it "appears to stop loading at the PHP function", what actually happens is that you've told the page parser that the new page code to form a page tree off of is the byte sequence <?php echo upadtePurchaseToDB();?>
. So the parser looks at that, sees <
, and so knows that what comes after that will be a tag, because that's how HTML works. It then sees ?
and goes "Error: this HTML is invalid HTML" and stops.
So the bottom line here is to read up on where and when PHP runs, vs where and when JS runs, but arguably even more importantly: never use document.write
because it doesn't do what you think, at all.