Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return php variable to jquery ajax

Tags:

jquery

ajax

php

I have an ajax function in jquery calling a php file to perform some operation on my database, but the result may vary. I want to output a different message whether it succeeded or not

i have this :

echo '<button id="remove_dir" onclick="removed('.$dir_id.')">remove directory</button>';

<script type="text/javascript">
    function removed(did){
        $.ajax({ 
            type: "POST", 
            url: "rmdir.php", 
            data: {dir_id: did},
            success: function(rmd){ 
                if(rmd==0)
                    alert("deleted");
                else
                    alert("not empty");
                window.location.reload(true);
            } 
        }); 
    }
</script>

and this

   <?php
require('bdd_connect.php');
require('functions/file_operation.php');
if(isset($_POST['dir_id'])){
    $rmd=remove_dir($_POST['dir_id'],$bdd);
}
?>

my question is, how to return $rmd so in the $.ajax, i can alert the correct message ?

thank you for your answers

like image 261
user1385745 Avatar asked Aug 31 '26 17:08

user1385745


2 Answers

PHP

<?php
   require('bdd_connect.php');
   require('functions/file_operation.php');
   if (isset($_POST['dir_id'])){
      $rmd=remove_dir($dir_id,$bdd); 
      echo $rmd;
   }
?>

JS

function removed(did){
    $.ajax({ 
        type: "POST", 
        url: "rmdir.php", 
        data: {dir_id: did}
    }).done(function(rmd) {
         if (rmd===0) {
            alert("deleted");
         }else{
            alert("not empty");
            window.location.reload(true);  
         }
    });
}
like image 120
adeneo Avatar answered Sep 02 '26 12:09

adeneo


i advice to use json or :

if(isset($_POST['dir_id'])){
    $rmd=remove_dir($dir_id,$bdd);  
    echo $rmd;
}
like image 41
mgraph Avatar answered Sep 02 '26 11:09

mgraph