I am trying to send a variable with jquery to a php script now this is my first try after reading the documentation but it wont work. can anyone give me some advice ? I didn't realize the error in code. The variable I want to send is $id. I defined it with '1'
<?php
$id = '1';
?>
jquery part
<script>
$(document).ready(function() { // Anfang Dokument Ready Funktion
$("p").click(function () { // Anfang Klick Funktion
var id = $(this).html(); // Inhalt in Klickfunktion
// Beginn Ajax Segment mit Angabe von Typ Url Data und Div #ausgabe
$.ajax({
type: 'POST',
url: 'http://localhost/ajax.php',
data: 'id='+id',
success: function(data){
$('#ausgabe').html(data);
}
}); // Ende Ajax Segment
}); // Ende Klick Funktion
}); // Ende Dokument Ready Funktion
</script>
<div id="ausgabe"></div>
<p><button>Sende Variable</button></p>
The ajax.php
<?php
$id = $_POST['id'];
echo $id;
?>
The right form to send info with ajax to PHP is:
$.ajax({
type: 'POST',
url: 'http://localhost/ajax.php',
data: id:id,
success: function(data){
$('#ausgabe').html(data);
}
});
To send by reference. If you want to send without reference just use:
$.ajax({
type: 'POST',
url: 'http://localhost/ajax.php',
data: id,
success: function(data){
$('#ausgabe').html(data);
}
});
Rely on data-*
attributes better:
HTML
<a href="#" data-id="<?php echo $id; ?>">Click me</a>
JS
$(function(){
$('a[data-id]').click(function(event){
event.preventDefault();
// $(this).data('id') fetches the data-id attribute from your anchor
$.post( someUrl, { id : $(this).data('id')} ).done(function(){ ... })
})
})
Simple Send it like this
$.ajax({
type: 'POST',
url: 'http://localhost/ajax.php',
data: {id : <?php echo $id ?>},
success: function(data){
$('#ausgabe').html(data);
}
}); // Ende Ajax Segment