Reputation: 125
I am trying to get and post data from a listbox using the onchange=
but i get the error Reference Error: Cant find variable: getMessage
getMessage is the name of function that contains the ajax get and post and I'm gessueing it means that it can't find the function for some reason. does anyone know why? my code is shown below.
<script type="text/javascript">
function getMessage() {
var data = { message : {$("#messageselect").val(); }};
$.ajax({
url: "/message",
type: "GET",
data: JSON.stringify(data),
dataType: 'jsonp'
})
$.ajax({
url: "/message",
type: "POST",
dataType: 'json',
contentType: 'application/json',
success: function(data) {
console.log(data);
}
error : function(err) {
console.log("error fetching message");
}
});
}
</script>
server:
app.post('/message', function(req, res) {
console.log(JSON.stringify(req.body));
Message.findOne({ 'page.message' : req.data }, function(err, message) {
if(err){
throw err;
}
res.send(message);
});
});
html:
<form method="POST">
<select multiple="multiple" class="messageselect" onchange="getMessage()" id="messageselect">
<% if(message) { %>
<% for(i=messagecount-1;i>=0;i--) { %>
<option value="<%= message[i].page.message %>">
From: <%= message[i].page.username %>
Message: <%= message[i].page.messagetitle %>
</option>
<% } %>
<% } %>
</select><br><br><br>
</form>
Upvotes: 0
Views: 132
Reputation: 5888
you need to define your function differently, like this:
var getMessage = function() {
...
}
or....
perhaps I am wrong here. for some reason i thought you needed to assign the function to a variable name in order to reference it. My next guess would be that the code which defines your function is somehow not getting into the page. You should use your developer tools (i use the tools in chrome but whatever browser you prefer) and see if you can actually locate the function in the source code of your page.
Upvotes: 0
Reputation: 1187
Syntax error in your function. Try with this.
function getMessage() {
var data = {
message: $("#messageselect").val()
};
$.ajax({
url: "/message",
type: "GET",
data: JSON.stringify(data),
dataType: 'jsonp'
});
$.ajax({
url: "/message",
type: "POST",
dataType: 'json',
contentType: 'application/json',
success: function (data) {
console.log(data);
},
error: function (err) {
console.log("error fetching message");
}
});
}
Upvotes: 1