0

This is a question where my overall approach might be wrong, but I hope you can help out.

I have a function, where I want to make a call to my server. I call that function cleanString. That cleanString function calls the server, using an AJAX call.

I know that AJAX is async, so I set the async: false value of my AJAX call.

But right now, I get undefined from the cleanString method, no matter what I do. As you can see in the method, I even return a hardcoded string just to test it.

My code calling the function:

         var serverName = cleanString(file.name);
            fileList[file.name] = { "serverFileName": serverName, "fileName": file.name };
            console.log(fileList);

This is the cleanString function:

function cleanString(str) {
    $.ajax({
        url: '/SingleLetter/StripString',
        type: 'POST',
        async: false,
        data: {
            'str': str
        },
        dataType: 'json',
        success: function (data) {
            return 'abekat2';
        }
    });
}

So basically: how do I make sure that the variable serverName get's the value "abekat2", from the cleanString method?

Lars Holdgaard
  • 9,496
  • 26
  • 102
  • 182
  • the function cleanString is not returning any value, you have to return a value outside the ajax call ;) – Alessio Jun 21 '14 at 13:37
  • @Alessio that changes nothing unfortunately it seems - my serverName is still undefined if i say data.str :) – Lars Holdgaard Jun 21 '14 at 13:38
  • read carefully the question Rory suggested, it contains a great explanation – Alessio Jun 21 '14 at 13:42
  • 1
    @LarsHoldgaard As Alessio said Felix Kling has a great explanation of the problem and the best pattern to use in this situation in the question I linked. Using `async: false` is never the answer. It has been deprecated, and will be removed from the source in the next version or two of jQuery, so don't rely on it. – Rory McCrossan Jun 21 '14 at 13:45
  • 1
    The `return` statement applies to the immediate `function` it's within. That would be `success:` rather than `cleanString`. And, your code isn't calling `success` directly, so it doesn't get the `return` value. As `Alessio` was hinting, you have to move the `return` out of the `success`. One way to do that: Define a `var res` or similar before `$.ajax()`, set `res = data;` in `success`, and `return res` at the end. – Jonathan Lonowski Jun 21 '14 at 13:45
  • @RoryMcCrossan I agree there are better options than `async: false`. But, the option isn't itself deprecated (unless the jQuery team hasn't [updated the docs](http://api.jquery.com/jQuery.ajax/) to reflect it), using it in combination with `$.Deferred()` methods is. – Jonathan Lonowski Jun 21 '14 at 13:47
  • @JonathanLonowski true, my bad. Still, it's use should be avoided. – Rory McCrossan Jun 21 '14 at 13:49

0 Answers0