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?

Read More

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);
}

Related posts

Leave a Reply

5 comments

  1. 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.

  2. window.location = "http://localhost:8081/wordpress/?p=535";
    

    UPDATE:- after the comment
    althought this aint the trick that should be used but can be
    try sending an ajax request to the url and if it successfull returns some content redirect else if there is an 404 error just do something else.

  3. To send the user to another URL, use

    window.location.href = 'http://localhost:8081/wordpress/?p=535'
    

    The stuff after “?” is part of the URL and is meant to be processed by a server-sided program.

  4. You can add a variable post ID into the location like this:

    var postID = 535;
    window.location = "http://localhost:8081/wordpress/?p="+postID;
    

    Now that you’ve updated your question I think it’s obvious that this isn’t a job for JavaScript. If you want to check if a page exists you should be doing that check server-side since only the server-side code has access to your database where it can check if specific post IDs actually exist or not.

    You could of course code up some AJAX interface where the JavaScript goes off and makes a query to the server-side code to see if the post exists, and then you’ll get your answer back and act on it accordingly—but that seems really over-complicated for this problem.