Ajax按钮单击无法正常工作

时间:2015-07-24 16:25:06

标签: javascript php jquery ajax

我花了几个小时搜索与此类似的其他问题,并尝试了所有建议的解决方案,似乎没有任何效果。我想要做的是从我的数据库中提取关于职业的帖子。当用户找到他们想要申请的职业时,他们点击按钮和标题&职位发布转移到下一页(通过ajax帖子),以便在成功申请时包含在数据库中。我目前的代码似乎正确地提取信息,但点击按钮没有任何反应。请帮忙!

注意:ajax调用位于文件的底部。我将整个文件包括在内,以防有任何与之相关的问题。

注意2:我尝试过.on('click'...,。onclick和.click。我尝试使用div指向按钮,我尝试使用各种方法来引用按钮,并且我试过了preventDefault(),以及这些的各种组合。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"[]>
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US" xml:lang="en">
<head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>Career Search Results</title>



<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>

    </head>
    <body>
    <?php
        {
        if (!isset($_POST['CareerSearch'])) {
        die(header("Location: {$Server}CareerSearch.php"));}
        $CurrentPage= "Careers";
        $Filepath= "c:/wamp/www/";
        $Server= "http://localhost";
        include ("{$Filepath}functions.inc");
        include ("{$Filepath}header.php");
        }
    ?>
        <div class="box sheet">
            <div class="box-body sheet-body">
                <div class="layout-wrapper">
                    <div class="content-layout">
                        <div class="content-layout-row">
                            <div class="layout-cell content">
    <div class="box post">
        <div class="box-body post-body">
    <div class="post-inner article">
                                    <h2 class="postheader">Currently Available Careers
                                    </h2>
                                                    <div class="postcontent">
    <br />
    <table style= 'width: 100%'>
                <tr style= 'text-align: left'>
                    <th>Posting ID</th>
                    <th>Career Title</th>
                    <th>Department</th>
                    <th>Location</th>
                    <th>Posted On</th>
                    <th>Apply</th>
                </tr>

    <?php
    $fieldName = array("ID", "Position", "Department", "City", "State", "All");
    //get values from form
    $srchField = filter_input(INPUT_POST,"srchField");
    $srchValue = filter_input(INPUT_POST, "srchVal");
    //don't proceed unless it's a valid field name
    $mysqli = new mysqli(DBHOST,DBUSER,DBPASS,DB);
    if ($mysqli->connect_errno) {
    error_log("Cannot connect to MySQL: " . $mysqli->connect_error);
    return false;}
    if (in_array($srchField, $fieldName)){
    $field = $mysqli->real_escape_string($srchField);}
    $srchValue= strtolower($srchValue);
    //put value inside %% structure
    $value = $mysqli->real_escape_string("%$srchValue%");
    if ($srchField !== 'All' || $srchValue !== 'all' || $srchValue !== '*')
    {$query= "SELECT * FROM open_careers WHERE $field LIKE '$value'";}
    if ($srchField== 'All' || $srchValue == 'all' || $srchValue == '*')
        {$query="SELECT * FROM open_careers";}
    $result= $mysqli->query($query);
    $num = $result->num_rows;
    if (!$mysqli->query($query)) {
        echo "Couldn't execute your search.";}

    if ($num == 0 || $num= ''){
    print "No matches found";
    /* free result set */
        $result->close();
        return false;}
    if (count($num) > 0){
        $n=0;
        while($row = $result->fetch_assoc()) {
            $Posting= $row['Posting'];
            $Title= $row['Position'];
            $Department= $row['Department'];
            $City= $row['City'];
            $State= $row['State'];
            $Date= $row['Date'];
            $Location= $City . ',' . $State;
            $n++;
            echo  "
                <tr> 
                    <td>$Posting</td>
                    <td>$Title</td>
                    <td>$Department</td>
                    <td>$Location</td>
                    <td>$Date</td>
                    <td><button id='Apply{$n}' name='Apply{$n}' class='Apply{$n}'>Apply Now</button></td>

    <script type='text/javascript'>
        $(document).ready(function(){
        $('#Apply{$n}').click(function(){
        request = $.ajax({
        type: 'post',
        url: '{$Server}CareerRegisterResume.php',
        data: {
            source1: '$Posting',
            source2: '$Title',}
        request.done(function( data ){ console.log (data);});
        )};
        });});
    </script>";}
                    echo "</tr></table>";
                                    $result->free();

            }
    else {
    print "Something went wrong.";
    } // end else
    ?>

2 个答案:

答案 0 :(得分:1)

少数事情:

  • 在循环中绑定事件处理程序绝不是一个好主意。
  • 将点击事件绑定到循环外部的按钮,在事件处理程序中,您可以找到单击的按钮并采取相应的行动。
  • 真正努力通过您的代码阅读并查看是否存在语法错误(您的代码中有一些错误)
  • 浏览器控制台是有原因的。利用它来查看是否有错误被抛出。这只会让你成为更好的开发者
  • 如果可能,请不要将客户端代码与服务器端脚本混合,尤其是在这种情况下,因为它是不必要的

所以,

1)将类添加到您希望稍后在ajax调用中从中获取值的TD,例如:

<tr> 
    <td class="posting">$Posting</td>
    <td class="title">$Title</td>
    <td>$Department</td>
    ...
    ...

2)在?>

之后,将竞争的javascript移到PHP块之外
$(document).ready(function() {
    //Target all buttons that has a class starting with 'Apply'
    $("button[class^='Apply']").on("click", function() {
        var $this = $(this),
            $tr = $this.closest("tr"),
            data = {
                source1: $tr.find(".posting").text(),
                source2: $tr.find(".title").text()
            },
            request = $.ajax({
                type: "post",
                url: "http://localhost/CareerRegisterResume.php",
                data: JSON.stringify(data)
            });

        request.done(function(data) {
            console.log (data);
        });
    });
});

测试代码以查看它是否有效。如果需要,重复我在一开始就提到的要点,以解决更多问题。

答案 1 :(得分:-1)

你试过吗

$(document).on('click', '#Apply{$n}', function() { ...

有时您应该动态添加此功能。

检查JS代码时,它显示#Apply1,#Apply2,#Apply3 ......?