0

I have 3 files; 1.html, 2.js, 3.php

I'm trying to get the value of a variable in 3.php to update in an element in 1.html

In 3.php I have a variable $title

In 2.js I'm trying:

var titlePHP = <?php echo json_encode ($title); ?>;
            console.log(titlePHP);
            $('#productTitle').val(titlePHP);

But getting Uncaught SyntaxError: Unexpected token <

I've tried the 3 solutions in How to pass variables and data from PHP to JavaScript? but they only seem to work if all the code is on the same page, but my code has to be seperate because these files are doing extra things.

I can update a single DOM element using echo in php, but I need to pass multiple variables across, so echo is insufficient.

Is there a better solution to my problem? Thanks

edit:

2.js:

$(function() {

    //Get the ASIN input
    var form = $('#inputASIN');

    //Get the div to update
    var formReply = $('#formReply'); //status

    //event listener for the contact form.
    $(form).submit(function(e) {
        e.preventDefault();

        //serialise the form data.
        var formData = $(form).serialize();
        //submit the form using AJAX.
        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {
            $(formReply).toggleClass('card-footer bg-success text-white');
            $(formReply).text(response);

            $('#asinForm').val('');
        })
        .fail(function(data) {
            $(formReply).toggleClass('card-footer bg-danger text-white');

            // Set the message text.
            if (data.responseText !== '') {
                $(formReply).text(data.responseText);
            } else {
                $(formReply).text('Error: could not load data from API.');
            }
        });

    });

});

3.php:

    <?php

      if ($_SERVER["REQUEST_METHOD"] == "POST") {
            include("amazonApiClass.php");
            $obj = new AmazonProductAPI();
            $asin = $_POST["ASIN"];

            if (empty($asin)) {
                  echo "Error: Please enter an ASIN!";
                  exit;
            }

            //fetch product information with the object
            try {
                  $result = $obj->getItemByAsin($asin);
                  echo "Success! Move on to step 2.";
            }
            catch(Exception $e)
            {
                  echo $e->getMessage();
            }



            $title = $result->Items->Item->ItemAttributes->Title;
            $price = $result->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice;    


            echo "Title: $title<br />";
            echo "Price: $price<br />";

      } else {
        echo "Error: could not load data from API.";
    }

?>
  • 2
    You need to use AJAX from 2.js to get the variable from 3.php. – Barmar Feb 13 '19 at 23:40
  • Where is `2.js` included? In `1.html` or `3.php`? What is the relationship between `1.html` and `3.php` anyway? Please describe how your application is structured – Phil Feb 13 '19 at 23:47
  • From the linked question, the top voted answer's first option is to use AJAX but it doesn't sound like you've tried that at all. That certainly doesn't require _"all the code is on the same page"_ – Phil Feb 13 '19 at 23:51
  • If you disagree with the duplicate vote, please update your question with the any attempts you made based on the other answers – Phil Feb 13 '19 at 23:56
  • @Phil 2.js is included in 1.html. Basically 1.html is a form that takes an input and sends it to 3.php to query an API. 2.js is a middleman to stop the page redirecting and it updates elements on 1.html I tried the AJAX answer from the other SO I linked, but I could not get it to work. – Tom Vanlaer-McCanna Feb 13 '19 at 23:56
  • Right, so sounds like you want `2.js` to make an AJAX request to `3.php` (triggered by an event in `1.html`) and then use the response to make changes on `1.html`. This scenario is detailed in [this answer](https://stackoverflow.com/a/23740549/283366) – Phil Feb 13 '19 at 23:58

1 Answers1

-1

You can't add PHP code into an external (.js) JavaScript file, as JavaScript itself has no knowledge of how PHP works. You also can't make use of 1.html, as HTML doesn't know how PHP works either.

What you're probably looking to do is make use of inline JavaScript on 3.php (or another .php page):

<?php
  $title = "Title";
?>
<script>
  var titlePHP = <?php echo $title; ?>
<script>

Unlike with trying to output the PHP directly into the JavaScript file, this will work. Your PHP file will see <?php, and swap to PHP to inject its variable on page load, then see ?> and swap back to JavaScript:

<script>
  var titlePHP = "Title";
<script>
Obsidian Age
  • 41,205
  • 10
  • 48
  • 71