doujian3132 2014-12-16 06:01
浏览 150
已采纳

AJAX不使用Jquery从PHP文件中获取数据

I'm trying post data to PHP file but i can't receive any data from PHP file. Let me add codes. This is my jQuery function:

$(document).ready(function () {

$(function () {
$('a[class="some-class"]').click(function(){

   var somedata = $(this).attr("id");

   $.ajax({
      url: "foo.php", 
      type: "POST",
      data: "id=" + somedata,

      success: function(){
          $("#someid").html();
      },
      error:function(){
          alert("AJAX request was a failure");
      }
    });
    });
    });
});

This is my PHP file:

<?php
$data = $_POST['id'];

$con = mysqli_connect('localhost','root','','somedatabase');
if (!$con) {
  die('Could not connect: ' . mysqli_error($con));
}

mysqli_select_db($con,"database");
$sql="SELECT * FROM sometable WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);


while($row = mysqli_fetch_array($result)) {

 echo $row['info'];

 }

mysqli_close($con);

?>

This what i have in HTML file:

<p id="someid"></p>

<a href="#page2" class="some-class" id="1">Data1</a>
<a href="#page2" class="some-class" id="2">Data2</a>

Note: This website is horizontal scrolling and shouldn't be refreshed. When i'm clicking links (like Data1) it's going to another page without getting data from PHP file

展开全部

  • 写回答

5条回答 默认 最新

  • duangan6731 2014-12-16 06:12
    关注

    You have a few problems:

    1. You are not using the data as mentioned in the other answers:
      success: function(data){ $("#someid").html(data); },
    2. You are not cancelling the default click action so your link will be followed:
      $('a[class="some-class"]').click(function(e){ e.preventDefault(); ...;
    3. As the id's are integers, you can use data: "id=" + somedata, although sending an object is safer in case somedata contains characters that need to be escaped:
      data: {"id": somedata},;
    4. You have an sql injection problem. You should cast the variable to an integer or use a prepared statement:
      $data = (int) $_POST['id'];;
    5. As also mentioned in another answer, you have two $(document).ready() functions, one wrapping the other. You only need one.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 VAE代码如何画混淆矩阵
  • ¥15 求遗传算法GAMS代码
  • ¥15 雄安新区高光谱数据集的下载网址打不开
  • ¥66 android运行时native和graphics内存详细信息获取
  • ¥100 求一个c#通过CH341读取数据的Demo,能够读取指定地址值的功能
  • ¥15 rk3566 Android11 USB摄像头 微信
  • ¥15 torch框架下的强化学习DQN训练奖励值浮动过低,希望指导如何调整
  • ¥35 西门子博图v16安装密钥提示CryptAcquireContext MS_DEF_PROV Error of containger opening
  • ¥15 mes系统扫码追溯功能
  • ¥40 selenium访问信用中国
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部