简体   繁体   中英

AJAX: Can't pass javascript variable to SQL query in PHP script

I have a PHP page with 2 sections side by side. The left pane has a MySQL query that runs and produces a list of categories as links. The right pane should have subcategories that appear when links in the left pane are clicked.

I have some AJAX in an attached JS file that should pass the ID in the links from the left pane, into a query in the right pane. The query should run. It runs if I take out a variable.

The PHP/SQL Queries work fine. JS does not.

I think this is the appropriate way of doing this.

ajax.js

$( document ).ready(function() {
$( 'a' ).on( 'click', function() {
    var a = $( this ).attr( 'id' );

    $.ajax({
        type: "POST",
        url: "categories.php",
        data: "ajax="+a,
        success: function(response){
            alert( a );
        },
        error: function() {
            alert('Error');
        }
    })
});

});

I am being told everything works, but I cannot call $_POST['ajax'] in PHP. Perhaps my page is not being refreshed. There is no form on the page.

Lastly, my file hierarchy has categories.php comprised of a list of includes, which are in a folder that is not public.

I think your ajax syntax is wrong. Try this if your argument is a and your post identifier is ajax :

$( document ).ready(function() {
    $( 'a' ).on( 'click', function() {
        var a = $( this ).attr( 'id' );

        $.ajax({
            type: "POST",
            url: "categories.php",
            data: {ajax : a},
            success: function(response){
                alert( a );
            },
            error: function() {
                alert('Error');
            }
        });
    });
});

Try setting async: false on your $.ajax call. Also, how is the data being return from php? Are you using JSON_ENCODE for the data?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM