dongshu4221 2015-05-08 07:14
浏览 49

如何通过Ajax和PHP传递表单

I'm new to this, I just want it to work with simple code then i'll add onto it. But it's not working in the sense that i don't get an echo. I just want to submit a form and have it not refresh the page.

here is my form

<form >
 <input type="text" id="name" >
 <input type="submit" value="s"  onclick="return chl()" >
</form>

here is my js

<script>
function chl(){

  var name= document.getElementByID('name').value;
  var dataString='name' + name; 

  $.ajax({
     type:"post",
     url:"hi.php",
     data:dataString,
     cache:false,
     success: function(html){
       alert ("success"); 
     }
   });
   return false;
}
</script>

and here is my php

<?php

$name=$_POST ['name'];
echo "response".$name; 

?>
  • 写回答

6条回答 默认 最新

  • dongtong5242 2015-05-08 07:15
    关注

    The datastring should be formed like a querystring; you've missed the = between the key and the value:

    var dataString = 'name=' + name; 
    

    That being said, you can improve your code. Firstly you should attach the event to the submit of the form, and use event.preventDefault() to stop the normal form submission. Also, you can use serialize() to generate an object containing the forms' values to pass across in the AJAX request. The response from your PHP code will be retuned in the parameter sent to the success handler, so you need to do something with it there. Lastly, you should attach your events in JS, not HTML attributes, for a better separation of concerns. Try this:

    <form method="hi.php">
        <input type="text" id="name" />
        <input type="submit" value="s" />
    </form>
    
    $('form').submit(function(e) {
        e.preventDefault();
        $.ajax({
            type: "post",
            url: this.action,
            data: $(this).serialize(),
            cache: false,
            success: function(html){
                 alert(html); // = 'response: name = [VALUE]'
            }
        });
    });
    
    $name = $_POST['name'];
    echo "response: name = ".$name;
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?