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.";
}
?>