du2229 2013-01-03 18:13
浏览 29
已采纳

php到表单提交jquery

i have this code which ask user to input value and submit.

html

 <form id="myForm" method="post" action="saving.php">
            <p><label for="input1">Input 1:</label>
                <input type="text" size="10" name="input1" id="input1" />
            </p>
            <input id="save" name="save" type="submit" value="save" />
    </form>
    <p><span id="thevalue"></span><span id="existornot"></span></p> 

js

$("#myForm").submit(function(event) {    
    event.preventDefault();      
    $("#myForm").validate(
      {     rules: {input1: "required",},
            messages: {input1: "message error input"},
            });
    if( $("#myForm").valid()){ 
        var $form = $("#myForm" ),
        url = $form.attr( "action" ), 
        insertedVal=$("#input1").val(); 

        $.post(url,{input1:insertedVal},  
          function(){

          //displaying value condition
          $("#thevalue").html(insertedVal);
          // ... msg from php to be inserted to #existornot 

          });  
       }
}); 

saving.php

<?php
  if(!empty($_POST['input1']))
  {
    $inputone= mysql_real_escape_string(trim($_POST['input1']));
    $result = mysql_query("SELECT COUNT(*) FROM `test_table` WHERE `name` = '$inputone' ");
      if (mysql_result($result, 0, 0) > 0) 
      {
        echo "is duplicate data" ;
      } 
      else 
      {      
        mysql_query("INSERT INTO `test_table`(name)  VALUES ('$inputone')") ;
         echo "is updated to db" ;
      }
  }
  else
  {
    echo "could not be empty"  ;
  }

?>

How to pass those message of 'is duplicate data' or ' is updated to db' from the php to the javasript, to tell user that the submit process is fail or success ?

Thanks in advance for any advice.

  • 写回答

5条回答 默认 最新

  • duanmei2459 2013-01-03 18:22
    关注

    Change the function call after the jQuery post to accept the data variable and process the results:

        $.post(url,{input1:insertedVal},  
          function(data){
    
          //displaying value condition
          $("#thevalue").html(insertedVal);
          // ... msg from php to be inserted to #existornot 
    
          if (data != 'is updated to db') {
              alert(data);
          }
    
          });  
       }
    

    (Data will contain what has been echoed in your save function)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 Revit2020下载问题
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数