Jquery GET in plain javascript [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I call my_function on form submit. The function looks inside a text file for the number entered by the user in my_input. If this number does not exist, the function pops an alert and should stop form submit.
My problem: the alert is shown, but when I close it, the form gets submitted. My problem is similar with this thread: How do I return the response from an asynchronous call?
One of the solutions there is to do the GET in plain javascript. Can someone help please? This is too advanced for me.
function my_function() {
$.get("http://www.example.com/file.txt", function(contents) {
var my_number = document.getElementById("my_input").value;
var hasString = contents.includes(my_number);
});
console.log(hasString); // **ALWAYS RETURNS UNDEFINED**
if (hasString == false) {
alert('Number does not exist in text file!');
return false;
}
}

hasString is a local variable of the callback function provided to $.get as second argument. This is why it's undefined outside said function. Note just moving the variable declaration to the outer scope won't fix the problem, as the callback function will be executed after the check hasString == false anyway (it will be executed when the get request finishes).
Answering your question more directly: either perform the get request synchronously (and properly declare the variable in the scope you need to use it) or restructure your code to use the information retrieved by the get request only inside the callback. Read the post #abc123 mentions for more information.

Related

JS error. Variable boolean value not changed [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I need to implement jQuery code on Facebook API event. Facebook API code must be placed before html code and also not inside jQuery function and calling jQuery function would be anonymous function , so I decided to create global variable, the true value of which would call the function. The problem is that the value of variable is not changed thought alert() function works in the same place of code.
Variable is defined at the very top of code just after script opens
var not_logged_show_wall = false;
so as part of Facebook API there is else condition and alert works inside it, but value of the variable is not changed
else{
alert();
not_logged_show_wall = true;
}
I checked that it's not changed by another alert in js code after html code(while the code higher was before). Also tried the same thing with $(document).ready()
No error in console log. What is wrong?
My guess (without fully seeing the code) is that the facebook code is wrapped in an immediately invoking function so the variable is hoisted to the top of that function and not to the window so it's actually two different variables.
if you really want it to be global (which is usually not the best) you can explicitly add it to the window, ie.
window.not_logged_show_wall = false;
else{
alert();
window.not_logged_show_wall = true;
}

javascript variable value lost when outside object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
This may sound a newbie question but I'm having really hard time with variable scopes in Javascript.
I have the following JS snippet:
<script>
window.IDFVPlugin.getIdentifier(function(result){ uuid = result; });
alert(uuid);
</script>
I want to use the variable uuid anywhere in the script outside the window object. uuid returns the correct value only when inside the object and the value is lost when outside. So the alert above will log an undefined variable error.
You use a callback function. Result should be used inside of callback body. If you try to use it immediately after main function call - it will not be yet available
window.IDFVPlugin.getIdentifier(function(result){
uuid = result;
alert(uuid);
});

JavaScript function returns empty string when a value is expected [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
There's probably an obvious mistake somewhere, but I just can't out find what's wrong.
I'm trying to retrieve data from an api, and use the js-function below to get it. If I do an alert(key) on the data inside the $.get-function, it alerts the correct data.
function getApiKey(company, password) {
var url = "http://myapi.com/" +company+ "?password=" +password;
var key = "";
$.get(url).done(function(data) {
key = data;
//alert(key) returns the correct data
});
return key;
}
However, I need to use the function in a different file, and that's where it doesn't work. When I do
var key = getApiKey("company", "password");
alert(key);
key is empty.
The $.get command is asynchronous, meaning that your function returns key with its initial value of "", then later when the async callback fires, it runs key=data.
You should read up on asynchronous behaviour in javascript - for a solution, you'll need some way to get the data back to the place of the call asynchronously. One such option is a promise.

Trying to access a variable inside a jquery function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to access a variables inside a $.post jquery method. The code I have so far is below:
var fromDatabase;
$.post( "../read.php", function( data ) {
fromDatabase = JSON.parse(data);
console.log(fromDatabase); //this works fine
return fromDatabase;
});
console.log(fromDatabase); // but this gives me 0.
I am trying to get the from database variable so i tried to declare it outside the function to no avail.
Thank you.
You can't - you must continue program execution from within the callback, not immediately after the asynchronous $.post call.
You cannot return from an asynchronous function, that's the nature of asynchronicity. Instead, after your value is available (the callback function is called) you must work with the data within the scope of that function.
Perhaps a good starting point would be some Ajax tutorial. If you want more, simply google for JavaScript async.

Ajax .responseText is available in alert but does not get saved in variable or return [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
var response_var=""; // Added this line for debugging
ajax.onreadystatechange=function()
{
if(ajax.readyState==4 & ajax.status==200)
{
response_var=(ajax.responseText);
alert(ajax.responseText); // This alerts properly (some text).
return (ajax.responseText); // This is returning as undefined
}
}
return response_var; // This is empty if I add the line 1, if not in console it gives error response_var is not defined.
Why does not the response is getting stored in the variable or returned? I guess the scope of response_var ends within the onreadystatechange function so I tried return. But the value is undefined.
Ajax function always work out of sync with normal code flow ,hence the name "Asynchronous JavaScript and XML" .For Ajax required events you should not rely on return ,rather do your task immediately when you get your response from AJAX.

Categories

Resources