Reputation: 1510
I made a basic AJAX function calling a php file. The response is a HTML to be inserted in a "content box" of my main page
function LoadAjax_alert_display_one(){
id_alert = <?php echo $id_alerte; ?>;
$('.preloader').show();
$.ajax({
mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
url: 'ajax/alert_display_one.php',
data: "id_alerte="+id_alert,
type: 'GET',
success: function(data) {
$('#ajax-content').html(data);
$('.preloader').hide();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
dataType: "html",
async: false
});
}
That's working fine. The called file 'alerts_create.php' is also runinng a php to get data from the database and displays it using a while loop
while ($stmt->fetch()) {
echo "<tr>";
echo "<td><a href='#' onclick='LoadAjax_alert_display_one();'>" . $nom_alerte . "</a></td>";
echo "<td>" . $country . "</td>";
echo "</tr>"; }
My issue is that I cannot properly pass the link I create in the while loop. The $nom_alerte always takes the value of the last iteration of the loop. So my AJAX take this as link value; any ideas how I can do that?
To clrify my title: my issue is to send a php variable to the called file ('alerts_create.php') and to retrieve an HTML result.
SOLUTION: just had to pass the php variable as the AJAX function parameter:
function LoadAjax_alert_display_one(id_alerte){
$('.preloader').show();
$.ajax({
mimeType: 'text/html; charset=utf-8', // ! Need set mimeType only when run from local file
url: 'ajax/alert_display_one.php',
data: "id_alerte="+id_alerte,
type: 'GET',
success: function(data) {
$('#ajax-content').html(data);
$('.preloader').hide();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
},
dataType: "html",
async: false
});
}
Upvotes: 0
Views: 103
Reputation: 1020
Use something like this
<script type="text/javascript">
var data = 'abc=0';
$.post(
'yoururl.php',
data
).success(function(resp){
var json = $.parseJSON(resp);
console.log(json);
});
and in php file use like this
while( $stmt->fetch() ) {
$data[] = array(
'link' => 'your link'
);
}
echo json_encode($data);
Upvotes: 1