I’m trying to pass to values from input text to ajax but I keep getting null
when I decode it.
Here is what I have written.
<script>
function myAjax()
{
var username = $("#username").val();
var orderid = $("#orderid").val();
$.ajax({
type: "POST",
url: 'jumper.php',
data:{ data1:{"username": username, "orderid": orderid}},
datatype: 'json',
success:function(html)
{
document.getElementById("test").innerHTML = html;
}
});
}
</script>
<body>
<input type="text" id="username" name="username">
<input type="text" id="orderid" name="orderid">
<button id="btnkey" class="button" style="vertical-align:middle" onclick="myAjax();return false;"><span>SEARCH</span></button>
<div id="test" class="test"></div>
</body>
and to decode:
$vars = (json_decode($_POST['data1']));
echo $vars;
I keep getting null
here.
2
Answers
If you want to send JSON, you have to call
JSON.stringify()
But you can leave it as is and just use
It’s not clear why you feel the need for the
data1
property in the first place.Other issues:
datatype: 'json'
should bedataType: 'json'
— JavaScript is case-sensitive.echo $vars;
should bevar_dump($vars);
, since$vars
is an array.And neither of these will echo JSON, as expected by the
dataType
option.Just keep this data in $.ajax
like this
you will get the post data like this
this will reduce code like you will not have to deal with JSON