Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP echo javascript doesnt work in if statement

So the code looks like this:

<script>
function createFolder(folder){
    $.ajax({
    url: "index.php",
    type: "POST",
    data: {'folder':folder},
    success: function(data) {
        console.log("successful post");
        }
    });
}
</script>

<?php
if(isset($_POST["folder"])){
    $folder = $_POST["folder"];
    if(!file_exists($folder)) {
        mkdir($folder);                         <--- this code runs
        echo '<script>alert("qwe")</script>';   <--- this code doesnt run 
    }
    else {
        echo '<script>alert("qwer")</script>';  <--- this code doesnt run
    }
    echo '<script>alert("qwert")</script>';     <--- this code doesnt run 
}
echo '<script>alert("qwerty")</script>';        <--- this code runs
?>

..so in the if-statement where I check the file exists the echo doesnt work, but the mkdir($folder) command runs successfully and it is a bit confusing for me. Why echo doesnt work if it in an if-statement?

like image 408
kreestyahn Avatar asked Feb 14 '26 15:02

kreestyahn


1 Answers

The <script> tags will only be executed if you put them into the HTML of a DOM element. That doesn't happen automatically, you need to do it in your success function.

function createFolder(folder){
    $.ajax({
        url: "index.php",
        type: "POST",
        data: {'folder':folder},
        success: function(data) {
            console.log("successful post");
            $("#somediv").html(data);
        }
    });
}
like image 136
Barmar Avatar answered Feb 17 '26 03:02

Barmar