Is it okay to use PHP inside a jQuery script? - php

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.

Related

php run before ajax is completed

I know PHP runs first but is there a way to get PHP to wait on an ajax request and then run its script? I have a php script here that I want to run but I NEED a variable from my JS file in order for it to run successfully. So was wondering if it's possible?
What I have is a normal request in my JS:
var myvar = data;
$.get('phpscript.php', {myvar: myvar} );
And in PHP:
$myphp = $_GET['myvar'];
But if i echo $myphp it returns "undefined", if I alert it however It displays the value; which means the php script is running before it even gets the request from ajax. Any way I could make the PHP wait?
Thanks.
Put the PHP that requires a variable in its own script and call it from the ajax call, once the ajax call gets a response update the DOM as needed.
PHP runs on server, then javascript runs on client to make the ajax call, then PHP runs on server returning data, then the javascript gets the data and does something with it.
$.get('phpscript.php', {myvar: myvar}, function(data) {
$('.result').html(data);
});
Inside the php file have something like:
$myphp = $_GET['myvar'];
echo $myphp;
The short answer is, no, you can't make PHP wait. PHP only runs on the server-side, by the time the AJAX request is sent, by definition, the page is already been sent to the client.
You'll probably have to do some refactoring. If the variable absolutely needs to be used for a PHP function, then you may need to move that logic into 'phpscript.php' or (less optimally) you may need to issue another AJAX request when you get the response from the first.
But my guess is that more commonly, you'll probably just have to figure out how to do what you want with javascript. If all you want is something equivalent to a PHP echo, you'll want to use Javascript (or JQuery) DOM manipulation for that.
EDIT: I forgot to mention, the other option is simply to do all the PHP stuff on the server-side before you send the page at all, instead of AJAX you'd want to do something in PHP like including your other php script and calling methods from it. But, everything you do on the server-side, the user is sitting there looking at a blank screen waiting for the page to load. So this isn't an option for anything that's not very quick.

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.

function running automatically instead of a click

I the following code:
<? $test = new com("Soundclass.Soundrec"); ?>
<? $test->startrec ?>
<script>
function stop(){
var stop_record = "<?=$test->stoprec;?>";
}
</script>
and I am running the stop function in a button click. But the php function seems to run without the click.
The purpose of this is to stop the recording on that button click.
You have a little logical error:
PHP is server-side and gets executed on the server when the document is called.
Javascript is client-side and gets called dynamically, it can't re-execute any php-code again.
See the source code in your browser and you'll understand!
But you could make an ajax call to the class and execute the stoprec() method with a (defined in your script) get/post variable. But as this still won't give you a handle on the same instance of the object, so unfortunately you probably have to rethink your whole script!
What you are trying to do is fundamentally impossible: You are mixing up PHP (which runs on server side) and JavaScript (which runs on client side).
You would have to build a second PHP script that stops the recording, and have that called from JavaScript using Ajax.
Calling $test->stoprec will probably stop recording (don't know Soundclass.Soundrec that specifically myself).
As you call it even before the page has been delivered, pressing the stop button later won't make a change here.
You need to execute the PHP later (after button click), however you have the general problem here that the com object in $test won't survive that (it would be a new one).
The only solution I see here is that you create a daemon that manages sound recording for you. This would work with AJAX, but is not trivial. So the short (and sad) answer is: Not easily possible.

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.

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.

Categories