PHP / AJAX POST表单检索

I am new to PHP/AJAX and I'm trying to obtain form values without a page refresh. I've tried various codes but none of them seem to work. Either nothing happens or I get an undefined index notice. I've tried using isset() and empty() but these dont seem to work either. Any help is appreciated. This is inside my javascript function:

    {
        var hr = new XMLHttpRequest();
        var url = "parser.php";
        var fn = document.getElementById("firstname").value;

        var vars = "firstname="+fn;
        //document.write(vars);
        //open() method of XMLHttpRequest object
        hr.open("get",url,true);
        //to send url encoded variables in the request
        hr.setRequestHeader("Content-type", "application/w-www-form-urlencoded");

        hr.onreadystatechange = function () {
            if(hr.readyState == 4 && hr.status == 200){
                var returnData = hr.responseText;

                document.getElementById("status").innerHTML = returnData;

            }


        };

        //send data to PHP----wait for response to update status div
        hr.send(vars); //execute request
        document.getElementById("status").innerHTML = "processing...";


    }

This is another method I tried (code is inside javascript function):

    {
        var name = document.getElementById('firstname').value;
        var dataString = "name"+name;
        $.ajax({
            type: "post",
            url: "validate.php",
            data: dataString,
            cache: false,
            success: function (html) {
                $('#result').html(html);

            }



    });
        return false;

    }

This is my php file that will return the data:

    <?php
         if(isset($_POST['firstname'])) {
         $name = $_POST['firstname'];
         echo 'Name:' . $name;
  }

This is the input tag:

    First name:<input id="firstname" name="firstname" type="text"><br>

I think your data string is not correct, you are missing an "="

var dataString = "name"+name;

var dataString = "name="+name;

But you can also try to insert an object like this:

$.ajax({
        type: "post",
        url: "validate.php",
        data: {"name":name},
        cache: false,
        success: function (html) {
            $('#result').html(html);

        }

Wrap your code in a document ready statement, trigger you code on a click on the form submit button,don't forget to add the jquery library to your page

$(function(){   
$('[type="submit"]').on('click',function(e){
  e.preventDefault();
  var name = $('#firstname').val();
        var dataString = {name:name};
        $.ajax({
            type: "post",
            url: "validate.php",
            data: dataString,
            cache: false,
            success: function (html) {
                $('#result').html(html);

            }
      });
});
});