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: (