Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a WordPress page exists using JavaScript before redirecting to it

My link looks like this:

 http://localhost:8081/wordpress/?p=535

How can I redirect to this page with JavaScript? I'm unfamiliar with the ? syntax, but I have a feeling I should be able to send some sort of request with the ID of the post?

Something like:

redirect("p="+postid);

Just calling window.Location won't work for me because if the post doesn't exist, then I want to be able to do something else. Also, I don't want it to direct to local host. It needs to direct to the root of the website...

More like this then:

if (request("p="+postid) exists) {
    redirect("p="+postid);
}
like image 496
egucciar Avatar asked Aug 08 '26 21:08

egucciar


1 Answers

document.location.href = "http://localhost:8081/wordpress/?p=535";

If you want to check if the page exists first, you could do this :

var addr = "/wordpress/?p=535"; // here with a relative url
$.ajax({
    type: 'HEAD',
    url: addr,
    success: function() {
        document.location.href = addr;
    }
});

This will make a HEAD request (so no content download) to check if the page exists and only change the current location if it's OK.

Note that you may do that without jQuery if you want, I let you determine the exact syntax if needed.

But this can only work if both page are from the same domain.

like image 190
Denys Séguret Avatar answered Aug 10 '26 10:08

Denys Séguret