Ajax按钮单击不起作用

I have spent hours searching through the other questions similar to this one and have tried all the suggested solutions and nothing seems to work. What I am trying to do is pull postings from my database in regard to careers. When the user finds a career they want to apply for, they click the button and the title & job posting are transferred to the next page (via ajax post) for inclusion into the database on successful application. The code I currently have seems to pull the information correctly, but on clicking the button nothing happens. Please assist!

Note: The ajax call is towards the bottom of the file. I included the entire file in case there were any questions relating to it.

Note 2: I have tried .on('click'..., .onclick, and .click. I have tried using a div to point to the buttons, I have tried using various ways to reference the button, and I have tried preventDefault(), and various combinations of these.

<!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
    ?>

Have you tried

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

Sometimes you should add this function dynamically.

When you check the JS code does it show #Apply1, #Apply2, #Apply3...?

Few things:

  • It's never a good idea to bind event handlers within a loop.
  • Bind a click event to the button outside the loop and within the event handler you can find out which button is clicked and act accordingly.
  • Make a genuine effort to read thru your code and see if there are syntax errors (There is a few in yours)
  • Browser console is there for a reason. Make use of it to see if there are errors being thrown. This only makes you better developer
  • When possible, do not mix client side code with server side script, esp. in this case as it's unnecessary

So,

1) Add classes to those TDs from which you'd like to grab values later within your ajax call, such as:

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

2) Move your compete javascript outside the PHP block, just after the ?>

$(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);
        });
    });
});

Test the code to see if it works. Repeat the points I mentioned in the very beginning if need be, to fix further issues.