nobrandheroes
nobrandheroes

Reputation: 758

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.

Upvotes: 1

Views: 904

Answers (2)

user2877011
user2877011

Reputation: 110

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');
            }
        });
    });
});

Upvotes: 1

T0w3ntuM
T0w3ntuM

Reputation: 332

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?

Upvotes: 0

Related Questions