Reputation: 3211
I've got a form checking whether a file exists on the server and if yes it serves it to the user. This all is done via PHP. However, if the file is not found I would like to use jquery for some client side. That's why if the file does not exists then I call echo and the jquery script. The problem is that the jquery does not get executed?
if (isset($_POST['download']))
{
if (file exists)
{
//serve it to the user
}
else
{
//these lines do not get executed. The page simply reloads after post method
echo"<script>
$('#collapseOne').show();
var content = $('#s').val();
$('#p').val(content);
</script>";
}
?>
Upvotes: 0
Views: 681
Reputation: 241
Do you do a full page reload or an javascript ajax request for getting the php script? In case of the full reload you already parse the html file with php before delivering so you don't need to use javascript for manipulating but just php to display or hide elements in the html page.
If it is an ajax request (so not including the answer of your form request) you could use the callback function to check for success or failure and execute the javascript after your ajax request (like Charlotte Dunois wrote). In this case you just receive the page with javascript but this javascript will not affect the already loaded page but only the new requested page from ajax request. That's why you don't get any effect.
In order to have affect from the javascript by ajax response you need to append it into the dom of the already loaded page.
In general I would try to separate javascript from php to keep it all clean so don't echo javascript code directly from php for including in the page but just inform the browser for success or failure (by ajax) or to place a tag on the page (for example a ) which can be found by javascript ($('#scriptSuccess').length > 0) to trigger your javascript script.
Upvotes: 0
Reputation: 4680
You have to do the javascript in the success callback of the ajax call.
success: function(resp) {
if(resp == 'false') {
$('#collapseOne').show();
var content = $('#s').val();
$('#p').val(content);
}
}
And in the else statement in php now you just have to return false.
if(file_exists(...)) {
//code
} else {
echo 'false';
}
This of course only applies if you're making an ajax call if not you have to deliver us more information how you're actually doing it.
Upvotes: 0
Reputation: 9583
Put your script inside $(function(){});
$(function(){
$('#collapseOne').show();
var content = $('#s').val();
$('#p').val(content);
});
The script is executing before the dom is ready
Upvotes: 1