santa
santa

Reputation: 12512

Combining PHP and jQuery to get and check URL

I am trying to figure out how o combine jQuery code, where I grab a URL value from a field a PHP code that will hit that URL to check if the site exists... I have to use the jQuery in this case. Perhaps i can validate the URL with it too?..

$("#go").click(function() {
    var $url = $("#url").val();
    <?php
    $x = @fopen($url,"r");
    if ($x) {
    ?>
        $("#ws").attr("src",url);
        $("#start").remove();
    <?php
        fclose($x);
    } else {
    ?>
        alert("bad URL");
    <?php
    }
    ?>      
});

Upvotes: 0

Views: 81

Answers (2)

Teena Thomas
Teena Thomas

Reputation: 5239

Learn the basics of PHP and javascript.

Upvotes: -1

Christofer Eliasson
Christofer Eliasson

Reputation: 33865

You are mixing client- and server-side languages. PHP is run on the server, before the page is served to the client. JavaScript (thus jQuery) does usually run on the client. Due to this, it doesn't make sense to mix the languages like in your example. You will have to separate them, using JavaScript on the client, making request to server. On the server you can then use PHP.

Step-by-step what you need to do:

  1. Use jQuery on the client side to get the address.
  2. Use jQuery to make an AJAX-request to the server, sending the URL to validate as data with the request.
  3. On the server-side you check if the URL is valid through PHP, using cURL or some other method. Then you return the result as JSON for instance.
  4. On the client-side, read the response and act accordingly.

Upvotes: 3

Related Questions