简体   繁体   English

运行php-script后没有Ajax成功

[英]No Ajax success after php-script is run

I have a php-script which performs a database backup of my website. 我有一个php脚本,可以对我的网站进行数据库备份。 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. 我想在管理面板中实时显示一些文本,告诉用户正在进行备份以及何时完成备份(过程大约需要1分钟)。

I believe using Ajax is the only reasonable way of doing this, and I have tried the following so far: 我相信使用Ajax是这样做的唯一合理方法,到目前为止,我已经尝试了以下方法:

<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? 在工作中,我需要在php文件中有一些特定的东西吗?

Any help is much appreciated! 任何帮助深表感谢!

EDIT: added the php script as requested 编辑:按要求添加了PHP脚本

<?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. 您的脚本db_backup.php应该以JSON格式输出内容,回显类似内容。

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. 如果返回falsetrue ,则对调用哪个回调处理程序没有影响。 You need to send an HTTP status code in your response headers. 您需要在响应标头中发送HTTP status code That is the only way jQuery can determine if the request was successful. 这是jQuery可以确定请求是否成功的唯一方法。

Lastly. 最后。 You only have a success callback. 您只有一个成功回调。 Your code should still work unless the server side returned a 4xx or 5xx response code. 除非服务器端返回4xx5xx响应代码,否则您的代码仍将正常工作。 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. 您可以将一个函数,而不是then称为always作为一个回调处理程序。 This will fire a callback regardless of the outcome. 无论结果如何,这都会触发回调。

I recommend investigating what I said in the jQuery docs. 我建议调查一下我在jQuery文档中所说的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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