I am having trouble passing AJAX data to PHP. I am experienced with PHP but new to JavaScript.
HTML / JavaScript
<input type="text" id="commodity_code"><button id="button"> = </button>
<script id="source" language="javascript" type="text/javascript">
$('#button').click(function()
{
var commodity_code = $('#commodity_code').val();
$.ajax({
url: 'get_code.php',
data: "commodity_code: commodity_code",
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});
});
</script>
PHP
$commodity_code = $_POST['commodity_code'];
$result = mysql_query("SELECT description FROM oc_commodity_codes WHERE code = '$commodity_code'");
$array = mysql_fetch_row($result);
echo json_encode($array);
I know the general AJAX fetch and PHP code is working as I can manually create the $commodity_code variable and the script works fine. I think my issue lies somewhere in passing the AJAX data to my PHP script.
mysql_database library that you're using is end-of-life. It was deprecated several years ago and removed entirely in PHP 7 due to security concerns, including (but not limited to) its inability to support parameterised queries to better protect against SQL Injection attacks. As it is, you are running unsupported code and your system is very vulnerable to injection attacks. If this is new code, you should absolutely not be usingmysql_, if it's old code you should plan to upgrade a.s.a.p. You should switch tomysqli_orPDOand start using parameterised prepared statements.