I’m working on an Add To Cart button, which passes an item’s ID and Quantity to a Javascript function. The function processes the values, creates a temporary form to POST the values and then reloads the product page with ?AddItem added to the url.
This is the working code:
function submitItem( ID, Code)
{
alert("Submission received"); //--This is being triggered
var toCart, inputA, inputB, quantity;
quantity = Code.value;
// Create form
toCart = document.createElement( 'form' );
toCart.action = " &AddItem";
toCart.method = 'post';
//Rest of the code excutes as normal
}
My product page is dynamically loaded, so the url for a category would be blah.com/products.php?cat=FOO, but the AddItem removes the cat= clause, so a blank page is loaded. To circumvent this, I’ve tried passing the category prefix (FOO) to the javascript, but the addition of a third parameter is breaking it.
This is my new code:
function submitItemCat( ID, Code, Category )
{
alert("Submission received"); //--This is not being triggered
var toCart, inputA, inputB, quantity;
quantity = Code.value;
// Create form
toCart = document.createElement( 'form' );
toCart.action = " &AddItem"+ Category; //--This is were I amend the URL
toCart.method = 'post';
//Rest of the code
}
and the function call in html
$jsCat = json_encode($_GET["cat"]); // This is FOO
echo'
<div id= "QuantBox">
<label for="Quantity">'.$catPrefix.'</label>
<input type = "text" name= "Quantity" id= "Q'.$row["StockCode"].'" value="1">
<a
class= "AddToCart"
onclick= "submitItemCat( '.$row["StockID"].', Q'.$row["StockCode"].', '.$jsCat.' )" >
</a>
</div>';
I’ve also tried passing the third variable as “FOO”, $_GET[“cat”] but none of them are working.
Any advice is much appreciated.
You’re probably missing quotes.
A quick fix would be
but this is horrible. Personally I’d refactor the code in order to avoid the building of inline javascript from PHP, for example by generating a clean javascript script with variable declared as