简体   繁体   中英

JQuery, Ajax and PHP issue to isset method

I' ve a issue that I could not solve, I've read a lot of questions similar to my, but have not been able to solve.

This is my code:

Ajax call:

function download() {           
    var doctypeString = $('#doctypeComponent').attr('class')+"";
    var metaString = $('#metaComponent').attr('class')+"";
    var cssString = $('#cssComponent').attr('class')+"";
    var jsString = $('#jsComponent').attr('class')+"";
    var ajax = $.ajax({
        type: 'POST',
        url: 'php/download.php',
        data: {doctype : doctypeString, meta : metaString, css : cssString, js :  jsString},
        dataType: "text"
    });

    ajax.done(function() {
        window.location = 'php/download.php';           
    });

    ajax.fail(function(jqXHR, error) {
        alert("Request failed: "+error);
    });

}

Php code is:

if(isset($_POST['doctype'])){
    $doctype = $_POST['doctype'];
    writeFile($doctype);
} else {
    $doctype = "error doctype\n";
    writeFile($doctype);
}

if(isset($_POST['meta'])){
    $meta = $_POST['meta'];
    writeFile($meta);
} else {
    $meta = "error meta\n";
    writeFile($meta);
}

if(isset($_POST['css'])){
    $css = $_POST['css'];
    writeFile($css);
} else {
    $css = "error css\n";
    writeFile($css);
}

if(isset($_POST['js'])){
    $js = $_POST['js'];
    writeFile($js);
} else {
    $js = "error js\n";
    writeFile($js);
}

$file = $file."\n\t</head>\n\t<body>\n\t</body>\n</html>";

.

downloadFile("test.html");

function writeFile($content) {
    global $file;
    $file = $file.$content."";
}

function downloadFile($filename) {
    global $file; 
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-disposition: attachment; filename="'.basename($filename).'";');
    header('Content-Length: '.strlen($file));
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Expires: 0');
    header('Pragma: public');
    echo $file;
    exit;   
}

Isset is always false, why?

I've tried also with GET instead of POST, but nothing changed.

Thanks.

You have ajax.done() going to download.php , this means when download.php get POST value from ajax, and it succeed, you didn't take it's response back but redirect to download.php, when it redirect to download.php it doesn't POST or GET anything, means it will always show isset() false, for "REDIRECTED" part. replace your window.location with alert() and I am sure you will get your values posted.

change datatype for ajax function

dataType: "html" or remove dataType option

doctype is a reserved keyword in javascript.

Write it as 'doctype' :

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