1

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.

2
  • Try logging the response in your console. What do you see? And you should probably format your output form categories.php with JSON for better interoperability. Commented Oct 14, 2013 at 18:33
  • Perhaps I'm doing something incorrectly, but I only need the ajax call to get an attribute from a link, nothing directly from PHP. Only need it to run a dynamic query on a click even. Commented Oct 14, 2013 at 20:04

2 Answers 2

1

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');
            }
        });
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

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?

1 Comment

My script generates a list of links to a page. JQuery pulls the id from the links and hopefully sends it to the page which will run an SQL query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.