dpp78272 2011-12-19 10:51
浏览 121
已采纳

使用Ajax生成提交按钮不提交表单数据

Resolved: I had $_SERVER['REQUEST_METHOD'] != 'post' as lowercase. That has to be capital apparently... It worked as soon as I capitalized it, and that was the only change. I voted you up for you fine chaps who helped. Thanks!

I'm generating a submit button after a simple math question with Ajax. The Ajax works fine. I can verify with var_dump/print_r that the $_POST and the $_SESSION data is being passed correctly. The submit button is going in the output div like I would expect.

However, when I press the submit button, it reloads the page but it does not trigger a submit. It goes back to the form and the $_POST variable is empty / not set at all.

The submit button is in the form tags. Why is it submitting the form but not the data / how do I get it to work?

I don't think you need the code to answer the question, but nonetheless, here is a simplified version of the code:

// In a server request method block on test.php:
     if( $_SERVER['REQUEST_METHOD'] != 'POST' ){
<form  id="addUserId"  name="addUser"  method="post"  action="test.php" >
<table id="formCreatoraddUserIdTableId"  cellpadding="2"  cellspacing="2"  width="100%" >
    <tr id="formCreatorRowId0" >
        <td valign="top" ><font>3 minus 1: </font></td>
        <td valign="top" ><input type="text"  id="validatorId"  name="validate"  onkeyup="makeAjaxRequest('./ajax/captchaSubmitButtonCheck.php', 'captcha='+encodeURIComponent(document.getElementById('validatorId').value),'captchaOutputDiv', '1');" autocomplete="off"  />          
        </td>
    </tr>
    <tr id="formCreatorRowId1" >
        <td valign="top" ><font></font></td>
        <td valign="top" >
            <div  id="captchaOutputDiv" ></div>
        </td>
    </tr>
  </table>
    <input type="hidden"  name="refreshPostPrevention"  />
</form>
   }else{

     print_r( $_POST ); // will be empty
   }
     // in an ajax file captchaSubmitButtonCheck.php:
<?PHP
if( $_SERVER['REQUEST_METHOD'] == 'POST' ){
    printr( $_POST );
    printr( $_SESSION, 'SESSION' );
    if( $_POST['captcha'] == $_SESSION['captcha'] ){
        echo '<input type="submit" value="Save" />';    
    }else{
        echo '<font class="red">Your math was wrong. Try again.</font>';    
    }
}
?>

     // the JS

function makeAjaxRequest(url, params, output, image) {
  var getdate = new Date();  //Used to prevent caching during ajax call
  if( image == 1 ){
      document.getElementById(output).innerHTML='<img src="./images/template/ajax-loader.gif"></img>'; 
  }
  if(xmlhttp) { 
    xmlhttp.open("POST",url,true); 
    xmlhttp.onreadystatechange = function(){
       if (xmlhttp.readyState == 4) {
         if(xmlhttp.status == 200) {
           document.getElementById(output).innerHTML=xmlhttp.responseText; //Update the HTML Form element 
         }
         else {
            alert("Error during AJAX call. Please try again");
         }
       }    
    }
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(params); //Posting txtname to PHP File
  }
}
  • 写回答

4条回答 默认 最新

  • dongsi1944 2011-12-19 10:57
    关注

    When you use AJAX driven interfaces, you may not want to use a submit button, only display a submit button as a fallback when JS is disabled. Because when you put a submit button inside a form it will always try to submit, unless you explicitely prevent it from doing so by overriding the submit action on the form.

    My solution is to just use a normal input type='button' or any element actually that performs the AJAX action onClick, and then submit the form data either with serialization or manually sent the data to the AJAX script. That way you also have more control over what is being sent and how.

    //Using jQuery

    function ajaxSubmit(){
        var data  = $("form").serialize();
        //Ajax code here
    }
    
    <span class='action' onclick='ajaxSubmit'>Send the data</a>
    

    Or overwriting the submit action, with jQuery:

    $('form').submit(function() {
      alert($(this).serialize());
      return false;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序