Mr Hery Mr Hery - 5 months ago 16
PHP Question

Sending GET from PHP parameter to AJAX

My coding isn't working. Please anyone could tell me why?
Here's the code:

AJAX code:

function sale(sale_code,sale_quantity) {
if (sale_code.length == 0 || sale_quantity == 0) {
alert("Product's code & quantity are required!");
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("show").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "sl.php?sdoc_no=<?= $sdoc_no ?>&sdoc_date=<?= $sdoc_date ?>&sale_code=" + sale_code + "&sale_quantity=" + sale_quantity, true);
xmlhttp.send();

}
}


HTML & PHP:

<?php $qitem = mysqli_query($conn, "SELECT * FROM stocks WHERE stock_type = 'product'");
while($ritem = mysqli_fetch_array($qitem)){ ?>

<div class="col-md-4 col-sm-6 text-center">
<button class="btn btn-info btn-block" type="button" onclick="sale(<?= $ritem['stock_code'] ?>, 1)"><?= $ritem["stock_name"] ?><br />
<small>RM <?= number_format($ritem["stock_sprice"], 2) ?></small>
</button>
</div>

<?php } ?>


sl.php file is working and returning data if i'm put it manually. And take note that I'm using bootstrap tab for this button.

Answer

You need to have quotes around string parameters in js:

Change:

sale(<?= $ritem['stock_code'] ?>, 1)

to:

sale('<?= $ritem['stock_code'] ?>', 1)

Then you should uri encode your parameters before you use them as url-parameters.

For JS, use encodeURI and for PHP, use urlencode;

Comments