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?
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);
}
});
}
Ok you're trying to get the value from a php server using Ajax with JavaScript, then I'm guessing you want to alert to the page when received
The problem is that
if(isset($_POST["folder"]))
Only is true in the actual Ajax request itself, which only fetches the data as a string from the server, but doesn't actually execute it
If you want the code to be executed on the page, you have to do that on the Ajax on success call on the client side, so
<script>
function createFolder(folder){
$.ajax({
url: "index.php",
type: "POST",
data: {'folder':folder},
success: function(data) {
document.body.innerHTML+=data
// Or maybe data.responseTezt or something idk
// Look up in the API how to get the text content
console.log("successful post");
}
});
}
</script>
Then on the server side only echo the JavaScript if "folder" is not set,
Also in the client side in order to actually execute you JavaScript you may have to make a new Dom parser
so the whole php file is basically
<?php
if(isset($_POST["folder"])) {
//All of your other code
} else {
?>
<!--all of your HTML code-->
<script>
function createFolder(folder){
$.ajax({
url: "index.php",
type: "POST",
data: {'folder':folder},
success: function(data) {
// Or maybe data.responseTezt or something idk
// Look up in the API how to get the text content
var dp= new DOMParser()
var doc=dp.parseFromString(data,"text/html")
Array.from(doc.children).forEach(t=>
document.body.appendChild(t)
)
console.log("successful post");
}
});
}
</script>
<?php } ?>
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.