AJAX not fetching data from PHP file using JQuery

I am trying to send data to a PHP file, but I cannot get data from a 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 is what I have in my 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 should not be updated. When I click on links (like Data1) it navigates to another page without getting data from the PHP file

+3


source to share


5 answers


You have several problems:



  • You are not using data as stated in other answers:
    success: function(data){ $("#someid").html(data); },

  • You do not cancel the default action of clicks, so your link will follow:
    $('a[class="some-class"]').click(function(e){ e.preventDefault(); ...

    ;
  • Since the id are integers, you can use data: "id=" + somedata,

    , although the sending of the object is more secure if somedata

    contains characters that must be escaped:
    data: {"id": somedata},

    ;
  • You have a problem with SQL injection. You must cast the variable to an integer or use the prepared statement $data = (int) $_POST['id'];

    :;
  • As mentioned in another answer, you have two functions $(document).ready()

    , one that wraps the other. You only need one.
+2


source


success: function(){
          $("#someid").html();
      },

      

it should be:



success: function(data){
          $("#someid").html(data);
      },

      

+1


source


Add parameter successfully

success: function(data){ //Added data parameter
      console.log(data);
      $("#someid").html(data);
  },

      

The data gets the values ​​that you echo back at the end of PHP.

+1


source


It:

  success: function(data){
      $("#someid").html(data);
  },

      

and you have two documents ready, so get rid of:

$(document).ready(function () { ...

});

      

+1


source


data: "id=" + somedata,

      

Change it to:

data: { id : somedata }

      

0


source







All Articles