-1

I'm trying to call a PHP script via AJAX but it seems like there is a problem I don't know what it is! I tried to use other solutions but I didn't understand them well. What I really want to do is call the PHP script via the AJAX code, then update the echo in the header with the data returned. Here's what I have done so far:

Header.php

<?php session_start(); ?>
<script src="https://code.jquery.com/jquery-3.4.1.slim.js" integrity="sha256-BTlTdQO9/fascB1drekrDVkaKd9PkwBymMlHOiG+qLI=" crossorigin="anonymous"></script>
<?php require_once('db/dbconnection.php'); ?>
<?php
    $result = $mysqli->query("SELECT * FROM task
    INNER JOIN user ON task.user_id = user.id
    WHERE username='$username' AND status = 'achieved'") or die($mysqli->error);

    $count = mysqli_num_rows($result);
?>
    <div class="done" data-tooltip="Achieved">
        <span><?php echo $count; ?></span>
    </div>

Dashboard.php

<link rel="stylesheet" href="css/dashboard.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.js" integrity="sha256-BTlTdQO9/fascB1drekrDVkaKd9PkwBymMlHOiG+qLI=" crossorigin="anonymous"></script>

<?php require_once('db/dbconnection.php'); ?>
<?php require_once("header.php"); ?>
<?php $result = $mysqli->query("SELECT * FROM `task`") or die($mysqli->error); ?>
<?php 
    while ($row = mysqli_fetch_array($result)):
?>
    <input type="checkbox" name="checkbox[]" value="<?php echo utf8_encode($row['id']); ?>">
    <p id="task"><?php echo utf8_encode($row['task']); ?></p>
<?php endwhile; ?>

<!-- js files -->
<script src="js/main.js"></script>

dashboard.css

input[type=checkbox]:checked~p {
text-decoration: line-through;
}

main.js

$(document).ready(function() {
   $("input[type='checkbox']").on('change', function() {
   var id = $(this).val();
   if (id) {
     $.ajax({
       type:'POST',
       url:'db/ajaxdata.php',
       data:'id='+id,
       success:function(html){
         $(".done").html(html);
       }
     });
   } else {
     //Error msg
   }
 });
});

ajaxdata.php

session_start();

require_once('dbconnection.php');

if ((isset($_POST['id'])) && (!empty($_POST['id']))){

    //Example
    $count = 2;
    echo "$count";

} else {
    header("location: /error.php");
}

Sorry if I didn't explain the problem properly!

M.Eddamoun
  • 31
  • 1
  • 7
  • What does your browser's Developer Tools windows' Network Tab say? Have you used your javascript debugger? – Dai Nov 02 '19 at 11:52
  • 1
    It is a very bad idea to use `die($mysqli->error);` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Nov 02 '19 at 12:28
  • 2
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Nov 02 '19 at 12:28
  • @Dharman Thank you, I started to learn about prepared statements and other security issues. – M.Eddamoun Nov 03 '19 at 11:30

4 Answers4

1

You explained well :-)

  1. use error callback function in ajax (main.js), so you can see what the error is coming
  $.ajax({
       type:'POST',
       url:'db/ajaxdata.php',
       data:'id='+id,
       success:function(html){
         $(".done").html(html);
       },
       error:function(html){
         $(".error").html(html);
         console.log(html);
       }
});
  1. Make sure you're redirecting the ajax request to absolute path ex. http://localhost/ajaxdata.php.

  2. Open the remote URL (http://localhost/ajaxdata.php) at browser and see what you get, may be you've an error in the db connection file.

  3. use exit(); in ajax if check

if ((isset($_POST['id'])) && (!empty($_POST['id']))){

    //Example
    $count = 2;
    echo $count;
    exit();

} else {
    header("location: error.php");
}
symi khan
  • 465
  • 5
  • 9
1

Edit your main.js to this.i have changed code within data and success

$(document).ready(function() {
   $("input[type='checkbox']").on('change', function() {
   var id = $(this).val();
   if (id) {
     $.ajax({
       type:'POST',
       url:'db/ajaxdata.php',
       data:{
          id: id
       },
       success:function(data){
         $(".done").html(data);
       }
     });
   } else {
     //Error msg
   }
 });
});
1

Try this:

$(document).ready(function() {
       $("input[type='checkbox']").on('change', function() {
       var id = $(this).val();
       if (id) {
         $.ajax({
           type:'POST',
           url:'db/ajaxdata.php',
           data:{id:id},
           success:function(response){
             $(".done").html(response);
           }
         });
       } else {
         //Error msg
       }
     });
    });
Ravi Ranjan
  • 269
  • 3
  • 2
0

I have solved the problem. It was a problem in the slim build of jQuery! which excludes the ajax. Just changed it to the uncompressed version and the problem was solved.

M.Eddamoun
  • 31
  • 1
  • 7