Reputation: 187
I have used postman to send the json data to the specifified url.I am getting the requred response that is json in postman.I want to send this json to some other file so i used ajax post method.Ajax post method is not called.My function is not triggering success or error here.
<?php
// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
$value1=json_encode($input);
//echo print_r($value1,1);
?>
<script type="text/javascript">
$(document).ready(function() {
// alert("hello");
var jsondata = <?php echo $value1 ?>;
$.ajax({
url: "/restapi/subscribe.php",
type: "POST",
data: { jsondata:jsondata },
dataType: "json",
Content-Type: "application/json",
success: function() {
alert("data sent!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
</script>
I am sending any of the json data as input.Output also json data that should be posted in subscribe.php.In subscribe.php i have written
<?php
$json=$_POST['jsondata'];
echo $json;
?>
Upvotes: 2
Views: 4625
Reputation: 11
Try to replace Content-Type: "application/json"
with contentType: "application/json; charset=utf-8",
Upvotes: 0
Reputation: 11
You should remove Content-Type: "application/json" from your js code and use next code in your php script:
header('Content-Type: application/json');
echo json_encode($data);
Upvotes: 1
Reputation: 963
Try with below code
<script type="text/javascript">
$(document).ready(function() {
// alert("hello");
var jsondata = <?php echo $value1 ?>;
$.ajax({
url: "/restapi/subscribe.php",
type: "POST",
data: { jsondata:jsondata },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
alert("data sent!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
</script>
and let me know if it work
Upvotes: 5
Reputation: 1381
I think the problem is with Content-Type
Try to replace it with contentType:"application/json"
Upvotes: 0