dongxue163536 2012-04-12 19:13
浏览 46
已采纳

使用PHP和AJAX插入MySQL记录

trying to insert a record in my DB using AJAX for the very first time. I have the following...

Form

 <form>
     <input type="text" id="salary" name="salary">
     <input type="button" onclick="insertSalary()">
 </form>

AJAX

<script type="text/javascript">

function insertSalary()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('current-salary').innerHTML=xmlhttp.responseText;
    }
  };
xmlhttp.open("POST","insert_salary.php",true);
xmlhttp.send("salary=" + document.getElementById("salary").value);
}

</script>

PHP

$uid = $_SESSION['oauth_id'];      
$monthly_income = mysql_real_escape_string($_POST['salary']);

#Insert a new Record
$query = mysql_query("INSERT INTO `income` (user_id, monthly_income) VALUES ($uid, '$monthly_income')") or die(mysql_error());
$result = mysql_fetch_array($query);
return $result;

Nowmy data is being inserted into the table BESIDES the 'salary' which is being inputted as '0'

Once inserted I also have a div 'current-salary' that should then be populated with there inputted value only it isnt, Can anybody help me to understand where im going wrong?

  • 写回答

1条回答 默认 最新

  • dragon19720808 2012-04-12 19:21
    关注

    If you want to save your self a lot of time, effort, and heartache, use the jquery library for your ajax requests. You can download it at http://jquery.com/

    After adding a reference(Script tag) to the jquery script your javascript for the ajax request would become:

    function insertSalary()
    {
        var salary = $("#salary").val();
        $.post('insert_salary.php', {salary: salary}, function(data) 
        {
            $("#current-salary").html(data); 
        });
    }
    

    Also keep in mind that using "insert_salary.php" as the url means it is a relative path and must be in the folder of the current running script.

    Your php script needs to echo whatever you would like to be injected into your current-salary tag also.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示