1

For example I have a variable $abc. I want to somehow pass it to the jQuery AJAX POST function which is stored in another JS file. The post function will pass that variable to page2.php and this page will use it to query database and finally display the content of page2.php on the current page.

So how do I actually pass the $abc variable to the jQuery post function which is in an external JS file?

1 Answer 1

1

You can use data-* attributes to achieve this. In your HTML, you can add that attribute with the $abc PHP variable:

<a href="#" data-var="<?php echo $abc ?>">Foo</a>

Then in your external JS file, you can read this attribute from the element which raised the event and include it in the AJAX data:

$('a').click(function(e) {
    e.preventDefault();
    $.ajax({
        url: '/bar/',
        data: {
            foobar: $(this).data('var')
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

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.