cycloidistic
cycloidistic

Reputation: 305

Echoed Javascript Code from PHP Via AJAX Not Running

My code is meant to get the author of an inputted book using the Google Books API via AJAX. If nothing is inputted it prints "Empty". What it actually does is print out the Javascript code when a book is inputted. When nothing is inputted, it prints "Empty" as it should. How could I modify my code to make the echoed Javascript execute and hence get the author of an inputted book?

Just to see, I replaced the echo part with echo "<script>document.getElementById('txtBox').innerHTML = 'Hello';</script>";. It also prints out the javascript code, so I don't think it has something to do with using the API.

getAuthor.html

<!DOCTYPE html>
<html>  
  <body>
	<!-- Input -->
    <div class="form">
      <form onsubmit="makeRequest(); return false">
        <input type="text" id="inputText" name="inputText">
        <input type="submit">
      </form>
    </div>
	
    <br>
    
    <!-- Output -->
    <div class="txtBox">
      <textarea  id="txtBox">
      </textarea>
    </div>
    
    <!-- AJAX to create output using jEcho.php file-->
    <script>
        function makeRequest() {
            httpRequest = new XMLHttpRequest();
            console.log(httpRequest.responseText);
            httpRequest.onreadystatechange = function() {               
                document.getElementById("txtBox").innerHTML = httpRequest.responseText;
            };
            httpRequest.open("POST", "jEcho.php", true);
            httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");
            httpRequest.send("inputText=" + document.getElementById("inputText").value);
        }

    </script>
  </body>
</html>

jEcho.php

<?php
$input = $_POST["inputText"];

if ($input == "") {
    echo "Empty";
} else {
    // used to parse
    // e.g. The Rosie Project -> The+Rosie+Project
    $temp = str_replace(" ", "+", $input);    
    
    // create appropiate source
    $scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";
    
    echo "<script>
           function handleResponse(response) {
              var item = response.items[0];
              document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
            }
          </script>
          <script src='$scriptSource'></script>";
}
?>

Links

Echoing Javascript From PHP:

How to call a JavaScript function from PHP?

Echoing javascript from PHP

Google Books API:

https://developers.google.com/books/docs/v1/getting_started

https://developers.google.com/books/docs/v1/using

Upvotes: 0

Views: 117

Answers (3)

user149341
user149341

Reputation:

<script> elements are only run when your page is first loaded. Script elements created later on, either by assigning to an element's .innerHTML, creating them using document.createElement(), or otherwise, are not executed.

If you want to have a PHP script send back code to be evaluated, you'll have to do that directly, e.g:

httpRequest.onreadystatechange = function() {               
    eval(httpRequest.responseText);
};

(And remove the <script> tags from the response.)

Upvotes: 1

Salamander115
Salamander115

Reputation: 29

I'm not allowed to comment so:

I'm not certain what has caused it for but could <script src='$scriptSource'></script>"; be called before the handleResponse function. I'm not too sure what is causing it, at the moment, that is my best idea.

Also could you not just have the url already in the code like this: (jEcho.php)

<?php
$input = $_POST["inputText"];

if ($input == "") {
    echo "Empty";
} else {
    // used to parse
    // e.g. The Rosie Project -> The+Rosie+Project
    $temp = str_replace(" ", "+", $input);    

    // create appropiate source
    //$scriptSource = "https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse";

    echo "
          <script src='https://www.googleapis.com/books/v1/volumes?q=$temp&callback=handleResponse'></script>
          <script>
              function handleResponse(response) {
                 var item = response.items[0];
                 document.getElementById('txtBox').innerHTML = item.volumeInfo.authors[0];
              }
          </script>";
}
?>

Upvotes: 0

NeiL
NeiL

Reputation: 801

Try setting header in jEcho.php file (not tested)

header('Content-Type: application/javascript'); 

Upvotes: 0

Related Questions