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

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备