AJAX data does not flow to PHP
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 generic choice of AJAX and PHP code works, since I can manually create the $ item_code variable and the script works fine. I think my problem is in passing AJAX data to my PHP script.
+3
source to share
2 answers
You forgot to add method: 'POST'
to your AJAX call. And you have problems with your call. Check below:
$.ajax({
url: 'get_code.php',
method: "POST", // Change here.
data: {commodity_code: commodity_code}, // Change here.
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});
Or, to keep it simple, use a shorthand function:
$.post('get_code.php', {commodity_code: commodity_code}, function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
});
+6
source to share
the error is on this line data: "commodity_code: commodity_code",
.. you can just pass the variable commodity_code
..
$.ajax({
url: 'get_code.php',
method: "POST",
data: commodity_code,
dataType: 'json',
success:function(data) {
var commodity_desc = data[0];
alert(commodity_desc);
}
});
0
user5350813
source
to share