I am trying to call a function that isn't being recognised. I have a PHP block of code that adds the form to the HTML when the user is logged in:
<?php
if(isset($_SESSION['user'])) {
$usr = $_SESSION['user'];
echo("<form onsubmit=\"nbpost('#nbpost','$usr'); return false;\">\n");
echo("<textarea id='nbpost' placeholder='Create a post...'></textarea>\n");
echo("<button type='submit'>SUBMIT</button>\n");
echo("</form>\n");
}
?>
I put my JavaScript below that HTML. According to W3Schools, the script has nothing to do with how it's executed. Additionally, I've tried countless times to execute the script when the script was on top, with no result either.
Also, I previously had the code in a separate script, but I've taken it out to see if that's the issue.
Here's the script with an example of the generated HTML:
<form onsubmit="nbpost('#nbpost','$usr'); return false;">
<textarea id='nbpost' placeholder='Create a post...'></textarea>
<button type='submit'>SUBMIT</button>
</form>
<script type="text/javascript">
const nbpost = function(element, name) {
alert("WORKING");
name[0] = name[0].toUpperCase();
const msg = $(element).val;
console.log(name, msg);
$.ajax({
url: "http://rmpc/php/nbpost.php",
method: "POST",
data: {
name: name,
notice: msg
}
});
};
</script>
Whenever I execute the code, it simply says in the console:
Uncaught TypeError: nbpost is not a function at HTMLFormElement.onsubmit (index.php:54)
What's going wrong?