skip to Main Content

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


  1. If you want to send JSON, you have to call JSON.stringify()

    data: { data1: JSON.stringify({"username": username, "orderid": orderid}) },
    

    But you can leave it as is and just use

    $username = $_POST['data1']['username'];
    $orderid = $_POST['data1']['orderid'];
    

    It’s not clear why you feel the need for the data1 property in the first place.

    Other issues:

    datatype: 'json' should be dataType: 'json' — JavaScript is case-sensitive.

    echo $vars; should be var_dump($vars);, since $vars is an array.

    And neither of these will echo JSON, as expected by the dataType option.

    Login or Signup to reply.
  2. Just keep this data in $.ajax

    data:{ data1:{"username": username, "orderid": orderid}},
    

    like this

    data:{"username": username, "orderid": orderid},
    

    you will get the post data like this

    $username = $_POST['username'];
    $orderid = $_POST['orderid'];
    

    this will reduce code like you will not have to deal with JSON

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search