The jQuery code is sending the POST data as a JSON string, but your PHP code is looking for standard key-value pairs.
You can change the Ajax call to send in key-value format. I can't see what utnew
refers to in your code, usually that would be a Javascript object or the result of serializing an HTML form with $.serialize()
:
$.post("myurl.php", utnew, "json")
.always(function(response) { console.log(response); }
Or you can change the PHP side to expect a JSON-encoded string in the POST payload rather than encoded key-value pairs:
...
$data = json_decode(file_get_contents('php://input'));
if (isset($data['id'])) { ... }
Whichever you choose, the problem you're having is the Ajax call sending a JSON-encoded string as the POST payload, but PHP expecting key-value pairs in $_POST
.
The "json"
data type argument to jQuery $.ajax
or the shortcut method $.post
tells jQuery what format to expect the return value in, so your PHP code should return a JSON-encoded string. Your PHP code is sending back a plain string, so you should either tell jQuery to expect that:
$.post(url, data, "text")
or have PHP send back a proper JSON-encode object:
echo json_encode(["result" => "success"]);
If you have PHP error logging on (you should) to a file you can debug your API endpoint with error_log
, i.e. error_log(print_r($_POST,1));
would have given you some clues.
No comments:
Post a Comment