-3

I am having problems using variables inside functions. So I have code:

functions.js:

function foo (callback){
    $.ajax({
    type:"POST",
    url:"ajax/companyInfo.php",
    data: dataString,
    success: callback
    });//end ajax
    alert (dada);
}

function mycallback (result){
    array=result.split('/');
    alert(dada);
}

invoice.php:

var array = [];
var dada="";
$('#next1').on('click', function(){
    dataString='company= '+$(this).closest('.inside').find('select').val(); // this is just for ajax
    resizeall($(this), 200, 100); //this is function that works and has no problem
    foo(mycallback);
    console.log(array);
});//end on click function

It says:

Uncaught ReferenceError: dada is not defined functions.js:41
Uncaught ReferenceError: dada is not defined functions.js:46

I think it's might be related to closures isn't it. What is going wrong?

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
funny
  • 83
  • 1
  • 14
  • 2
    `dada` seems out of scope, but in essence, this is yet another duplicate. Once you go asnyc, there's no way back; you have to use callbacks or promises. Read about Continuation Passing Style (CPS), it will clear up your mind. – elclanrs Oct 24 '14 at 18:15
  • even if you think it is duplicate, i was not lazy to read anything but it couldn't solve my problem. please help me out with this example. regarding CPS, i will read it now – funny Oct 24 '14 at 18:18
  • 1
    This *is* a duplicate. One of literally (and I mean literally) thousands on this site. Your mistake is to think that lines of code after an async call like `.ajax()` would also be executed after that call returns. They are not. They are executed *before* that call returns. *Everything you want to do after the call must go into the callback function.* – Tomalak Oct 24 '14 at 18:22
  • i got it, but how to use this dada variable inside callback? – funny Oct 24 '14 at 18:25
  • Does changing `var dada="";` to `window.dada="";` fix the problem? – Clayton Leis Oct 24 '14 at 18:29
  • I'm not sure it's something that can be fully understood in an afternoon for the first time, it may take hours, or days to change your mindset to work with async code, that's why there are so many duplicates. – elclanrs Oct 24 '14 at 18:30
  • Clayton, yes it fixed – funny Oct 24 '14 at 18:35
  • possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – TylerH Jun 29 '15 at 13:57

2 Answers2

1

Kind of hard to debug since I can't see all of the invoice.php or functions.js The line numbers you report (41 and 46) indicate that there is more to functions.js then what you pasted. But I'll give a hack you could try

invoice.php

var array = [];
window.dada="";
$('#next1').on('click', function(){
    dataString='company= '+$(this).closest('.inside').find('select').val(); // this is just for ajax
    resizeall($(this), 200, 100); //this is function that works and has no problem
    foo(mycallback);
    console.log(array);
});//end on click function

functions.js

function foo (callback){
    $.ajax({
    type:"POST",
    url:"ajax/companyInfo.php",
    data: dataString,
    success: callback
    });//end ajax
    alert (window.dada);
}

function mycallback (result){
    array=result.split('/');
    alert(window.dada);
}
davelpz
  • 151
  • 3
  • ok but i was creating global variable, why it didn't work? as i understand when a global variable is set, it's added to the window object... – funny Oct 24 '14 at 18:39
  • @funny Don't work with global variables. That's cheating. Also, it's very bad style. – Tomalak Oct 24 '14 at 19:03
  • @funny are you sure your variable was global and not defined within a $(document).ready(...) closure? – Clayton Leis Oct 24 '14 at 19:11
0

Here is what your setup should look like.

function getCompanyInfo(companyName) {
    return $.post("ajax/companyInfo.php", {
        company: companyName
    }).then(function (rawData) {
        return rawData.split("/");
    });
}

$('#next1').on('click', function() {
    var companyName = $(this).closest('.inside').find('select').val();

    resizeall($(this), 200, 100);

    getCompanyInfo(companyName).done(function (array) {
        console.log(array);
        // everything else you want to do with the array goes here
    });
});

Read up on jQuery Deferreds to find out what .then() and .done() do.

Final tip: If you want to update data on the server, use a POST request. If you want to fetch information from the server, use a GET request. The .post() in my code above is there because you used it in your code. It's semantically wrong and you really should change it to .get().

Tomalak
  • 332,285
  • 67
  • 532
  • 628