NuwanD NuwanD - 6 months ago 7
PHP Question

Passing values through javascript to php

I'm creating small shopping-cart program, I'm using following code to input values.

<input type="button" value="Add to Cart : <?php echo $row['PART_NO']; ?>" onclick="addtocart('<?php echo $item; ?>')" />


value goes through following javascript code.

function addtocart(pid){
alert(pid);
document.form1.productid.value=pid;
document.form1.command.value='add';
document.form1.submit();
}

<body>
<form name="form1">
<input type="hidden" name="productid" />
<input type="hidden" name="command" />
</form>

<?php
if ( isset($_REQUEST['command']) && $_REQUEST['command'] == 'add' && $_REQUEST['productid']>0 ){
$pid=$_REQUEST['productid'];
addtocart($pid,1);
header("location:shoppingcart.php");
exit();
}

?>


when I'm inserting
productid
like
02190249
it goes through javascript code and php code and loading the shoppingcart.php. but inserting
productid
like
PF161202
its not loading the
shoppingcart.php
. how can I pass values like
PF161202
to php code through js.

Answer

Remove $_REQUEST['productid']>0 from your php code. It is checking only for numbers(02190249) which is greater then 0 but as per your question you are passing a string(PF161202).

<?php
if ( isset($_REQUEST['command']) && $_REQUEST['command'] == 'add' && ($_REQUEST['productid'] != '')){
    $pid=$_REQUEST['productid'];
    addtocart($pid,1);
    header("location:shoppingcart.php");
    exit();
}
?>
Comments