how to put javascript variable in php inside the javascript code - php

I have a javascript code that I wanna put a php on it.Then in middle of php code , put a javascript variable.
like this :
<script>
function getuserid(id,shop){
...
var htmlString="<?php $_SESSION['SELECTED_CID']= {I want to put 'id' variable here}?>";
}
</script>

PHP code was compiled and run once when you done loading your page. But javascript function can be used many time! So, some function like this does not exist.
You can use Ajax to accomplish what you want, whenever you wanna retrieve UserID, you can call an ajax, then ajax do a request to server and return you what you need!
Have a try :)

Related

jQuery AJAX vs PHP in HTML attribute

If I want to do some PHP on an event(e.g. onchange) should I use jQuery ajax like:
$("#elm").on("change", function(){
//ajax code
}
, should I use the PHP in the HTML attribute like:
<element onchange="<?php //stuff to do ?>"></element>
You seem to be conflating two different issues.
JS bound events vs intrinsic event attributes.
Bind your event handlers with JS.
Follow the principles of Progressive Enhancement and Unobtrusive JavaScript.
Ajax vs Putting PHP in a JS function
If you put PHP in a JS function then it will run when the PHP outputs the JS function to the browser, not when the JS function is called.
If you want to run PHP in response to an event, then you have to make an HTTP request to the server to run the PHP.
If you want to insert content from the load of page and leave it static, you should use only PHP.
If you want to insert content dynamically (changing with users interactions) you should use AJAX.
I can't found out what are you trying to achieve with your example, so not very sure what you should do there.
taking your code it would give this :
$("#elm").on("change", function(){
//ajax code
$.get('url', {data:'tosend'}, function(data){
// here you have the response of the php script in the data object
// it can be json for exemple
});
}
You must realise two things, your php code will be render when the page is loaded in the
browser so the second code you gave us
means that your "onchange" event is already present in your page.
If you want to request something (data, html, etc) to server from a loaded page, then do an ajax.
In that case below code is correct.
$("#elm").on("change", function(){
//ajax code
}
You cannot execute a piece of php code from client side. But you can assign values from php to javascript and then do operations on client side.

Calling a PHP function through an HTML Link (no form)

I have a PHP Function that I would like to integrate into my (existing) web page. Further, I would like it to execute when the user clicks a link on the page. The function needs to accept the text of the link as an input argument.
Everything I've researched for sending data to a PHP script seems to involve using forms to obtain user input. The page needs to accept no user input, just send the link-text to the function and execute that function.
So I guess the question is two-part. First, how to execute a PHP script on link click. And second, how to pass page information to this function without the use of forms. I am open to the use of other technologies such as AJAX or JavaScript if necessary.
EDIT:: Specifically what I am trying to do. I have an HTML output representing documentation of some source code. On this output is a series of links (referring to code constructs in the source code) that, upon being clicked, will call some python function installed on the web server (which leads me to think it needs called via PHP). The python function, however, needs the name present on the link as an input argument.
Is there some sort of interaction I could achieve by having JavaScript gather the input and call the PHP function?
Sorry for the vagueness, I am INCREDIBLY new to web development. If anything is unclear let me know.
You'll need to have a JS function which is triggered by an onclick event which then sends an AJAX request and returns false (so it won't be redirected to a new page in the browser). You can do the following in jQuery:
jQuery:
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function doSomething() {
$.get("myfile.php");
return false;
}
</script>
And in your page body:
Click Me!
In myfile.php:
You can add whatever function you want to execute when the visitor clicks the link. Example:
<?php
echo "Hey, this is some text!";
?>
That's a basic example. I hope this helps.
You will need to use AJAX to accomplish this without leaving the page. Here is an example using jQuery and AJAX (this assumes you have already included the jQuery library):
First File:
<script language="javascript">
$(function(){
$('#mylink').click(function(){
$.get('/ajax/someurl', {linkText: $(this).text()}, function(resp){
// handle response here
}, 'json');
});
});
</script>
This text will be passed along
PHP File:
$text = $_REQUEST['linkText'];
// do something with $text here
If you are familiar with jQuery, you could do the following, if you don't want the site to redirect but execute your function:
in your html head:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
the link:
Execute function
in ajax.php you put in your function to be executed.
Maybe something like this:
....
<script>
function sendText(e)
{
$.ajax({
url: '/your/url/',
data: {text: $(e).html()},
type: 'POST'
});
}
</script>
You can use query strings for this. For example if you link to this page:
example.php?text=hello
(Instead of putting a direct link, you can also send a ajax GET request to that URL)
Inside example.php, you can get the value 'hello' like this:
<?php
$text = $_GET['hello'];
Then call your function:
myfunction($text);
Please make sure you sanitize and validate the value before passing it to the function. Depending on what you're doing inside that function, the outcome could be fatal!
This links might help:
http://net.tutsplus.com/tutorials/php/sanitize-and-validate-data-with-php-filters/
http://phpmaster.com/input-validation-using-filter-functions/
Here's an overly simplistic example of what you're trying to do..
Your link:
Some Action
Your PHP file:
<?php
if (isset($_GET['action']))
{
// make sure to validate your input here!
some_function($_GET['action']);
}
PHP is a server side language i.e. it doesn't run in the web browser.
If you want a function in the browser to operate on clicking a link you are probably talking about doing some Javascript.
You can use the Javascript to find the text value contained in the link node and send that to the server, then have your PHP script process it.

Javascript variable not working in a different file

I have this script in index.php file:
<script type="text/javascript">
$(document).ready(function(){
$('#ads').load('output.php').fadeIn('slow');
});
</script>
And the output.php file contains a hidden input by which I pass a php variable and retrieve it succesfully:
<script type="text/javascript">
num = document.getElementById('number').value;
</script>
And if I put, say, an alert(num); in the output.php file, everything works. Though when I do the same in the index.php file, javascript doesn't seem to see that num variable.
Im just going to ges that you dont actually wait until the file is actually loaded before testing to access that variable
http://api.jquery.com/load/
the load method takes a completed callback that u can use like this
$(document).ready(function(){
$('#ads').load('output.php', function() {
alert(num);
}).fadeIn('slow');
});
but you should probably not solve your problem this way i sugest you call a function from your
loaded file instead of setting a variable
You can't access variables before you create them. In the code you provided the first time num is being assigned to is when the output.php file is loaded and parsed. Since jQuery's load function isn't blocking - that is, your browser will continue executing JS while the load function is doing its magic - you have no good way to know when num will be assigned to. It could be milliseconds, or it could be never if your webserver refuses to return the output of output.php for whatever reason.
In jQuery programming, using a callback function is common practice, although you can make it cleaner by passing it a function reference instead of an inline function:
$(document).ready(function(){
$('#ads').load('output.php', outputLoadCallback).fadeIn('slow');
});
function outputLoadCallback(response, status) {
console.log(num);
}
Maybe an even better way would be to include the logic you need to run in the callback function like so:
var num; // Make sure num is in the global scope
function outputLoadCallback(response, status) {
num = document.getElementById('number').value;
console.log(num);
}
If you're "not much of a pro", may I suggest jQuery in Action?

Php - run another page and go

i've a question, in a php script I've to do some things, and I need to be really fust, but in the script I've to do some database controlls, too, so, I would know if it's possible run an external php page, that do something, but without wait for its results.
Thanks
(P.S.: sorry for my english)
You'll want to look at using Javascript and Ajax. This allows you to run a php script from within a page asynchronously.
If you use a javascript library, such as jQuery then you can use something similar to this:
$.get('my_script.php', function(response) {
// This code is ran when the page has been loaded
// `response` is the content you get back from script
});
For more information have a look at the jQuery documentation on the $.get function.
You can use Ajax to do that, it let another script run in background.
Yes, you can use Ajax for this. Using Ajax you can run php code in the background, however if user navigates to another page, the execution of that php code will be terminated. The simplest way to get started with Ajax is to use a library like jQuery. See http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
Hope this helps
--EDIT--
This how you can achieve calling exec(php script.php) using Ajax and PHP
home.php (here you are using Ajax to run exec.php)
<!--include the jQuery library -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.js"></script>
<script type="text/javascript">
function runInBackground(){
$.get('exec.php', function(data) {
});
}
</script>
exec.php
<?php
exec(php script.php);
?>

issue calling JavaScript function from PHP

basically I am trying to call a javascript function from my PHP and I am using code I know works in other situations however here is it not and I am at a loss as to why?
It may be something stupid as I have been staring at this screen for a long time :)
here is where I call the function:
if(isset($test_details['done_test'])){
echo "getting here";
echo "<SCRIPT LANGUAGE='javascript'>user_error();</SCRIPT>";
}
I successfully get 'getting here' printed however it does not call the JS function.
javascript function:
function user_error(){
document.write("working");
//alert("User has already taken this test. Your are being redirected...");
//setTimeout("window.location='home_student.php'",3000);
}
The commented it what I do eventually want it to do.
Could anyone please shed some light.
Many thanks,
#Crimson - Here is what I tried after your advice...still no luck.
javascript now:
$(document).ready(function () {
var done = "<?= $test_details['done_test'] ?>";
if(typeof done != 'undefined'){
$('WORKING').appendTo('#bodyArea'); // just to test
}
});
By echoing <script>...</script> with PHP, you are not going to get the browser run the JS function!
PHP only outputs the HTML file that you want to send to the browser. The browser then parses this HTML and does a multitude of things before the page is displayed to the user.
Next, the user interacts with the displayed page (or some other browser related event like 'onload' happens) and the attached JS gets called.
So, if there is some JS that you want to run at a certain time, say immediately after the browser has finished loading the page, you need to create JS in the HTML file such that there is a JS function which gets called at the page load event like this:
<body onload="/*do something here*/"> ... </body>
It is better to use JQuery or some other JS frmework to accomplish something like this though.
Are you sure the function is already defined? Perhaps you declared your function after making the function call.
Additionally, although it's not really going to matter here, the proper way to have a javascript script tag is.
<script type="text/javascript"></script>
i.e. not language="javascript"
Replace the line you call the JS function with this:
echo '<script type="text/javascript">window.onload = user_error </script>' ;
It should solve the problem. Because at the time you are calling user_error(), the function may not have been initialized by the browser. So you'll get an error since the function could not be found.
If the function is placed in an external .js file, it's very likely that you get this error, since the external file usually takes a while to be loaded. If the function deceleration is in the same file but after where you are calling it, same thing happens.

Categories