How to send POST data in ajax?
<p>I need to write a script that receives and parses a JSON array within the POST array.  In order to do this, I'm first trying to just send any old JSON data to my script so I have something to work with.</p>

<p>My receiving script is in PHP (but alternately could be done in Javascript.)  Right now, I'm just serializing the POST array and writing it to a text file to make sure something is coming in.  What it's writing is an empty array, though. </p>

<p>I'm trying to send the data using an ajax request.  This is what I have at the moment:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
    &lt;meta charset="UTF-8"&gt;
    &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"&gt;&lt;/script&gt;
    &lt;script&gt;
        $(document).ready(function() {  
        var jsondata = JSON.stringify({
            val1:"this",
            val2:"that"
        });  

        $.ajax({
            url: "http://api.mydomain.com/test/index.php",
            method: "POST",        
            data: {json: jsondata},
            contentType: "application/json",
            success: function(data){alert(JSON.stringify(data));},
            error: function(errMsg) {
                alert(JSON.stringify(errMsg));
            }
        });
    });
    &lt;/script&gt;
&lt;/head&gt;
&lt;body&gt;  
&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>I've tried lots of variations on this, too, including</p>

<ul>
<li>not stringifying jsondata</li>
<li>changing data to this: <code>data: jsondata</code></li>
<li>using <code>type:</code> instead of <code>method:</code>in the request</li>
<li>including <code>datatype: "json"</code> in the request</li>
</ul>

<p>and some other variations I can't even remember at this point.  Am I missing something simple?  Or is there an easier way to accomplish this?</p>

<p>EDIT: adding my index.php file</p>

<pre><code>if (isset($_POST)){
    // This line is commented out because it breaks it.
    //$jspost = json_decode($_POST['json']);
    $jsser = serialize($_POST);
    echo "I'm here.";
    // Write to text file
    $myfile = "response.txt";
    $fh = fopen($myfile, 'w') or die("can't open file");
    $now = date("n/j/y g:i:s a");
    fwrite($fh, $now."\r\n");
    fwrite($fh, "I received a POST.\r\n");
    fwrite($fh, $jsser);
    fwrite($fh, "\r\n\n");
    fclose($fh);
}
</code></pre>