Hello guys I am new to javascript
I am trying to send php variable to AJAX url file but i was unable to do it. I don’t know where the problem actually arise. your help will be highly appreciated
Here i want to send the below PHP Variable "$cheque" to the AJAX URL Page cheque_select.php
<php? $cheque = '78964Y' ?>
$(document).ready(function(){
function fetch_data()
{
$.ajax({
url:"cheque_select.php",
method:"POST",
dataType:"json",
success:function(data)
{
var html = '';
for(var count = 0; count < data.length; count++)
{
html += '<tr>';
html += '<td><input type="checkbox" id="'+data[count].id+'" data-cheque_no="'+data[count].cheque_no+'" data-id="'+data[count].id+'" data-name="'+data[count].name+'" data-sum="'+data[count].sum+'" data-account="'+data[count].account+'" class="check_box" /></td>';
html += '<td>'+data[count].cheque_no+'</td>';
html += '<td>'+data[count].id+'</td>';
html += '<td>'+data[count].name+'</td>';
html += '<td>'+data[count].sum+'</td>';
html += '<td>'+data[count].account+'</td></tr>';
}
$('tbody').html(html);
}
});
}
fetch_data();
This is my cheque_select.php i want to fetch data from mysql by the above variable
<?php
include('connection.php');
$query = "select * FROM entry where entry.bank= $cheque";
$statement = $connect->prepare($query);
if($statement->execute())
{
while($row = $statement->fetch(PDO::FETCH_ASSOC))
{
$data[] = $row;
}
echo json_encode($data);
}
?>
2
Answers
Add
data
in your AJAX request like –It will send the cheque value to the server end.
And get it at the PHP end just before the query by adding –
Simply add a "data" value in the ajax/jquery request you are firing. This will send data in the form of a POST value to the page that is receiving your ajax request. This is the revised "fetch_data" function after adding the data you wish to send:
Then on the page that is receiving the request, you would get the cheque value by saying
php $_POST['cheque']
. Also one mistake I noticed is you have mistyped your opening PHP tag. You have wrote<php?
. The correct way is<?php
.One more thing – you haven’t prepared your statement correctly in the PHP page. This is how you should prepare it:
Preparing statements like this prevents SQL injection