简体   繁体   English

使用$ .ajax将表单数据发送到php页面

[英]send form data to php page with $.ajax

I have a form like this, 我有这样的表格,

<form id="frm" method="post">
    <input type="text" name="inp_txt" id="inp_txt"/>
    <input type="submit" name="sbtn" value="send" id="sbtn">
</form>

and this is my javascript code 这是我的JavaScript代码

 $(function(){

  var request ;

   $('form#frm').submit(function(e){

   e.preventDefault();

   if(request){
       request.abort();
   }

   var $form = $(this);
   var $inputs = $form.find('inputs');
   var serailize = $form.serialize();

   console.log(serailize);

   $inputs.prop('disabled',true);

   request = $.ajax({
      url:'form.php',
      type:'post',
       data:serailize
   });

   request.done(function(response, textStatus, jqXHR){
       console.log('oky');

       $.ajax({
           url: "form.php",
           type: "get",
           success: function(data){
               console.log(data);
           },
           error:function(){
              console.log('bad');
           }
       });
   });

   request.fail(function(jqXHR, textStatus, errorThrown){
       console.error(
           "The following error occurred: "+
               textStatus, errorThrown
       );
   });

   request.always(function(){
       $inputs.prop("disabled", false);
   })
 })
})

and my php code in form.php 和我的PHP代码在form.php

<?php
  $name  = $_POST['inp_txt'];

  echo(json_encode(array(data=>$name)));
?>

but I have big problem , In this section of my javascript code : 但是我有一个大问题,在我的javascript代码的这一部分:

$.ajax({
           url: "form.php",
           type: "get",
           success: function(data){
               console.log(data);
           },
           error:function(){
              console.log('bad');
           }

I get the message from post.php in console.log(data) 我从console.log(data) post.php获取消息

Undefined index:inp_txt in htdocs\phpajax\form.php

Please help me solve this problem, thanks 请帮我解决这个问题,谢谢

set data type to json in ajax's settings object: 在ajax的settings对象中将数据类型设置为json

$.ajax({
       dataType :'json',
       url: "form.php",
       type: "get",
       success: function(data){
           console.log(data);
       },
       error:function(e){
          console.log(e);
       }
   });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM