Reputation: 59
I use a custom alert javascript. I want to call this javascript inside a php. I got a basic alert to work but I cannot get the custom one to work.
This code works. It opens an alert window if my file path is empty
<?php
$albums_json_file1 = site_path . DIRECTORY_SEPARATOR . 'users' . DIRECTORY_SEPARATOR . $username . DIRECTORY_SEPARATOR . 'main.json';
if (!empty($albums_json_file1))
echo "<script type='text/javascript'>alert('message')</script>"
?>
This code does not work
<?php
$albums_json_file1 = site_path . DIRECTORY_SEPARATOR . 'users' . DIRECTORY_SEPARATOR . $username . DIRECTORY_SEPARATOR . 'main.json';
if (!empty($albums_json_file1))
echo "<script> swal('REGISTRATION SUCCESS!', 'You are now being redirected to the payment screen!', 'success'); </script>"
?>
In my webpage I have the script source for the custom alert and if I just add this code in my webpage the popup alert works BUT I need it to check the site path and return the alert only if it is empty.
Here is the regular script. If I put this in the body of my webpage the alert pops up.
<script>
swal("REGISTRATION SUCCESS!", "You are now being redirected to the payment screen!", "success");
</script>
Upvotes: 1
Views: 407
Reputation:
In your first example, you will always get an alert because the way you wrote it, the string will never be empty. You ought to check if it creates a valid file path instead of checking if the string is empty (which it never will be). Use file_exists()
instead of empty()
.
I'm willing to bet the problem is that your filepath that you are generating is not correct.
EDIT - I'm not allowed to comment, but in response to the other answer - putting JS in the header is bad practice. It will slow down page load. If this indeed the issue, you ought to put an onload call in the footer and put all your javascript inside of it.
window.onload = function(){
// Put codes here
};
So that the page content is loaded before doing any scripting.
That said, this isn't the issue you're having since you say that putting your swal()
call in the body manually works.
Upvotes: 2
Reputation: 7694
Your html is loading top to bottom.
Move the declaration of swal()
to the header so it can be used anywhere in the body.
So your PHP echo is probably before you declare swal()
example:
<script>swal('Does not work');</script>
<script>
var swal = function(txt){
alert(txt);
}
</script>
<script>swal('Works');</script>
The reason alert();
works is because that works in your entire Document.
Upvotes: 3