为什么在使用AJAX调用php方法时会得到未定义的索引?

时间:2016-04-10 18:57:59

标签: php jquery ajax methods undefined-index

我试图从我的专辑课程中获取一些信息。我认为我的问题在于我的AJAX调用的语法。让我一步一步为你解决这个问题。这是方法:

Album.php

    ...

    public function getTracks ($title) {

    $db = Dbclass::getDB();
    $query = "SELECT *
                FROM upcoming_albums_tracks
                WHERE albums_title = :title";

    $statement = $db->prepare($query);
    $statement->bindParam(':title', $title, PDO::PARAM_STR, 50);
    $statement->execute();
    $tracks = $statement->fetchAll();
    return $tracks;

    }

顺便说一下,这种方法工作正常。现在我的php文件调用了这个方法:

GetTracks.php

<?php
require_once '../../models/database.php';
require_once 'Album.php';

$tracks = new Album;
$tracks->getTracks($_POST['albumTitle']);

return $tracks;

最后,AJAX调用

upcoming_albums_ajax.js

    ...

    $(document).ready(function() {

    //Get track info with Ajax 
    $(".btn-tracks").click(function (e) {

        // stop form submission first
        e.preventDefault();

        // get album title
        var albumTitle = $(this).val();
        console.log(albumTitle) //This gives me the value I'm looking for.

        // get tracks from php
        $.ajax({
            url : '../../controllers/admin/GetTracks.php',
            //I think the issue is in how I'm formatting the data.
            data: {title: albumTitle},
            type : 'POST',
            success : function (d) {
                alert(d);
            },
            error : errorHandler
        });

    });

});

我的提醒弹出告诉我,我有一个未定义的索引:albumTitle。

顺便说一句,这是我的按钮:

<button type='submit' class='btn-tracks' value='" . $album['albums_title'] . "'>Show Tracks</button>

1 个答案:

答案 0 :(得分:1)

在GetTracks.php中,您希望收到$_POST['albumTitle']

$tracks->getTracks($_POST['albumTitle']);

但你从javascript传递$_POST['title']

data: {title: albumTitle},

改变(因此他们相等)你应该没事。