weixin_33725126 2016-07-27 10:24 采纳率: 0%
浏览 14

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>
  • 写回答

2条回答 默认 最新

  • weixin_33724046 2016-07-27 10:28
    关注

    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);
    
            }
    
    评论

报告相同问题?