Reputation: 635
I have a search bar searching on index.php
page. But i want to show the result on coupons.php
. How to do it in AJAX.
NOTE: #search_result
is a div of coupons.php file where i want to display the result.
AJAX
$("document").ready(function() {
$("#search_form").on("submit", function (e) {
e.preventDefault();
$.post("result.php?query=" + encodeURIComponent($("#list_search").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
</script>
Upvotes: 0
Views: 1136
Reputation: 317
I am assuming you need to somehow show result on another page but cannot use server side. I don't know why you want to do that, but ajax is surely not the option and if you can't use server side, you can do this. Instead of sending the JSON response on your coupons.php page. Send the search query to the coupons page. So you should create a search form in index.php something like this
<form action="coupons.php" method="GET">
<input type="text" name="query" />
<input type="submit" value="Submit" />
</form>
Then in your coupons.php page you can access your search query by window.location.search This will give you the query user search on
Now using this query, here on coupons.php page you will write your logic to get the json response and print the result in #search_result element.
So your coupons.php will look something like
$("document").ready(function() {
var q = window.location.search; // q is your query string you got from index.php
$.post('result.php'+q, function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
Upvotes: 2