JavaScript variable scope - javascript

Here's my code
errors=0;
$(document).ready(function () {
var chk=$("#usnm").val();
$.post("register.php",{'chkuser':chk},function(data){
if(data==" Username already exists.Choose a new one"){
errors++;
alert(errors);
$("#alerts").html(data);
}
});
if(errors==0){
alert(errors+"post");
}
});
Here, the first alert gives me a "1" whereas the second alert runs, so therefore it give me '0post' . What i'd like to know is: How is the value of the variable errors, changing to 0 all of a sudden after being 1 ?
Thanks

Change errors=0; to var errors=0;
and put the error check inside the $.post function:
$.post("register.php",{'chkuser':chk},function(data){
if(data==" Username already exists.Choose a new one"){
errors++;
alert(errors);
$("#alerts").html(data);
}
if(errors==0){
alert(errors+"post");
}
});

jquery.post is called asynchronously. you might be debugging it locally otherwise the second alert would go on the first place. anyways because it runs async the value is different inside and outside the post function

Related

JavaScript scoping rules possibly being tampered with by jQuery/Ajax?

Note: I will specify the workaround I found for this issue, but I still do not understand why the first method did not/does not work for me.
I have a jQuery script for my HTML file that is supposed to send a number to a server via an ajax request. Here is the way my script is laid out:
// Beginning of script
var number = 0; //ensure that the variable has global scope
// Send number to server on click of button (which has type 'button' not 'submit') in HTML document
$(document).ready(function() {
$( "#button" ).click(function() {
number = 0; // reset the value of the number every time the button is clicked
// A function runs here and returns a number, and it has a callback (which gets passed that returned number).
// Callback is defined as follows:
function callback(returnedNumber) {
if (condition == true) {
alert("Condition passes");
} else {
// assign returnedNumber to 'number', then initiate ajax POST request to server
number = returnedNumber; // just assume returnedNumber is 23
}
// Notice that the ajax request is NOT initiated as part of the else statement.
$.post("test.php", { key: number }, function(data) {
$( "#resultDiv" ).html(data);
});
}
});
});
Now here is what the "test.php" file on the server looks like:
<?php
echo var_dump($_POST);
?>
When the condition in the callback does not pass, var_dump() shows that the value of $_POST["key"] is still 0 instead of 23, and this is where I get confused. My understanding of JS scoping rules is that once a variable is declared globally, functions can modify its value as long as the var keyword is not used to re-declare the variable within the function. I thought this would mean that using my callback to reassign the value of number would also change the value of the global variable number, thus allowing me to send it to the server without the ajax request being a part of the else statement that reassigned the variable. So, what part of that do I have wrong? If there is documentation that will help clarify my misunderstanding, please provide a link. :)
My Workaround: I simply appended the ajax POST request to the else statement, and that worked as I wanted it to. But I do not understand why the ajax request does not take the updated value of number when the request is not part of the else statement.
Thanks!
As you can see in this example, you are right about the scope part, so there must be something else going wrong, probably in the callback. Perhaps you're trying to get the number in an async-way, posting the data before you've gotten a response?
var condition = false;
var number = 0; //ensure that the variable has global scope
$("#button").click(function() {
number = 0; // reset the value of the number every time the button is clicked
function callback(returnedNumber) {
if (condition == true) {
//alert("Condition passes");
} else {
// assign returnedNumber to 'number', then initiate ajax POST request to server
number = 23; // just assume returnedNumber is 23
}
condition = !condition;
$("#result").text(`Result: ${number}. Setting condition to ${condition}`);
}
// Call the callback as an actual callback
setTimeout(callback, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">Click...</button>
<div id="result"></div>

WebMethod Call Within a WebMethod Call

I need to call a WebMethod that returns an integer, this integer is then displayed to the user in a confirm message. If they confirm then I need to call a second WebMethod and then alert them of the result via an alert message.
When I do this, everything works fine except for the second success function. That function is never reached, and the user is never alerted as a result.
This is example JavaScript of my situation:
$( "a" ).live( "click", function() {
PageMethod.GetCount(OnSucceed, OnFail);
});
OnSucceed(result)
{
var retVal = Confirm(result);
if(retVal == false)
return false;
PageMethod.Create(Succ, OnFail); //Produces the correct files
}
function Succ(resultStr)
{
alert(resultStr); //This is never reached
}
function OnFail(error)
{
alert(error);
}
Well .. It can be for different reasons
You have an error calling the second PageMethod. You can check your console to see if you have "500 INTERNALL ERROR".
The problem is before calling the page method but guessing you have already checked your PageMethod this is not likely.
You are calling PAGEMETHODS from your JS codes, but you mentioned WebMethods which are 2 different things. Make sure what is that are
you really calling.
your PageMethod/WebMethod does not return anything

Why the variable value from is not accessible in following code snippet?

I've following Javascript code snippet :
authData=ref.getAuth();
if(authData == null){
//TODO find an elegant way to manage authorization
// window.location = "../index.html";
} else {
ref.child("users").child(authData.uid).on("value", function(snapshot){
$( "span.user-name").html(snapshot.val().displayName);
loggedInUser.displayName = snapshot.val().displayName;
//alert("Name inside : "+loggedInUser.displayName);
//Here it displays the value
});
}
alert("Nameada is out : "+loggedInUser.displayName);
//Here it shows 'undefined'
why?
I want to use the variable value loggedInUser.displayName where did I shown alert.
Can someone please help me in accessing the value and displaying the alert?
Thanks.
Your final alert is executed when the callback function (function(snapshot){ ... }) has not yet been called. Note that the callback function is called asynchronously, so it only gets executed after the currently running code has completed and the value event is triggered.
This also explains why the inner (commented out) alert does work. Just realise that this piece of code (the call back function) is executed later than the other alert, even though it occurs earlier in your code.
You could "solve" it by calling another function from within the call back, like this:
authData=ref.getAuth();
if(authData == null){
//TODO find an elegant way to manage authorization
// window.location = "../index.html";
} else {
ref.child("users").child(authData.uid).on("value", function(snapshot){
$( "span.user-name").html(snapshot.val().displayName);
loggedInUser.displayName = snapshot.val().displayName;
whenUserLogged();
});
}
function whenUserLogged() {
alert("Name : "+loggedInUser.displayName);
// anything else you want to do....
}
Some suggestions for improvement
Don't use too many global variables (in your code all of them are global), and instead pass variables as function arguments.
You may want to look into promises.

call function using if statement

I want to be able to call a function within an if statement.
For example:
var photo = "yes";
if (photo=="yes") {
capturePhoto();
}
else {
//do nothing
};
This does nothing though. The function is clearly defined above this if statement.
Edit: Wow, downboated to hell! capturePhoto(); was just an example function that didn't really need any more explanation in this scenario?
That should work. Maybe capturePhoto() has a bug?
Insert an alert() or console.log():
var photo = "yes";
if (photo == "yes") {
alert("Thank you StackOverflow, you're a very big gift for all programmers!");
capturePhoto();
} else {
alert("StackOverflow.com must help me!");
}
I'm not seeing any problems here. I used this code and the function call worked. I kept your code and just added a function called capturePhoto().
Are you sure that the code you're using to call the function is firing?
var photo = "yes";
if (photo=="yes")
{
capturePhoto();
}
else
{
//do nothing
};
function capturePhoto()
{
alert("Pop up Message");
}
You probably missed something, a quotation, a semicolon or something like that. I would recommend you to use a debugger like Firebug or even Google Chrome's Web Developer Tool. You will know what's wrong with your code and where it is wrong.
You may take a look at this live code that your code above works: http://jsfiddle.net/ZHbqK/
The code looks fine to me (except you don't need the ; at the end of the last line). Check your error log; perhaps the browser thinks capturePhoto is not defined for some reason. You can also add alert statements to make sure the code is actually running:
var photo = "yes";
alert('Entering if statement');
if (photo=="yes") {
alert('then');
capturePhoto();
} else {
alert('else');
//do nothing
}
When you encounter a situation where it seems like a fundamental language feature is not working, get some more information about what is going on. It is almost never the platform's fault. It is occasionally a misunderstanding of how the feature works (e.g. why does parseInt('031') == 25 ?). It is usually a violation of an assumption you're making about the code that isn't holding up because of a problem elsewhere.
You should also consider using true and false instead of strings that could be manipulated depending on input.
If I had to correct the following code, then I should've done it like this;
var photo = true; // Will capture picture.
if (photo) { // 'true' is a truthy value.
capturePhoto();
} else {
// Do nothing
}
The code that you posted does work.
I copied it and tested it.
Demo: http://jsfiddle.net/Guffa/vraPQ/
The only thing wrong with it that I can see is a semicolon after the closing bracket, but that is only a style problem. It will form an extra empty statement, but that doesn't cause any problems.

Variable scope issue on returning value from $.post

I have one of those pesky variable scope problems with $.post. Before submitting a form, I want to first check if the user has edited the content. I return false if the user hasn't.
I've looked at a bunch of different examples on Stackoverflow and the general way to do this is to create a function and a callback function inside that function to handle the callback. My problem is that the when I call getReturned below, the callback does not get implemented (know this because form gets submitted and I've tried an alert). Btw, alert("No changes were made so text was not submitted."); gets called successfully.
What am I doing wrong?
function getReturn(callback, id, old_variable){
var return_value = "ERROR";
$.post('myURL', {"id" : id},
function(data) {
var text_from_server = $.trim(data[0].note_text);
if (old_variable == text_from_server){
alert("No changes were made so text was not submitted.");
return_value = false;
callback(return_value);
} else {
return_value = true;
callback(return_value);
}
},
"json"
);
};
var id = 123;
var old_variable = "foo";
getReturn(
function(return_value){return return_value;/*alert("SUCCESS!");*/},
id,
old_variable
);
Since you are making an asynchronous request to test if the value has changed you have to always return false from your submit handler. In the callback, if the form was edited, you would then manually submit the form using form.submit(). Something like this:
getReturn(
function(return_value) {
if (return_value) {
$("#myForm").submit();
}
},
id,
old_variable);
return false;
You don't understand asynchronous execution. You can not return anything from $post! Do not forget that. All you can do is trigger execution of something - you can try to set a variable flag, but it won't help you. You also need to trigger the execution of a function that does something with that flag, and you have to call that function from inside $post.
The function you are sending in as the callback returns a value. But it does not return the value to anyplace. You are calling it inside $post, and it's returning the value inside $post - which does nothing useful for you at all since you aren't doing anything with the return value.
I would tell you how to change it, except you have not said what you want to do with this return value.

Categories