1

I'm writing some code that has a variable in JavaScript that must be passed into the PHP script in the same document. The user input will be used to be scraped from some external site.

The JavaScript variable is HtmlLink, and it needs to be passed to the PHP code where it says INSERT HTMLLINK VARIABLE HERE without reloading the page.

<!DOCTYPE HTML>
<HEAD>
   <TITLE>Test Input</TITLE>
   <SCRIPT>
      type = "text/javascript"
      function testResults (form) {
         var TestVar = form.inputbox.value + ".html";
         var HtmlLink = "www.mp3skull.com/mp3/" + TestVar;
         document.write(HtmlLink);
      }
   </SCRIPT>
   <?php
      $contents = file_get_contents('INSERT HTMLLINK VARIABLE HERE');
      $dom = new DOMDocument();
      libxml_use_internal_errors(true);
      $dom->loadHTML($contents);
      libxml_clear_errors();
      $xpath = new DOMXpath($dom);

      $element = $xpath->query('//div[@id="right_song"]/div[3]/div[1]/div[1]/a')->item(0)-                    
      echo $element;  
   ?>  
</HEAD>
<BODY>
   <FORM NAME="myform" ACTION="" METHOD="GET"> Song Name <BR>
      <INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
      <INPUT TYPE="button" NAME="button" Value="Search" onClick="testResults(this.form)">
   </FORM>
</BODY>
</HTML>
6
  • I would have thought that allowing this to happen would open you up to allowing anyone to load whatever file they wanted to, that your PHP user has access to there? Ie. a bad thing Commented Jul 23, 2014 at 22:11
  • Thanks for your reply, but how would this open up my server to the user/client loading any server files? Commented Jul 23, 2014 at 22:27
  • The javascript function can be set to anything by the user to change the path to whatever they want. You'd be better having the main path in the PHP code and simply taking a song name as the variable. You would probably be better off in the long run turning this into an ajax call. Commented Jul 23, 2014 at 22:33
  • Yes alright thank you, that helps and I agree with you that this is a poor way of accomplishing the task, and that the main path should be in the php code block. Although I should be able to make this work as an ajax call, I would still like to use this as an opportunity to learn... In the future I may need to pass a variable from JavaScript to php, could you tell me how I would do this? Thanks Commented Jul 23, 2014 at 22:48
  • I've not used this approach, the main problem I would anticipate is that your PHP script needs to have the information available when it loads, whereas your form can't do anything until after it has loaded and received user input. You can use the javascript to redirect to the same URL with a URL variable set and then pick that up from the PHP with a conditional block around the whole script so that it only runs when the variable is passed (remember to validate the variable), but doing this you don't really need the form. Commented Jul 23, 2014 at 22:55

2 Answers 2

1

If you want to do some searching, first of course build the proper URL first, then from there search/scrape the site, actually the base code is already working so its time to build on that. You can do something like this: Sample Demo

$main_url = 'http://www.mp3skull.com/mp3/';
$results = array();

if(isset($_POST['submit'])) {
    // handle input (sample: hot mallets)
    $input = preg_replace('/[\s]+/', '_', strtolower(trim($_POST['input'])));
    $main_url .= $input . '.html'; // turns to hot_mallets.html

    $contents = @file_get_contents($main_url);
    if($contents !== false) { // simple error checking

        $dom = new DOMDocument();
        libxml_use_internal_errors(true);
        $dom->loadHTML($contents);
        libxml_clear_errors();
        $xpath = new DOMXpath($dom);

        $search_results = $xpath->query('//div[@id="song_html"]');
        if($search_results->length > 0) {
            foreach($search_results as $result) {
                // each row result, put it inside the array
                $results[] = $xpath->query('//div[@id="right_song"]/div[3]/div[1]/div[1]/a', $result)->item(0)->getAttribute('href');
            }
        } else {
            echo 'Zero results';
        }


    } else {
        echo 'Some error on getting results from external site.';
        exit;
    }
}

?>

<form method="POST">
    <label for="inputbox">Song Name: <input type="text" id="inputbox" name="input"/ ></label>
    <input type="submit" name="submit" />
</form>
<?php if(!empty($results)): ?>
<h3>Search Results:</h3>
<ul>
    <?php foreach($results as $result): ?>
        <li><?php echo $result; ?></li>
    <?php endforeach; ?>
</ul>
<?php endif; ?>
Sign up to request clarification or add additional context in comments.

Comments

0

Because of the way that pages are loaded on the web this doesn't really make sense in most setups. The PHP runs on the server, sends the javascript and HTML to the client and then the javascript executes on the client. At that point in the process it's too late for javascript to set a variable in php because php is already finished loading. You could use ajax to send the request from javascript. If you did that the page would load like this:

(Server gives initial HTML/javascript/CSS to client)->(Client runs javascript which makes request to server (after the user has entered the data))->(Result of external request returns and is now usable by javascript).

You don't really need to do that for what you're trying to do though - fetch a link off of another page. What you should really do is write your javascript stuff in php and then echo out the link. Then, set the form to submit back to the same page. Here's an example:

<!doctype html>
<head>
    <title>Fetch Link</title>
</head>
    <body>
        <?php
            ini_set('display_errors', 0);
            if (isset ($_GET['search_term']))
            {
                $searchTerm = $_GET['search_term'];
                $searchPage = "http://www.example.com/".$searchTerm.'.html';
                $searchPageContents = file_get_contents($searchPage);
                $feedBack = '';
                $failedMessage = 'Sorry, we couldn\'t match your search =(';

                if ($searchPageContents !== FALSE)
                {
                    $searchPageDom = new DOMDocument();

                    if (!$searchPageDom->loadHTML($searchPageContents))
                        $feedBack = $failedMessage;
                    else
                    {
                        $searchPageXpathWrapper = new DOMXpath($searchPageDom);
                        $searchLinkNode = $searchPageXpathWrapper
                        ->query('SOME QUERY HERE')
                        ->item(0);

                        $searchLink = $searchPageDom->saveHTML ($searchLinkNode);
                        $feedBack = $searchLink;
                    }
                }
                else
                    $feedBack = $failedMessage;

            }
            else
                $feedBack = 'Please enter a search term';

            echo $feedBack.'<br>';
        ?>
        <form name="myform" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="GET">
            <label for='search_name' for='search_term'>Search Term</label>
            <input type="text" name="search_term">
            <input type='submit' value='Search'>
        </form>
    </body>
</html>

Of course, unless you have a particularly good reason to be fetching the link from the page instead of just generating the link yourself - you can generate the link yourself with minimal javascript and save the round trip to the server and guard against the possibility of the page formatting changing on the other side.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.