Reputation: 2323
The following button calls a jQuery function onClick. However, the Firefox dev console says "postData is not defined."
Here is the button and the jQuery script.
<div class="center_text_grid flex-item EMail_Pwd">
<button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button></div>
function sendReply() {
// autoresponder
}
postData().done(sendReply);
</script>
</form><br>
<br><br><br>
<!-- ________________ -->
<script type="text/javascript">
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
}
Why does the console say the function postData is not defined?
Thanks for any ideas.
Upvotes: 0
Views: 185
Reputation: 3257
I don't understand why you need two nested ajax calls, you really don't need them, I think. In any case, you can't declare a variable like this var datastring = $("#echo_test").serialize();
inside curly brackets, so move that line outside the ajax call.
Also take into consideration the order in which you declare/execute functions.
So, moving the script, where the function is declared, up:
<div class="center_text_grid flex-item EMail_Pwd">
<button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)" onClick="postData()">Click to Submit Data</button></div>
<script type="text/javascript">
function postData() {
var datastring = $("#echo_test").serialize();
return $.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
}
</script>
<script>
function sendReply() {
// autoresponder
}
//also, this line is not needed for the button to work, this is just if
//you need the function to execute on page load as well
postData().done(sendReply);
</script>
HIH
Upvotes: 2
Reputation: 2109
you are calling postData before to implement the method, as mentioned move your function document.ready or put
<script type="text/javascript">
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
}
</script>
in the head of the html file
Upvotes: 2
Reputation: 14413
Remove onclick
from the button and add handler in the $(document.ready)
function:
<button class="btn_joinnow" id="btn_joinnow" style="color:rgb(255,255,255)">Click to Submit Data</button></div>
...
<script type="text/javascript">
$(function(){
function postData() {
return $.ajax({
var datastring = $("#echo_test").serialize();
$.ajax({
type: "POST",
url: "echo_test.php",
data: {post: datastring},
});
});
$("#btn_joinnow").click(postData);
});
</script>
Upvotes: 1