Undefined in the PHP return to the front with JSON

0

I am trying to create a session validation with Jquery, AJAX, JSON and PHP. I have this code.

This is the generic function that I invoke in each query, I modified the code because apparently I was doing the return inside the AJAX function, I created a variable to store the response and I have returned the variable, but it follows without working, if I do the console.log within the .done correctly launches the response, but when I exit the AJAX, I lose the value of the variable.

  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);
    return returnValue;
  }

This is the invocation form, in the data comes a series of validations of the inputs:

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

All this is my initial code in PHP with which I receive the data:

require 'connection.php';
date_default_timezone_set('America/Mexico_City');
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 series of queries and ciphers depending on the condition, I get a Y for successful validation or an N for a login failure that encapsulates an array and passes it to JSON format and return it.

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

If in the AJAX success I make a console.log(response.resp); , the character returned by the PHP returns to me well. But if I try to make a console.log(answer) out of the AJAX function, in the place where it was invoked, it returns undefined . I'm supposed to be giving it return response.resp I would have to return the lyrics.

What is failing me: (

    
asked by Alberto Siurob 20.06.2017 в 21:44
source

1 answer

1

Remember that ajax is an asynchronous function, therefore the value you are waiting for return response.resp may not return it immediately and therefore the value of your answer may be undefined.

The best thing you can do is add the async : false parameter to ajax so that the ajax process and the query to your data are synchronous and wait to finish the process to continue with the procedure.

    
answered by 20.06.2017 в 21:46