I have a website where I want to provide an option for users, if they click on a table\'s rows, they get regirected to another page (based on the contect of the table row).
You cannot redirect with PHP, however you can easily redirect with the response of your ajax call.
refer to: window.location.replace(...)
No.
A redirect tells the client that the resource they just requested can be found elsewhere.
The page that was previously loaded which contains that JavaScript is not the resource that the Ajax request is asking for. Something will be returned though—it should get the resource that you redirected to (which will be available in xhr.responseText
(assuming the same origin policy doesn't interfere and that you get a 200 OK
response at the place you are redirecting to)
If you intend to always redirect, then don't use Ajax.
If you intend to sometimes redirect, then you'll need to put the URL in the body of the response, parse it with JavaScript and then assign it to location
.
Yes and no. If you work with jquery, and your ajax call responds with a json like this:
{
success : true,
redirect_to : "http://www.google.com"
}
that in php means
<?php echo json_encode([
'success' => true,
'redirect_to' => 'http://www.google.com',
]);
then your ajax caller can do the dirty job:
$.get('/your/path', function (json) {
if(json.success) {
document.location.href = json.redirect_to;
}
}, 'json');
My two cents.
I basically want to get the id from the row and when the visitor clicks on the row, they should land on example.php?id=XXXXX
You can do so entirely from PHP. When you generate the table, in each row (whose id we'll call XXXX
to follow your example) you can include a link to example.php?id=XXXXX
, or an onclick
event for the whole row that executes window.location.href = 'example.php?id=XXXXX';
. So your table might look like:
...
<tr onclick="window.location.href = 'example.php?id=1234';">
<td>1234</td><td>some value</td><td>some other value<td>
</tr>
<tr onclick="window.location.href = 'example.php?id=1235';">
<td>1235</td><td>some value</td><td>some other value<td>
</tr>
...
It could be done a little nicer by generating the rows with javascript and using event listeners, but this should work.