I am trying to send a json object to a php page demo.php using an ajax request
<script type="text/javascript" charset="utf-8">
$(document).ready(function ()
{
var data =
{'name':'Sam','ID':'1345'};
var test = {}
test["data"] = JSON.stringify(data);
$("#btnsend").click(function()
{
$.ajax({
type:"POST",
url:"/demo.php",
dataType:'json',
data:test,
success: function(data)
{
console.log('success');
}
error: function()
{
console.log('failure');
}
});
});
});
</script>
This is what I tried in jQuery,but it is not rendered on my php page.In php I tried the following:
<html>
<?php
$json = json_decode(stripslashes($_POST['data']), true);
echo var_dump($json);
?>
<body>
Hello World !!!
</body>
</html>
But it is printing a failure in console. Please help me with this.
Edit: My initial answer was wrong, the reason you get to the error
function, is that you have specified:
dataType:'json',
So jQuery expects the output of your php script to be valid json. It is not, you are returning text / html so that is why your success
function is never reached.
The way you have setup your php script (outputting html), you probably should just remove:
dataType:'json',
and then you will get to your success function.
By the way, nothing is rendered on your page until you do something (show...) the data
variable in your success
function:
success: function(data) {
console.log('success');
$('#some_element').html(data); // to put the output in #some_element
}
And in your php script you should only send back / echo out what you want to display in your html element, so no html
or body
tags.