Reputation: 45
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?
Upvotes: 1
Views: 122
Reputation: 337656
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')
}
});
});
Upvotes: 1