javascript post not doing function but load url - javascript

I am creating Stratego.
(the error is farther down)
so i am creating the map when the page is loadet whit:
turn = true;
komboType = "2kombo";
GameOpsetning = [];
GameOpsetningEnemy = [];
$(document).ready(function() {
createmap();
}
and then i do some console log to make sure it works..
function createmap () {
if (!GameStarted) {
console.log("GameOpsetning" + GameOpsetning);
if(GetSetup(Gameid)){
console.log("GameOpsetning1" + GameOpsetning);
}
else
{
console.log("GetSetup : error");
}
and here the error comes, it will open the file "game.php" whit no error. but it will not do eny thing in side the post/funcion. It will not do the alert or the if or console.log?
function GetSetup (Gameid) {
console.log("GameOpsetning3: " + GameOpsetning);
if ($.post("game.php", { gameid: Gameid }, function(data) {
alert(data);
var data2 = JSON.stringify(data);
alert(data2);
//var json = $.parseJSON(data);
if (data2.status2 && data2.status2 != "false") {
console.log("data.game: " + JSON.stringify(data.game));
GameOpsetning = JSON.stringify(data.game);
GameOpsetningEnemy = JSON.stringify(data.enemygame);
komboType = data.type;
turn = data.turn;
console.log("GameOpsetning5: " + GameOpsetning);
return true;
}
else
{
console.log("error: ");
return false;
}
})){
console.log("post: done");
}else{
console.log("post: error");
}
console.log("GameOpsetning4: " + GameOpsetning);
}
the console output:
GameOpsetning
GameOpsetning3:
post: done
GameOpsetning4:
GetSetup : error
there is no console errors and the page is return JSON
and it have try ed to do like:
console.log("GameOpsetning" + GameOpsetning);
GetSetup(Gameid);
console.log("GameOpsetning1" + GameOpsetning);
if (CheckGame()) {
then the console log is:
GameOpsetning
GameOpsetning1
GameOpsetning3:
post: done
GameOpsetning4:
GetSetup : error
Sorry for my bad English.

You're testing if($.post("game.php",... What is the result of this if test? Always true. Because anything that is not false, 0 or undefined is true. You're not testing the result of an ajax call, you're testing an ajax call (a function).
Same with if(GetSetup(Gameid)). GetSetup(Gameid) returns : console.log("GameOpsetning4: " + GameOpsetning). if(GetSetup(Gameid)) result is undefined, which explains the GetSetup : error output.
Type this in your console : if(console.log('test')) alert("yay") : it won't alert "yay", it will just log 'test' and return undefined. This is your if(GetSetup(Gameid)).
Same way, if you type if($.post("game.php")) alert('yay'), it will alert yay, because the test is always true, whatever the result of the $.post.

Related

variable is not getting defined even though the code works somwhere else

so i am building a game in three js and trying to make it multiplayer throught socket.io so i am loading all of my characters into an array called players on my server side
and then i pass it to each client when they connect like so
socket.on('addPlayer', function(username) {
players.push(username)
console.log(username + " joined")
console.log("online Users " + players)
socket.broadcast.emit('syncPlayers', players)
socket.emit('syncPlayers', players)
})
and on my client syncPlayers looks like this
socket.on('syncPlayers', function(players) {
players.forEach(function(value) {
if (value == username) {
console.log("not adding " + value + " thats you ")
loadPlayerdata(username)
} else {
console.log("player Online " + value);
newplayer = value;
loadPlayerdata(newplayer)
addPlayer(newplayer)
}
});
})
then it calls this wich sends the server data
function loadPlayerdata(playerName) {
console.log(playerName)
console.log("phase1")
socket.emit('loadPlayerdata', playerName)
}
then this is called and it retrieved the player name and the data of the players location this is were my problem lies
socket.on('loadPlayerdata', function(data, username) {
toMove = threeObjects[username + "Char"]
if (data == "null" || "") {
console.log(username + " is new")
} else {
console.log(username + " Exists")
console.log(toMove)
toMove.position.set(world.spawnPointx, world.spawnPointy, world.spawnPointz)
}
i keep getting Uncaught TypeError: Cannot read property 'position' of undefined
even though i can use this
function addPlayer(playerName) {
var charObjectName = playerName + "Char"
var threeObject = models.tent1.mesh.clone();
scene.add(threeObject)
//threeObject.position.set(world.spawnPointx, world.spawnPointy, world.spawnPointz)
// set reference
threeObjects[charObjectName] = threeObject;
}
btw i have an object
var threeObjects = {};
can someone please explain why it wont work and how to fix it
You can read this answer to understand the difference between dot and brackets notation.
You are getting error because, tomove seems to be undefined and dot notation will throw error if any new user joins and if the object is empty.
Check if this helps. This will assign the object key as username and position as an value which will be array like this,
{"usernamechar": {"position": [x,y,z]}}
socket.on('loadPlayerdata', function(data, username) {
if (data == "null" || "") {
console.log(username + " is new")
} else {
console.log(username + " Exists")
threeObjects[username + "Char"]["position"] = [world.spawnPointx, world.spawnPointy, world.spawnPointz]
}
}

Cannot read property 'finally' of undefined

I can't figure out why I'm getting an
Cannot read property 'finally' of undefined error here..
$scope.saveToDos = function(){
console.log("Save to do was pressed.")
var filteredTodos = $scope.todos.filter(function(todo){
if(todo.edited){
return todo
}
})
console.log("There are " + filteredTodos.length + " edited todos")
dataService.saveToDos(filteredTodos)
.finally($scope.resetTodoState())
}
It errors out on the finally line and I'm not sure why.
The issue can be reproduced cloning Git repo
https://github.com/Velua/To-Do-List
this.saveToDos = function(todos){
var queue = [];
todos.forEach(function(todo){
var request;
if(!todo._id){
request = $http.post('/api/todos', todo);
} else{
request = $http.put('/api/todos/' + todo._id, todo).then(function(result){
todo = result.data.todo;
return todo
})
}
queue.push(request);
})
$q.all(queue).then(function(results){
console.log("I saved " + todos.length + " todos!");
})
}
Thanks!
You aren't returning anything from saveToDos(), so the return value is by default undefined.
You probably wanted to return $q.all(...

Insert a function into javascript object

I tried to insert a function into javascript object but I get
undefined
This is supposed to return a message into div.
I would like to do it the first way, but here is the both way I tried :
var errorMessage = {
empty: function(message){"<div class='field'><div class='csv'><span class='icon'></span><label class='manual' id='error-message'>" + message + "</label></div></div>"
}
};
console.log(errorMessage.empty("Hello"));
I also try this way
function errorMessage(message){
"<div class='field'><div class='csv'><span class='icon'></span><label class='manual' id='error-message'>" + message + "</label></div></div>"
}
console.log(errorMessage("hello"))
You need a return of the value literally.
The return statement ends function execution and specifies a value to be returned to the function caller.
var errorMessage = {
empty: function (message) {
return "<div class='field'><div class='csv'><span class='icon'></span><label class='manual' id='error-message'>" + message + "</label></div></div>";
}
};
console.log(errorMessage.empty("Hello"));
Your function needs to return the value
var errorMessage = {
empty: function(message){
return "<div class='field'><div class='csv'><span class='icon'></span><label class='manual' id='error-message'>" + message + "</label></div></div>";
}
};
console.log(errorMessage.empty("Hello"));

How to respond to SyntaxError in javascript

I get data back from a php server and sometimes it tosses in warnings. These warnings cause the parsing of the response to throw a syntax error which defies all try/catch code I have in place and just stops processing, leaving complex objects in partial states that can't be recovered.
How can I catch these errors? I want to have a chance to get the object back into some steady state.
Ideally, I would not receive answers stating that I should rethink architecture or change php settings. I would like to know how to respond to SyntaxErrors being thrown by JSON.parse().
Thank you,
Jeromeyers
EDIT:
It has come to my attention that the problem is more complex than I originally thought. This is the code that doesn't catch the SyntaxError:
generateSubmissionSuccessCallback: function (reloadOnSave) {
var self = this;
var submissionCallback = function(response) {
var processingError = false;
try
{
var responseObject = {};
if (self.isAspMode())
{
if (typeof response !== 'object') // Chrome auto-parses application/json responses, IE & FF don't
{
response = JSON.parse(response);
}
responseObject = {
entity: response.Payload,
success: response.Success,
message: response.Exception
};
if (jQuery.isArray(response.ValidationErrors))
{
responseObject.message += ' \r\n\r\nValidation Errors\r\n';
for (var i = 0, maxi = response.ValidationErrors.length; i < maxi; i++)
{
var error = response.ValidationErrors[i];
responseObject.message += error.Error + '\r\n';
}
}
}
else
{
responseObject = JSON.parse(response);
}
if (!responseObject || (responseObject.success !== undefined && responseObject.success !== true))
{
processingError = true;
var message = responseObject ? responseObject.message : response;
ErrorHandler.processError(
'An attempt to save failed with following message: \r\n' + message,
ErrorHandler.errorTypes.clientSide,
null,
jQuery.proxy(self.validatingAndSubmittingFinallyFunction, self));
}
else
{
// If this is a parent metaform, reload the entity, otherwise, close the metaform
if (self.metaformType === 'details')
{
if (self.substituteWhatToDoAfterSavingCallback)
{
self.substituteWhatToDoAfterSavingCallback(responseObject);
}
else if (reloadOnSave)
{
self.reloadCurrentEntity(true, responseObject.entity);
}
if (self.doesViewOutlineDefinePostSaveHook())
{
self.viewOutline.functions.postSaveHook(self);
}
}
else if (self.metaformType === 'childDetails')
{
// Reload the Grid by which this form was made
if (self.associatedGridId)
{
Metagrid.refresh(self.associatedGridId);
}
if (self.parentMetaform.associatedGridId && self.childPropertyName)
{
var annotation = self.parentMetaform.getAnnotationByPropertyName(self.childPropertyName);
if (annotation && annotation.hasPropertyOptions('updateParentMetaformAssociatedGrid'))
{
Metagrid.refresh(self.parentMetaform.associatedGridId, self.parentMetaform.entityId);
}
}
if (self.substituteWhatToDoAfterSavingCallback)
{
if (self.doesViewOutlineDefinePostSaveHook())
{
self.viewOutline.functions.postSaveHook(self);
}
self.substituteWhatToDoAfterSavingCallback(responseObject);
}
else
{
if (self.doesViewOutlineDefinePostSaveHook())
{
self.viewOutline.functions.postSaveHook(self);
}
self.disposeMetaform();
}
}
}
}
catch (ex)
{
processingError = true;
ErrorHandler.processError(
"Please immediately inform the authorities that: \r\n\r\n" + typeof response === 'string' ? response : JSON.parse(response) + "\r\n\r\nand:\r\n\r\n " + ex.message,
ErrorHandler.errorTypes.clientSide,
null,
jQuery.proxy(self.validatingAndSubmittingFinallyFunction, self));
}
finally
{
// If we are reporting an error to the user then we can't reset these state variables
// because in the case where this is a child form, the parent will close the form
// before the user has read the error.
if (!processingError)
{
self.validatingAndSubmittingFinallyFunction();
}
}
};
return jQuery.proxy(submissionCallback, self);
}
There's really a lot going on in there, and a lot of structure that it fits into. I don't know if including it will really help.
Assuming you are talking about JSON and it raising an error (and not actual JavaScript being served to the page):
var data;
try{
data = JSON.parse(jsonString);
}catch(e){
// handle the error here, if you like
}
if (typeof data !== "undefined"){
// Yay, we got some!
}
Read more about try...catch at MDN.
For example (from Chrome's console):
> try{ JSON.parse('3/') }catch(e){ console.log('oh no!') }; console.log('OK!')
"oh no!"
"OK!"

Getting UnreadmessagesCount

The question I have here is for some reason when the getInboxUnreadMessagesCount js function is ran then it comes up with a different number then what is there to begin with and keep in mind there is no new message being sent. When I run the php dashboard functions they both are returning the correct numbers but I think the issue lies with the last line of code with the messageTimer
Anybody even have any thoughts onto what it might be? I'm hoping someone can figure it out.
var $messageCountJSON;
var messageTimer = '';
var messageInterval = 5;
//assumed JSON response is {"count":"20"} for example sake.
function getInboxUnreadMessagesCount(displayElementID) {
$.get('dashboard/getInboxUnreadMessagesCount', function (data) {
$messageCountJSON = data;
}, 'json');
if (displayElementID != null && displayElementID != undefined && displayElementID != '') {
//$('#'+displayElementID).html($messageCountJSON);
if (parseInt($('#' + displayElementID).text()) < parseInt($messageCountJSON)) {
$.jGrowl("You have received a new private message!", { theme: 'information' });
$('#' + displayElementID).html($messageCountJSON).css({ "display": "block" });
}
if (parseInt($messageCountJSON) == 0) {
$('#' + displayElementID).html($messageCountJSON).css({ "display": "none" });
}
}
}
function getInboxMessagesCount(displayElementID) {
$.get('dashboard/getInboxMessagesCount', function (data) {
$messageCountJSON = data;
}, 'json');
if (displayElementID != null && displayElementID != undefined && displayElementID != '') {
//$('#'+displayElementID).html($messageCountJSON);
if (parseInt($('#' + displayElementID).text()) < parseInt($messageCountJSON)) {
$('#' + displayElementID).html($messageCountJSON);
}
if (parseInt($messageCountJSON) == 0) {
$('#' + displayElementID).html($messageCountJSON);
}
}
}
$(document).ready(function () {
messageTimer = setInterval(function () { getInboxUnreadMessagesCount('notifications'); getInboxMessagesCount('inboxCount'); }, messageInterval * 1000);
});
//you can optionally kill the timed interval with something like
//$('#pmMessagesIcon').click(function(){clearInterval(messageTimer);})
You are trying to access the message count before it's received:
// Here you create an asynchronous request to the server.
$.get('dashboard/getInboxUnreadMessagesCount', function (data) {
// This section of your code will only run after you get the JSON response
$messageCountJSON = data;
}, 'json');
// Code here will run immediately after the request is fired,
// and probably before the JSON response arrives
You have to move your big if statements to inside each $.get() callback function.

Categories

Resources