0

this might be fairly simple but I cant find my way around... I have js (jQuery) code that goes like this:

function publicCheck(research, $clicked) {
var result = null;
$.ajax({
    type: "POST",
    data: "research="+research+ "&action=check",
    url: "ajax_check.pl",
    success: function (msg) {
            if (something ...) {
            result = "ok";
            }
            });
     return result;
     }

=> now why do I get null returned every single time (I know my condition works ok). It must be a scope issue. Why is result not "ok" but is always null even when the condition is valid?

kosta5
  • 1,129
  • 3
  • 14
  • 36

3 Answers3

3

Not trying to be mean, but you should look a bit before asking questions, this is a very common one, here is an answer to a similar question:

Variable scope in Javascript Object

If you have further doubts, we can help you.

Community
  • 1
  • 1
Deleteman
  • 8,500
  • 6
  • 25
  • 39
  • thanks.... I tried looking around but I didnt see any answers to situation similar to mine.... – kosta5 Dec 20 '11 at 12:26
2

$.ajax() is a async call, you can't get the result like that unless you provide a parameter

async: false

This is not recommended, and your browser will freeze until you get a response.

Its better if you provide a callback for return

function publicCheck(research, $clicked, callback) {
    $.ajax({
        type: "POST",
        data: "research=" + research + "&action=check",
        url: "ajax_check.pl",
        success: function (msg) {
            if (something...) {
                callback("ok");
            }
        }
    });
}

USAGE:

publicCheck(research, $clicked, function(status) {
   alert(status); // yeilds ok
});
Abdul Munim
  • 18,869
  • 8
  • 52
  • 61
0

Since you are using an AJAX call it is performed asynchronously. jQuery tends to make using AJAX so simple it's a temptation not to take the time to understand it. Please, take the time to understand the asynchronous nature of AJAX, you will benefit greatly from it.

Tom Hubbard
  • 15,820
  • 14
  • 59
  • 86
  • I understand the AJAX principle more than well my friends :) Using it all the time... I just got to an interesting point in one project: If I want to "reuse" my code I need to call this particular ajax synchronized. These are the situations when I am using this ajax call: 1. (this could be asyn) After $selectElement.change() => perform asynchronous ajax call and put results to HTML 2. (this is where is must be synchronized). Perform an ajax call after submit click but make sure that if ajax call has certain results the page is not posted – kosta5 Dec 20 '11 at 14:45
  • I meant no offence with the comment, more of a warning for anyone who may read it. For number 2, couldn't you have the async callback submit the form, that way you wouldn't risk halting the browser? – Tom Hubbard Dec 20 '11 at 16:30