-2

I am new to Ajax and I am confused as to how we pass data in Ajax. I have an index.php file which displays some data, it has a link to delete the record, now the problem is, I am not able to figure out how to transfer the id value from index.php of the selected record to ajax file. Also, how should I go about once I have fetched the value in delete.php page where lies the code to delete records. I have coded as below.

index.php

<div id="delMsg"></div>
<?php
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
echo "<table>";
while($row=mysqli_fetch_array($data))
{
    echo "<tr>";
    for($i=0;$i<$col;$i++)
    {
        echo "<td>".$row[$i]."</td>";

    }
    echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
    echo"</tr>";
}
echo "</table>";
?>

ajax-file.js

$(document).ready(function(){
    $(".del").click(function(event){
    event.preventDefault();
    $.ajax({
        url:"delete.php",
        method:"get",
        data:{id:'ID'},
        dataType:"html",
        success:function(str){
            $('#delMsg').html(str);
            }

        })

    })  
})

delete.php

<?php
$id=$_GET['id'];

$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"delete from member where id='$id'");
if($data)
{
    echo "success"; 
}
else
{
    echo "error";   
}

?>
Don'tDownvoteMe
  • 501
  • 2
  • 16

3 Answers3

0

you should use what is called JSON ( Javascript Object Notation, I think). This will let you order your data better to do that you have to use, json_encode.

Now I am not exactly sure what you mean by this id value from index.php

But taking your index.php file, I would change it like this

//make sure the is no space here
<?php
//start output buffering
ob_start();
$html = ['<div id="delMsg"></div>'];
$con=mysqli_connect("localhost","root","","ajaxtest");
$data=mysqli_query($con,"select * from member");
$col=mysqli_num_fields($data);
$html[] = "<table>";
while($row=mysqli_fetch_array($data))
{
    $html[] = "<tr>";
    for($i=0;$i<$col;$i++)
    {
        $html[] = "<td>".$row[$i]."</td>";

    }
    $html[] = "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";
    $html[] = "</tr>";
}
$html[] = "</table>";

$result = [
    'html' => implode("\n", $html),
    'debug' => ob_get_clean()
];

header("Content-type:application/json");
echo json_encode($result);

//?> ending tags are undesirable

Your JavaScript part will change too

$(document).ready(function(){
    $(".del").click(function(event){
    event.preventDefault();
    $.ajax({
        url:"delete.php",
        method:"get",
        data:{id:'ID'},
        dataType:"html",
        success:function(data){
            $('#delMsg').html(data.html);
            }

        })

    })  
})

You can see now that instead of just returning HTML, We will be returning it like this data in the Javascript and $result in php

{
  html : '<div id=" ...',
  debug : ""
}

I added ob_start and ob_get_clean this can be helpful because you cannot just echo content when outputting JSON, so this will catch any echo or print_r type content and put that into the debug item in the return.

ArtisticPhoenix
  • 21,464
  • 2
  • 24
  • 38
  • I am dynamically showing the records from the database using a loop. I want to fetch the "id" value of the record corresponding to which delete link is clicked so that that value could be sent to the server and delete action gets performed. – Don'tDownvoteMe Feb 16 '18 at 19:04
0

Hopefully this conveys the idea of how an AJAX call works.

The first thing we want to do is setup our trigger, which in your case is a button with an onclick event.

<script
  src="http://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

<!-- <button id="delete">Delete Something</button> -->
<button id="delete" onclick="onClickHandler(5)">Delete Something</button>

<p id="message">AJAX</p>

<script>
/* Notice I removed the document ready */
function onClickHandler(id)
{
    event.preventDefault();
    $.ajax(
    {
        url:"delete.php",
        method:"POST", /* In the real world you want to use a delete here */
        data: { /* plugin your data */
            id: id,
            name: "Bob",
            age: 25
        },
        dataType:"html",
        success: function(success)  {
            // Handle the success message here!

            if (success) {
                $('#message').text("Your message was received!");
            }
        },
        error: function(error) {
            // Handle your errors here
            $('#message').text("Something went wrong!");
        }
    });
};
</script>

Notice how my data is prepared in the data object. I leave it up to you to figure out how to grab data and set it in the right field. You could: $('#someId').value(); or pass it through a function. If this is a source of confusion I can clarify.

data: { /* plugin your data */
    id: 1,
    name: "Bob",
    age: 25
},

Next, we need to setup our script.

delete.php

<?php

    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

        // Obviously validate the data.
        // But this is how you access it.
        // $_POST is a global array, so you can access it like so:
        $id = $_POST['id'];
        $name = $_POST['name'];
        $age = $_POST['age'];

        // Do your server side stuff...
        $sql = "DELETE FROM member
                WHERE id = '{$id}' AND name = '{$name}' AND age = '{$age}'";

        // Do your SQL (delete) here
        // $con = mysqli_connect("localhost","root","","ajaxtest");
        // Use prepared statements http://bobby-tables.com/php
        // $data = mysqli_query($con,"delete from member where id='$id'");

        // if ($data) { // Your condition

        // This is where you would check if the query passed
        // and send back the appropriate message.
        if ($id) {
            echo json_encode($id);
        }
        else {
            echo http_response_code(500);
        }
    }
    else {
        echo "You don't belong here!";
    }
Kevin Pimentel
  • 2,056
  • 3
  • 22
  • 50
  • You have explained quite wonderfully but I am still confused as to how should I fetch "id" value which is stored in the query string in my code `echo "Delete";`? – Don'tDownvoteMe Feb 16 '18 at 19:00
  • I'll update my code to reflect this. – Kevin Pimentel Feb 16 '18 at 19:11
  • 1
    I removed document ready, added onclick param to button, and removed hard coded check for 1 in delete script. – Kevin Pimentel Feb 16 '18 at 19:14
  • Thanks a lot man! You have been a great help. I have up voted you but seems like someone else has down voted your answer. I'll mark your answer though. Thanks again for all the help. – Don'tDownvoteMe Feb 16 '18 at 19:23
  • I was wondering, what are you going to use in place of `if ($_SERVER['REQUEST_METHOD'] == 'POST')` if the method used is `get`? I think not using it will throw a `variables undefined` error. – SaurabhCooks Feb 17 '18 at 01:32
-1

Just replace

echo "<td><a class='del' href='delete.php' data-ID=$row[0]>Delete</a></td>";

To

echo "<td><a onclick="deleteRow($row[0])">Delete</a></td>";

Javascript

function deleteRow(recordID)
{
   event.preventDefault();
  $.ajax({
    type: "GET",
     url: "delete.php",
     data:{id: recordID}
    }).done(function( result ) {                    
      alert(result);
  });      
} 

In your PHP I recommend you to use PDO which is more easy and protected from SQL injection attacks. PHP:

    $db = new PDO('mysql:host=localhost;dbname=yourDB','root','');
$query = $db->prepare("Delete From yourTableName Where ID=:ID");
$id=$_GET['id'];
$query->bindParam('ID', $id);
$query->execute();

if ($query->rowCount()) {
    echo "success";
}
else
{
    echo "fails";
}
Sajjad Ali
  • 304
  • 3
  • 12