简体   繁体   中英

No Ajax success after php-script is run

I have a php-script which performs a database backup of my website. This backup-script can be triggered by clicking a button on the websites' admin-panel.

I'd like to have some text in the admin-panel that tells the user when the backup is ongoing and when it's complete (process takes about 1 minute) in real-time.

I believe using Ajax is the only reasonable way of doing this, and I have tried the following so far:

<button id="btn">Backup</button>
<script>
    $("document").ready(function(){
        $("#btn").click(function(){
            $.ajax({
                type: "POST",
                dataType: "json",
                url: "backup/db_backup.php",
                success: function(data) {
                    alert("success!!!");
                }
            });
        });
    });
</script>

The above does run the backup-script just fine, but I'm unsure why the alert doesn't trigger once the script has finished running. Is there something specific in the php-file I need to have for this to work?

Any help is much appreciated!

EDIT: added the php script as requested

<?php
    include_once '../includes/db_connect.php';

    ini_set("max_execution_time", 0);

    $zip = new ZipArchive();
    $dir = "backups";

    if(!(file_exists($dir))) {
        mkdir($dir, 0777);
    }

    $p = backup_tables($mysqli);
    echo $p;
    if (glob("*.sql") != false) {
        $filecount = count(glob("*.sql"));
        $arr_file = glob("*.sql");

        for($j=0;$j<$filecount;$j++) {
            $res = $zip->open($arr_file[$j].".zip", ZipArchive::CREATE);
            if ($res === TRUE) {
                $zip->addFile($arr_file[$j]);
                $zip->close();
                unlink($arr_file[$j]);
            }
        }
    }

    //get the current folder name-start
    $path = dirname($_SERVER['PHP_SELF']);
    $position = strrpos($path,'/') + 1;
    $folder_name = substr($path,$position);
    //get the current folder name-end

    $zipname = date('Y/m/d');
    $str = "dRbot-".$zipname.".zip";
    $str = str_replace("/", "-", $str);

    // open archive
    if ($zip->open($str, ZIPARCHIVE::CREATE) !== TRUE) {
        die ("Could not open archive");
    }

    $zip->addFile(realpath($folder_name . "/" . $p));
    // close and save archive
    $zip->close();
    echo "Archive created successfully.";

    copy("$p.zip", "$dir/$str");
    unlink("$p.zip");

    /* backup the db OR just a table */
    function backup_tables($mysqli, $tables = '*') {
        //get all of the tables
        if($tables == '*') {
            $tables = array();
            $result = $mysqli->query('SHOW TABLES');
            while($row = $result->fetch_array(MYSQLI_NUM)) {
                $tables[] = $row[0];
            }
        } else {
            $tables = is_array($tables) ? $tables : explode(',',$tables);
        }
        $return = "";

        //cycle through
        foreach($tables as $table) {
            $result = $mysqli->query('SELECT * FROM '.$table);
            $num_fields = mysqli_field_count($mysqli);
            $return.= 'DROP TABLE '.$table.';';
            $result2 = $mysqli->query('SHOW CREATE TABLE '.$table);
            $row2 = $result2->fetch_row();
            $return.= "nn".$row2[1].";nn";

            while($row = mysqli_fetch_row($result)) {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j<$num_fields; $j++) {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = preg_replace("#n#","n",$row[$j]);
                    if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                    if ($j<($num_fields-1)) { $return.= ','; }
                }
                $return.= ");n";
            }
            $return.="nnn";
        }

        //save file
        $path = 'db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql';
        $handle = fopen($path,'w+');
        fwrite($handle,$return);
        fclose($handle);
        return $path;
    }

?>

Your script db_backup.php should output something in JSON format, echo something like this.

echo json_encode(array('success'));

OR

You can change your code to this:

<button id="btn">Backup</button>
<script>
    $("document").ready(function(){
        $("#btn").click(function(){
            $.ajax({
                type: "POST",
                url: "backup/db_backup.php",
                success: function(data) {
                    alert("success!!!");
                }
            });
        });
    });
</script>

I would try something like this:

 var serverCall=function(){
      var ajax=$.ajax({
            type: "POST",
            dataType: "json",
            url: "backup/db_backup"
        });


     return ajax.then(function(data,status,xhr){
                              // success
                }, function(){
                    // fail
                });

  }



 $("#btn").on('click',serverCall);

That should give you what you want. One thing to keep in mind is what you are returning from your server code. If you are returning false or true , it will have no impact on which callback handler is called. You need to send an HTTP status code in your response headers. That is the only way jQuery can determine if the request was successful.

Lastly. You only have a success callback. Your code should still work unless the server side returned a 4xx or 5xx response code. Then it will fire the fail callback handler, which you don't have, so nothing will happen. You can attach a function instead of then called always as a callback handler. This will fire a callback regardless of the outcome.

I recommend investigating what I said in the jQuery docs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM