python小菜 2015-06-22 12:34 采纳率: 0%
浏览 9

Ajax不会将数据发送到PHP

SOLVED: The code posted here was correct, but some of the PHP code connecting to the database needed fixing, I have it working now. I used Quentin's suggestions in the comments to fix my problem.

I'm trying to send a JSON of an array through ajax to a PHP file, then have the php file run. This is my ajax:

    $('#submit').click(function() {
  $.ajax({
    method: "POST",
    url: "submit.php",
    data: {selectedImageArray: selectedImageArray}
  }).done(function( msg ) {
    alert( "Data Saved: " + selectedImageArray );

  });
});

In my PHP file I connect to a database then have this:

$array = $_POST['selectedImageArray'];
    $sql = $dbh->prepare("INSERT INTO pending_trades (steam_id, trade_items, is_giving, is_receiving, has_started) VALUES (:steamid, :itemlist, '1', '0', '0')");
    $sql->bindParam(':steamid', $steamprofile['steamid']);
    $sql->bindParam(':itemlist', $array);

    $sql->execute();

I want this to send the "selectedImageArray" json to the php and run the msql query using it on the press of this button:

<button id="submit" class="button1" >Submit<span></span></button>

When the button is clicked, I get the "data saved: array data" message, but the php code isn't run. Why isn't this working?

EDIT: I set data: {selectedImageArray: selectedImageArray} instead of data: selectedImageArray because I was told it makes it into JSON format, is that correct?

  • 写回答

3条回答 默认 最新

  • weixin_33724659 2015-06-22 12:45
    关注

    You can add content type JSON. other wise it will consider as text.

    var data = JSON.stringify({selectedImageArray: selectedImageArray});
     $.ajax({
    method: "POST",
    dataType: 'json', // If your response is JSON
    contentType: "application/json",
    url: "submit.php",
    data: data
    }).done(function( msg ) {
    alert( "Data Saved: " + selectedImageArray );
    include ('submit.php');
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程