-1

I´m developing a session system with Jquery, AJAX, PHP and JSON.

This is my generic AJAX function:

function ajaxConn(incomingUrl,incomingData)
  {
    var returnValue;
    $.ajax({
      url:'backend/'+incomingUrl,
      method:'POST',
      data: JSON.stringify(incomingData),
      contentType: "application/json; charset=UTF-8"
    }).done(function(response){
          returnValue = response.resp;
    });
    console.log(returnValue);
  }

This is the call of the function and the storage of result to be used. variable data has inputs values previously filtered and validated.

var data = {user:user,pass:pass};
var answer = ajaxConn('core_files/startSession.php',data);
console.log(answer);

This is the headers of my PHP code

require 'connection.php';
mysqli_set_charset($conn,"utf8");
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);
$user =  mysqli_real_escape_string($conn,$data["user"]);
$pass =  mysqli_real_escape_string($conn,$data["pass"]);

$response = array();

After a lot of validations PHP returns a word depending of the session case: It can returns

$response["resp"] = 'N';
echo json_encode($response); 

for wrong session or

$response["resp"] = 'Y';
echo json_encode($response); 

for success session.

The problem is coming on the value return, if I do console.log(returnValue) inside the AJAX call, it returns the correct word from PHP. But, if I exit from AJAX call and I try to do the same out the funcion it returns me undefined. Actually, in the return of the function it returns me undefined too, outside the

ajaxConn();

What I'm doing wrong

Alberto Siurob
  • 151
  • 1
  • 3
  • 11
  • Ajax is asynchronous. So even you are using '=' sign, It doesn't mean you get a result. $.deferer will help you – SouXin Jun 20 '17 at 20:43
  • Don't do like that, you print variable before ajar request finishes, that's why it's undefined. Put console.log into function and you will see result. If you want to return value there is only one way, make ajax request synchronous. But I don't recommend to do so. – Alex Kapustin Jun 20 '17 at 20:47
  • For what it's worth, your ajaxConn should probably accept a third param that's a callback function that gets called in success. I wouldn't use it personally. It's going to limit you the first time you run into an edge case. – Matt Jun 20 '17 at 20:48

1 Answers1

1

console.log it inside the .done. Your current console.log is running immediately before the ajax request completes and the value is not yet defined.

Matt
  • 5,315
  • 1
  • 30
  • 57