0

I Have this piece of code

(function(){
    $.ajax({
        type: "POST",
        url: "g.php",
        data: {g:""+a}
    }).always(function(a,b,c){
        console.log(c.responseText);
        if (c.responseText.length < 45 ) {
            return "error";
        } else return (c.responseText);
    });
}())

If I try to assign it to a variable undefined is returned; however, if I console.log it, the expected value is returned... its very confusing...

How can i extract the response, I read somewhere about callbacks however it didn't help. I tried restructuring the code into many fashions with no result.

-- Why does console.log print the right result vs undefined with any other function?

  • I don't see where you are assigning any variable, but the `return` statements are certainly suspicious. – Felix Kling Jun 01 '16 at 15:59
  • The code above is an ajax call that either returns error if the response from the server is shorter than 45 characters... –  Jun 01 '16 at 16:00

1 Answers1

0

I am not sure, but check if it will work with dataType json

 $.ajax({
        type: "POST",
        url: "g.php",
        dataType: 'json'
        data: {g:""+a}
    })
Elnoor
  • 3,401
  • 4
  • 24
  • 39
  • does not work, it invalidates the code –  Jun 01 '16 at 16:03
  • Your'e also missing a comma, after the datatype –  Jun 01 '16 at 16:03
  • Opps, yeah sorry, comma should be there. And also you need to parse json before using it – Elnoor Jun 01 '16 at 16:04
  • Welp... my question was marked as a duplicate even though the other users question is of a different context...... i read that question before asking this one. –  Jun 01 '16 at 16:06