Hi I am just a little bit frustrated and also I hate Javascript in any form but please someone can tell me why is this not working? :C But If I mess up something or I just return a simple string then its working. Its only when I try to access sg from $decoded.
PHP
header("Content-Type: application/json"); // Setting content type to application/json
function JsonError($msg1, $msg2) // Error handler
{
die(json_encode(array("error" => $msg1, "errorMessage" => $msg2)));
}
if(strcasecmp($_SERVER["REQUEST_METHOD"], "POST") != 0) // Throw error if request is not POST
{
JsonError("exception", "Not valid request method!");
}
$contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : "";
if(strcasecmp($contentType, "application/json") != 0) // Throw error if content is application/json
{
JsonError("exception", "Not valid content type!");
}
$content = trim(file_get_contents("php://input")); // Getting rid of any whitespace and getting that juicy json content
$decoded = json_decode($content, true); // Decoding json content
die(json_encode(array("status" => "FUCK ME", "title" => $decoded[0]["uri"])));
JS
// Function to handle errors and responses
function HandleAjax(resp)
{
console.log(resp);
if(typeof(resp) == "string")
resp = JSON.parse(resp);
if (resp.error)
{
alert(resp.error + " " + resp.errorMessage);
}
}
/////
//////////// TEST SECTION /////////////////
$("#submit").on("click", function(e)
{
e.preventDefault();
alert($("#val1").val());
var data = [
{"uri":"utalasdata"},
{"currpass":$('#utalas .paytoform input[name=currpass]').val()},
{"payto":$('#utalas .paytoform input[name=payto]').val()},
{"amount":$('#utalas .paytoform input[name=amount]').val()}
];
$.post("ajax.php", JSON.stringify(data) , HandleAjax, "application/json");
});
//////////////////////////////////////////
HTML
<form method="POST">
<input type="text" name="val1" id="val1">
<input type="button" id="submit" value="subme">
</from>
<script src="js/vendor/jquery-3.5.1/jquery-3.5.1.min.js"></script>
<script src="js/test.js"></script>
Thanks for everyone in advance!
2
Answers
The solution was that I changed my Jquery code to this...
Funny :C
this will not solve your problem but will help you understanding what is happening