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

报告相同问题?

悬赏问题

  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键