Vasilen Donchev
Vasilen Donchev

Reputation: 1035

jquery.get() - problem using data as global variables

Well, I've read a lot in the Net, bust still haven't found a solution to my problem: I need to check if the content of a file is "nok" or empty ("") using the jquery method get. One of the things I tried (didn't work of course, but shows clearly my idea) is:

$(document).ready(function(){
$("#submit").click(function(){
...
var captchacheck="";
$.get("/form.php", function(data){captchacheck=data;}));
if(captchacheck == "nok") hasError=true;
...

So please tell me how really to store the string from data into a global variable (or another suitable structure) so that the plain text nok could be used in if-clauses.

Upvotes: 3

Views: 9397

Answers (2)

Mark Snidovich
Mark Snidovich

Reputation: 1055

If you declare the variable outside of the ready function, it will be a global. Assigning it a value without using var will affect the global variable. This should work:

var captchacheck=false,hasError=false;
$(document).ready(function(){
  $.get("/form.php",{},function(data){captchacheck=data;});
  });
//later...
if(captchacheck == "nok"){ hasError=true; }

Upvotes: 0

BalusC
BalusC

Reputation: 1108722

Use window.variablename or in jQuery style $.variablename to assign and access global variables.

E.g.

$(document).ready(function() {
    $.captchacheck = "";
    $("#submit").click(function() {
        $.get("/form.php", function(data) {
           $.captchacheck = data;
        });

        hasError = ($.captchacheck == "nok");

Upvotes: 4

Related Questions