I'm trying post data to PHP file but i can't receive any data from PHP file. Let me add codes. This is my jQuery function:
$(document).ready(function () {
$(function () {
$('a[class="some-class"]').click(function(){
var somedata = $(this).attr("id");
$.ajax({
url: "foo.php",
type: "POST",
data: "id=" + somedata,
success: function(){
$("#someid").html();
},
error:function(){
alert("AJAX request was a failure");
}
});
});
});
});
This is my PHP file:
<?php
$data = $_POST['id'];
$con = mysqli_connect('localhost','root','','somedatabase');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"database");
$sql="SELECT * FROM sometable WHERE id = '".$data."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo $row['info'];
}
mysqli_close($con);
?>
This what i have in HTML file:
<p id="someid"></p>
<a href="#page2" class="some-class" id="1">Data1</a>
<a href="#page2" class="some-class" id="2">Data2</a>
Note: This website is horizontal scrolling and shouldn't be refreshed. When i'm clicking links (like Data1) it's going to another page without getting data from PHP file
You have a few problems:
success: function(data){ $("#someid").html(data); },
$('a[class="some-class"]').click(function(e){ e.preventDefault(); ...
;data: "id=" + somedata,
although sending an object is safer in case somedata
contains characters that need to be escaped:data: {"id": somedata},
;$data = (int) $_POST['id'];
;$(document).ready()
functions, one wrapping the other. You only need one.success: function(){
$("#someid").html();
},
should be:
success: function(data){
$("#someid").html(data);
},
You should add parameter in success
success: function(data){ //Added data parameter
console.log(data);
$("#someid").html(data);
},
The data get the values what you echo in PHP end.
This:
success: function(data){
$("#someid").html(data);
},
and you have two document ready, so get rid of:
$(document).ready(function () { ...
});
data: "id=" + somedata,
Change it to:
data: { id : somedata }