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?
3 Answers 3
Change the name of the function nbpost so it does not match the textarea id='nbpost'
1 Comment
I would try and separate your content a little better, it can make it less confusing. Give this a try with jQuery enabled.
<?php
if(isset($_SESSION['user'])) {
$usr = $_SESSION['user']; ?>
<form id="form" method="post">
<textarea id='nbpost' placeholder='Create a post...'></textarea>
<input type="hidden" name="user" value="<?=$usr;?>">
<button type='submit'>SUBMIT</button>
</form>
<?php
}
?>
This needs to go at the bottom of your document. You can also put the JavaScript in a separate file and call it by filename of course.
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$("#form").on("submit", function (e) {
e.preventDefault();
var name = $("input[name=user]").val().toUpperCase();
var msg = $("#nbpost").val();
console.log(name, msg);
$.ajax({
url: "http://rmpc/php/nbpost.php",
method: "POST",
data: {
name: name,
notice: msg
}
});
});
</script>
see if this works for you.
2 Comments
You should declare your submit event as an entire function
onsubmit=\"function(){nbpost('#nbpost','$usr'); return false;}\"
const nbpost = functionvsfunction nbpost. There is a great SO Answer explaining the scope issues, but I would try declaring your function asfunction nbpost(element,name){}and see what happens.