Pooja Kshatriya Pooja Kshatriya - 2 months ago 7
PHP Question

Am i getting html and javascript code when using ajax to pass parameters to the function on onClick event (Ajaxing on the same page)

<html>
tables, textbox, buttons
</html>

<?php

//some php, sql stuff


echo "<td><input type='button' name='disable' value='Disable' onClick='disable($id);'/></td>";

if(isset($_POST['action']) && $_POST['action']=="delete")
{
if(isset($_POST['ID']) && !empty($_POST['ID']))
{
$id = $_POST['ID'];
echo "Id:".$id;

//Call to another function

die();

}

?>

<script>
function disable(id) {
jQuery.ajax({ type: 'Post',
url: '',
data: {action: 'delete', ID: id}
})
.done(function(data) {
alert("Data Saved: " + data);
location.reload();
});
}

</script>


Alert box is showing html code which is in HTML block and successful messages from php block. I don't need to show HTML code, only need to show successful messages. How to do that??? many thanks

Answer

The issue is that you need to respond to the ajax request before any html is sent to the browser and call exit; to stop the remaining page content from being sent as well. Something like this would work:

<?php
if(isset($_POST['action']) && $_POST['action']=='delete'){
    // process request...... 
    $id = $_POST['ID'];
    echo "Id:".$id;
    //Call to another function 
    exit; // stop the script here so it doesnt also return the html content of the page
}
?>

<!DOCTYPE html>
<html>
<head>
</head>
<body>
tables, textbox, buttons

<?php
//some php, sql stuff 
// note that $id is not defined where you try to use it here in your code, not sure what that's about....
echo "<td><input type='button' name='disable' value='Disable' onClick='disable($id);'/></td>";
?>
<script>
    function disable(id) {
        jQuery.ajax({   type: 'Post',
            url: '',
            data: {action: 'delete', ID: id}
        })
            .done(function(data) {
                alert("Data Saved: " + data);
                location.reload();
            });
    }
</script>
</body>
</html>