I want to load a dynamic content to specific div name with multiple querystring from a menu.
Example dynamic menu link
index.php?tag=2
index.php?category=1&tag=2
index.php?category=2&tag=2&location=3
Example query process in PHP for link index.php?category=1&tag=2
$tag = intval($_GET['tag']);
$cat = intval($_GET['category']);
if(isset($tag) && isset($cat)) {
$select = $db->query("SELECT * FROM table WHERE cat=".$cat." AND tag=".$tag."");
... // fetch results
}
Question - With jQuery how to tell user clicked the link then send the callback to PHP process & show the results in the specific div name without refresh the page.
Let me know
You have to create another php page that returns data in json format for the given substring. Your substring is dynamic so you have to get the substring from another element. I suggest a <input type="hidden" value="YourQueryString"/>
, its simple. You can put the element next to your link and get the value using jQuery.val()
.
Then you use jQuery.ajax()
/ jQuery.get()
or jQuery.post()
in your index.php to get the data from that page / script. (jQuery.get()
and jQuery.post()
uses jQuery.ajax()
internally)
In the callback method of jQuery ajax you grab the data and build the html from it. After that you can use jQuery.html() to set the data to your div.
html / php
<a class="AnyClassName">Click me</a>
<input type="hidden" value="category=1&tag=2"/>
jQuery
$(".AnyClassName").click(function() {
// lets get the query string
var queryString = $(this).next().val();
$.ajax({
url: "yourNewPage.php?" + queryString,
context: document.body,
success: function(data){
var generatedHtml = "..." // build your html from the data object
$("#IdOfYourDiv").html(generatedHtml);
}
});
});
Alternatively your php page can return html (simple page) for your query string. This is easier than build html in the jQuery Ajax Callback
. If this is done you can do this
$(".AnyClassName").click(function() {
// lets get the query string
var queryString = $(this).next().val();
$('#IdOfYourDiv').load("yourNewPage.php?" + queryString);
});
Documentation
Tutorials
Use one of jQueries many AJAX functions, for instance:
$.post("ajax.php", "category=1&tag=2",
function(data) {
alert("Data Loaded: " + data);
});
Check: http://api.jquery.com/jQuery.post/
Your PHP script should return the HTML you want to load into the div; the JS looks like this:
$('#your_menu').on('click', 'a', function(e) {
var $this = $(this),
url = $this.href;
$.ajax({
url: url,
success: function(html) {
$('#div_to_update').html(html);
}
});
});
It gets the URL from the link you clicked in the menu, passes the URL to the Ajax call, and fills the target div with the HTML response. See here for more info on this topic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With