I am getting undefined from an ajax call while the variables I pass through exist for sure.
This is my ajax function:
function setMessages(roomId, username, message){
$.ajax({
type: "get",
url: "http://www.sinansamet.nl/chatdistract/ajax/setMessages.php",
data: { roomId:roomId, username:username, message:message },
success: function(html) {
strReturn = html;
}
});
}
My PHP:
<?php
$roomdId = $_GET['roomId'];
$username = $_GET['username'];
$message = $_GET['message'];
echo $username;
?>
Calling ajax:
$(document).on("click", "#messageSubmit", function(){
var username = window.localStorage["username"];
var message = $("#message").val();
alert(setMessages(roomId, username, message));
alert(roomId + username + message);
});
The first alert returns undefined. No matter which variable I use. The second alert returns all 3 variables like they are supposed to be. So they do exist for sure. I am using phonegap for this but it does the same on desktop browser.
The function does not return a value, and even if it did, ajax is async, so you'll have to wait until the data is returned before you can use it :
function setMessages(roomId, username, message){
return $.ajax({
type: "get",
url: "http://www.sinansamet.nl/chatdistract/ajax/setMessages.php",
data: { roomId:roomId, username:username, message:message }
});
}
$(document).on("click", "#messageSubmit", function(){
var username = window.localStorage["username"],
message = $("#message").val();
setMessages(roomId, username, message).done(function(data) {
alert(data);
});
});
try:
function setMessages(roomId, username, message){
var strReturn = '';
$.ajax({
type: "get",
url: "http://www.sinansamet.nl/chatdistract/ajax/setMessages.php",
data: { roomId:roomId, username:username, message:message },
success: function(html) {
strReturn = html;
},
async: false
});
return strReturn;
}
Try the following
function setMessages(roomId, username, message){
return $.ajax({
type: "get",
url: "http://www.sinansamet.nl/chatdistract/ajax/setMessages.php",
data: { roomId:roomId, username:username, message:message },
success: function(html) {
strReturn = html;
}
});
}
<?php
$roomdId = $_GET['roomId'];
$username = $_GET['username'];
$message = $_GET['message'];
echo $username;
?>
$(document).on("click", "#messageSubmit", function(){
var username = window.localStorage["username"];
var message = $("#message").val();
setMessages(roomId, username, message).done(function (){
alert(strReturn);
alert(roomId + username + message);
});
});