I'm using jquery to send a JSON to a php file by ajax, all this inside a javascript function but when I use return
to return the json converted to an object it just returns undefined
this is the js
function createFieldSearch (datos) {
var res;
$.ajax({
data: {"datos":datos},
url: 'php/createFieldSearch.php',
type: 'post'
}).done(function (response) {
res = JSON.parse(response);
});
return res;
}
var respuesta = createFieldSearch('{"color":"rojo"}');
console.log(respuesta);
and this is the php
<?php
$datos = $_POST["datos"];
header('Content-Type: application/json');
echo json_encode($datos, JSON_FORCE_OBJECT);
?>
what I want is to store the object in a variable so that I can later use it as I tried to do here
var respuesta = createFieldSearch('{"color":"rojo"}');
console.log(respuesta);
In your function you are using .done for the callback. You can modify the return as follows:
To use the function it would be like this:
and in the php file