Change a php variable for entire document - php

I want to change the effects of a set variable that is at the beginning of a document for example:
if(isset($var)){
// Show Loading Message
}
// Whole bunch of code to load a report
unset($var); // To remove the loading message
I want the deceleration at the end of the code to remove the loading message that is above by removing the variable. Is there any way to do this with PHP?
Thanks!
Note: I understand how the program would usually work, the question is if there is a way around this typical model output being definite, using PHP.

You are not able to remove something that has already been outputted to the browser using PHP - once you output the loading message, from PHP's perspective it is gone and out the door.
You'd have to have some javascript on the page to manipulate the DOM and remove the text node that way.
For example:
print '<div id="loading_message">Loading, please wait</div>';
... bunch of code ...
print '<script type="text/javascript">var e = document.getElementById("loading_message"); e.parentNode.removeChild(e); </script>';

You will have to do it client side; all HTML generated by a PHP script is sent to the browser and can't be retrieved again. To do it client side, give the loading div an ID of, say, #loading. Then, at the end of the PHP script, stick some JavaScript in that will hide the div. Here's a jQuery example:
Loading div:
<div id="loading">Loading...</div>
jQuery (echo this from the bottom of your PHP file):
<script>
$("#loading").hide();
</script>
EDIT
For a vanilla JavaScript solution, please see #Chris's answer
Hope this helps,
James

Well, there are actually ways to process PHP and send to the browser window BEFORE things are done processing.
It's a hokie, hokie, hokie way of doing things but I wanted to at least share.
You can use the flush() command at any point to output the current moment in processing out to the browser while the page is still rendering.
You can also do your processing and store the output of the processing in the output buffer before it goes out.
ob_start();
//Do a bunch of PHP stuff
$results = ob_get_contents();
ob_end_clean();
echo $results
Like I said...HOKIE for general web page processing. Use jQuery or your own JS, but maybe this will some in handy somewhere else.

Related

Is there any way to get an html content/value with php?

Can i get the content or value of the tag with php?
I know i can get it with javascript:
$(function() {
$('class or id').text();
});
But i would like to get it with php, so i can send it back in another query to my sql table.
function changeContentToId(id) {
$("#spanContent").html(id); }
<?php echo "<span onclick='changeContentToId($ob->ID)'>...</span>"; ?>
<span id="spanContent"></span>
This is my code right now, any tips on how to write the top code in php?
thanks. :)
No way : PHP is server-side, and your data is on the client.
Then you have 2 alternatives : getting the information before sending it to the browser (output buffering is a good way), or after, via an AJAX call.
Hope this helps !
Why don't you send it in a 'normal' way ? Like putting the content inside a form then submit it to PHP.
Or get it using Javascript then submit it using AJAX.
PHP won't access client-side information(HTML) once it is in your client(after the content is delivered) you can use client-side manipulation(Javascript) or send it back to server then use it there.
Regards
The simple answer is you cannot do that. PHP is executed on the server before the page is rendered. JavaScript, which updates the content, is executed in the browser after the page is rendered. Hence by the time your content is ready to be read, there is no PHP any more.
The way around it would be to use AJAX to read the info with JavaScript and then send it to another PHP script.
get it with javascript and send it uing ajax to the server.
Just if you really need to, because i don't see any reason since it's generated with php the first time. so you should use the word you want before rendring the html page.

PHP GET variable in same document

how can i pass a variable from javascript to php using same file
in this example page keeps refreshing and i don't get to see the result
it works only if i separate the scripts... but i need it somehow like on ajax..
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
and this is the seccond part of the script ( they are both in same file )
<?php
Id = $_GET[Result];
echo $dbId;
?>
As Brian said you should put it in a conditional statement.. also your PHP is bad. Try the following
<?php if(isset($_GET["Result"])) : ?>
// do work with set variable
<?php $dbID = $_GET["Result"];
echo($dbID); ?>
<?php else : ?>
// "Result" not set
<SCRIPT language="JavaScript">
var carname="Volvo";
location.href="http://localhost/put.php?Result=" + carname;
</SCRIPT>
<? endif; ?>
I think this is a good exercise if you're trying to learn the Ajax method, in the real world I recommend using a framework like jQuery. Of course understanding how this works will help you build better applications in the end.
So you could do something like this in the PHP script:
if (!isset($_GET['Result']))
{
// include the javascript portion with the redirect
}
I'm with the others, though--I'm not seeing the value in a page load followed by an immediate redirect to the same page.
What you are trying to do cannot be done. Your script runs on the client in real time but the php will run on the server during the request. You will need to make an AJAX request.
First you will want to use Firefox with firebug and the web developer toolbar. Firebug gives a great view of ajax traffic and the web developer toolbar helps you see what's going on in the page.
Use jQuery make an ajax request to "send" the value to another php file. Don't be afraid to separate out files, in fact it's encouraged and considered good programming. If you find your sending a lot if information to a php script you will want to use JSON instead of as part of the url.
Man, you should follow a client-server pattern.. So the Client page can use some ajax to make a request to a Server page. This will response to the Client and you can make with the data what you want.
of course it will keep refreshing:)) Because as soon as the browser gets the js code, it will load that page you specify, which will send your browser the same page... you get the idea. It's like writing for(;;){}
Your question is difficult to understand (for me at least.) My guess is that you are wanting to use AJAX to send data to the server and receive a response without leaving the page.
Probably the easiest way to accomplish this is to use a library such as jQuery. (see jQuery.ajax())
PHP only runs on the server and the javascript only runs on the client. By the time your client is running the javascript, no more PHP can be executed on that request.

Is it okay to use PHP inside a jQuery script?

For example:
$(document).ready(function(){
$('.selector').click(function(){
<?php
// php code goes here
?>
});
});
Will this cause issues or slow down the page? Is this bad practice? Is there anything important that I should know related to this?
Thanks!
If you are trying to bound some PHP code with the click event then this is impossible in the way you are trying and PHP code will be executed as soon as page load without waiting for a click event.
If you are trying to generate final javascript or jquery code using PHP then this is okay.
It won't slow down the page; the PHP runs on the server and emits text which is sent to the browser, as on any PHP page. Is it bad practice? I wouldn't say "bad" necessarily, but not great. It makes for messy code - in the event where I need to do something like this, I usually try to break it up, as in:
<script>
var stuff = <?php print $stuff; ?>;
var blah = "<?php print $blah; ?>";
// Do things in JS with stuff and blah here, no more PHP mixed in
</script>
PHP is executed on the server, and then the javascript will be executed on the client. So what you'd be doing here is using php to generate javascript that will become the function body. If that's what you were trying to do then there's nothing wrong with doing it.
If you thought you were going to invoke some PHP code from javascript, then you're on the wrong track. You'd need to put the PHP code in a separate page and use an ajax request to get the result.
Sure, as long as you keep in mind that PHP code will be executed by the server before the page is sent out. Other than that, have fun.
PHP is a "backend" language and javascript is a "frontend" language. In short, as long as the PHP code is loaded through a web server that understands PHP - the downside is that you have to inline the JS, losing caching ability (there are workarounds to parse php in .js files but you shouldn't really do this). To the user it will just look like javascript and HTML. Here's the server order:
User requests page.
Apache (or equivalent) notices this
is a php file. It then renders all
the php that are between php tags.
Apache sends the page to the user.
User's browser sees the JavaScript
and executes it.
Just be sure the PHP is outputting valid JavaScript.
you have a better choice to use ajax that runs the php script when you are handling a click event
$(document).ready(function(){
$('.selector').click(function(){
$.ajax({url:"phpfile.php",type:"POST",
data:"datastring="+value+"&datastring2="othervalue,
,success:function(data){
//get the result from the php file after it's executed on server
}
});
});
});
No it's not. Just as long as you know that the JS is executed after the PHP page is parsed.

How to implement php tags in javascript for url's or anything

I was wondering how i could achieve using <?php?> in javascript for url's? There's a certain route you have to go, Anyone know?
the normal way for example:
$fetchContent = $('#div').load('website/members #content');
What i'm trying to do:
$fetchContent = $('#grav').load('<?php?> #poppu');
Yep, thats wrong as hell lol, but i'm sure someone knows
I would also like to know how to tie php with javascript, but thats probably a whole new topic
You said it right :)
Yep, thats wrong as hell lol, but i'm
sure someone knows
Anyway, from your php script, output the url as a javascript code anywhere in the script before the javascript used for ajax call, e.g.
<?php
echo '<script language="javascript"> var g_ajax_url = "'. $the_url . '";</script>';
?>
and in your javascript, use it this way
$fetchContent = $('#grav').load(g_ajax_url + ' #poppu');
What it simply does is define g_ajax_url as a global variable with the proper php value, and you can use that variable in your js as you use other variables.
To tie php with js directly, try looking into xmlrpc topic.
If javascript is in .php file you can use <?php echo $url ?> and if the file is .js you can't use <?php ?>
It is not clear to me what you are trying to achieve. I assume you are using the jQuery load() function, if yes, you should state so.
You can't load php during javascript execution because the php has already been processes and rendered as HTML and sent back to the client. As PHP is processes on the server it is logical that you cannot run it on the client side.
You could of course send an AJAX request to the server that runs a certain php page and you will be able to use the response as you please.
you can't necessarily "tie" them together because they operate in two different spectrums of processing, php being processed on the server, and javascript being processed in the browser.
You can however render javascript within a php file.
if your javascript is included within a <script> tag within your php page your example should work should actually work. The php would render the urls into the script before it is sent to the browser.
if you are wanting to load external javascript files with php inlcuded urls, you will need to set the proper headers and include the php file just as you would a normal .js file.
good article on this topic HERE
You cannot execute <?php ?> inside JavaScript, but inside PHP you can declare a global variable as:
var x = '<?php echo x;?>';
or, if it's an array, store it as JSON:
var x = <?php json_encode(x); ?>
then access the JavaScript variables inside the external JavaScript.

Can I add a javascript alert inside a PHP function? If yes, how? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to call a JavaScript function from PHP?
Can I add a javascript alert inside a PHP function? If yes, how?
Yes, you can, though I 100% guarantee this isn't what you want or what you mean:
<?php
function do_alert($msg)
{
echo '<script type="text/javascript">alert("' . $msg . '"); </script>';
}
?>
<html><head><title>Hello</title></head>
<body>
<h1>Hello World, THis is my page</h1>
<?php
do_alert("Hello");
?>
</body>
</html>
The browser runs the Javascript, the server runs the PHP.
You could also echo Javascript from your server (without HTML) and then include that script into your page by dynamically creating a <script> tag containing that Javascript. This is essentially creating Javascript on the fly for injection into your page with the right headers etc.
If you want to trace some PHP script execution, then you can use trigger_error() to create a log entry, or you could write a trace() function to store strings in a buffer and add them to a page.
If you want to trace Javascript, See Firebug for Firefox.
PHP Headers API Documentation
On-demand Javascript at Ajax Patterns
Assuming that what you mean is that you want an alert to pop up from the browser when the server reaches a certain point in your php code, the answer is "no".
While the server is running your php code, there's no contact with the browser (until the response starts coming back). There are situations in which a server may be streaming content back to the browser, and in such a case it'd be possible to have some agreed-upon convention for the server to mark the content stream with messages to be alerted out immediately, but I don't think that's what you're asking about here.
Yes, you can.
echo "<script>alert (\"js inside php\")</script>";
To explain; PHP is compiled at the server and the result is plain HTML. Therefore alerts and such cannot appear while compiling is a silent process.
If you want to show an alert in the HTML generated by PHP;
<?php
echo '<script type="text/javascript"> alert(\'Hi\'); </script>
?>
Yes, if you send Javascript code with alert to a html page from PHP.
No, if you want to call alert just by executing server side code and not sending JS to client browser.
echo "<script type='text/javascript'>alert('alert text goes here');</script>";
But i don't know how it can be useful because it will work only on the client side. If you want to debug your code you can simply print it on the screen, but if you use the alert take care of quotes because they can break the javascript part.
You can output a Javascript alert() within a PHP function in at least two ways:
A) Return it:
function sendAlert($text) {
return "<script type='text/javascript'>alert('{$text}');</script>";
}
B: Output it directly:
function echoAlert($text) {
echo "<script type='text/javascript'>alert('{$text}');</script>";
}

Categories