dsxjot8620 2017-07-19 14:39
浏览 47

使用Ajax添加监视列表按钮功能(PHP)

My HTML Code:

<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">

    <input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
    <button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="'.$addremove.' TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>

</form>

   // Same form as above
<form class="addtowatchlistform" action="logo/insertwatchlist.php" method="POST">

    <input type="hidden" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'"/>
    <button id="addtowatchlistbutton" type="submit" name="tmdb_id" value="'.$result[$x]["tmdb_id"].'" data-tooltip="'.$addremove.' TO YOUR WATCHLIST" class="material-icons" style="color:'.$watchlisticoncolor.'">add_box</button>

</form>

Jquery code:

<script>
$(".addtowatchlistform").submit(function(e) {
  var data = $(this).serialize();
  var url = $(this).attr("action");
  $.post(url, data, function() {

     try {
        data = JSON.parse(data);
        $("button#addtowatchlistbutton").data('tooltip', data.addremove + " TO YOUR WATCHLIST");
        $("button#addtowatchlistbutton").css('color',data.watchlisticoncolor);
    } catch (e) {
        console.log("json encoding failed");
        return false;
    }

  });
  return false;
});
</script>

insertwatchlist.php code

<?php
$response = new \stdClass();
$response->addremove = "item1";//you can get the data anyway you want(e.g database)
$response->watchlisticoncolor = "red";
die(json_encode($response));
?>

Expected Result:
1.)When someone clicks on add_box button, it submits the form without reloading the page (This one works fine)

2.) insertwatchlist.php sends this code: {"addremove":"item1","watchlisticoncolor":"red"} and, the Jquery code place them in place of: $addremove and $watchlisticoncolor variable, in the real time without reloading the page.

Original Result:

First point of expected result works fine.

Second point of expected result do nothing (no error)

  • 写回答

1条回答 默认 最新

  • doubo82706 2017-07-19 14:42
    关注

    data is not defined at $.post() callback function. Though you have already defined data before $.post() call. Use a different identifier name

    $.post(url, data, function(response) { // define `response` here
      $("button#addtowatchlistbutton")
      .data('tooltip', response.addremove + " TO YOUR WATCHLIST")
      .css('color',response.watchlisticoncolor);
    })
    

    JSON.parse() is not necessary. jQuery.post() converts JSON from server to a JavaScript object

    评论

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据