I have a function in my Javascript script that needs to talk with the PHP to get the data in my database. But I'm having a small problem because I start the PHP in the for loop in Javascript, and then inside that for loop I get the data in my database. But the pointer in the for loop inside the PHP code is not working.. I guess the problem is in escaping? Or maybe it's not possible at all.
Here's my code:
(function() {
var data = [];
for(var i = 0; i < 25; i++) {
data[i] = {
data1: "<a href='<?= $latest[?>i<?=]->file; ?>'><?= $latest[?>i<?=]->title; ?></a>", // The problems
data2: ....
};
};
});
I think you are confused, you are trying to use a variable of javascript in php.
You cannot do this:
<?= $latest[?>i<?=]->file; ?>'
Which expands to:
<?php
$latest[
?>
i
<?php
]->file;
?>
how can you possibly know the value of i, if i is a variable generated in the client side?, do not mix the ideas, i is defined in the browser and the php code is on the server.
You may want to consider using PHP to output the JavaScript file, that way the PHP variables will be available wherever you want them.
The following links better explain this.
http://www.givegoodweb.com/post/71/javascript-php
http://www.dynamicdrive.com/forums/showthread.php?t=21617
1.Pass the javascript variable to the URL to another php page.
window.open("<yourPhpScript>.php?jsvariable="+yourJSVariable);
2.Then you can use this variable using $_GET in the php script.
$jsVaribleInPhp=$GET['jsvariable'];
//do some operation
$yourPhpResult;
3.Perform any server side operation in the Php and pass this result.
header("Location:<your starting page>?result=".$yourPhpResult);
4.Redirect back to the page you started from thus passing the result of PHP.
Php and Javascript have different roles in web development.
This task can also be performed if there's a php script and js in the same page. But that I leave for the readers to work it out.
Hope this helps!!
Related
The code looks like this:
PHP file
<?php
...
$arrayName = ['ArrayValue_0', ..., 'ArrayValue_n'];
...
php?>
JavaScript
$('.elementClass').each(function(index, id) {
$(id).html('<?php echo $arrayName[index - 1]?>');
});
But you can't just insert a JavaScript variable like that into php tags so index is never received.
I know this can be done via AJAX but is there any other way? Thanks in advance.
Additional info:
I've been told to do this in PHP so there's no posibility of switching the array to a JS file.
You can define arrayName variable in JS and initialize it with the value from the server:
var arrayName = <?php echo json_encode($arrayName); ?>;
$(".elementClass").each(function(index, id) {
$(id).html(arrayName[index-1]);
});
What you're trying to do will not work. For example this:
$(id).html('<?php echo $arrayName[index - 1]?>');
The above will never, ever work, because PHP is run on a server, not on your user's browser.
What you need to do is send the variable somehow to the server. You have a plethora of options:
Use a form and read a $_POST variable
Append it to a URL and read a $_GET variable
Use AJAX and asynchronously send that variable to the server
Return the whole array from PHP to your Javascript code
etc. etc.
Remember, PHP runs on the server, which renders the page, which then in turn is read by your browser where you run Javascript. You can't paste PHP code into the page and expect it to be parsed by PHP!
You need to get back to the server if you wish to get info from it (PhP runs on the server), so either you create a javascript variable on-the-fly when loading the page with the complete content of your PhP array , either you use ajax to get back to the server without refreshing the whole page.
I am trying to send Javascript variables over to a PHP script for updating scores of a quiz game. I've looked up the shorthand method of doing this, which is $.post, but I am unable to retrieve the values in the PHP script. I am fairly unfamiliar which JS and require help as to what I am doing wrong.
Here is the Javascript
function updatescore(){
var thisgamemarks= 2300;
var thequizid = 5;
$.post("updatemark.php", { quizidvalue: thequizid, newmarkvalue: thisgamemarks } );
}
And the PHP
$studentnewmark = $POST['newmarkvalue'];
$thisquizid = $POST['quizidvalue'];
$thisstudentid = $_SESSION['studentid'];
type $_POST instead of $POST. also, on a windows based machine, you can use ctrl + shift + j to debug a js script - which will help if if there's any problems with your code. but, the js code you have shown us looks perfectly fine.
Yes. As suggest use the $_POST instead of $POST and try putting the "quizidvalue" in the javascript inside quotations. It might help. Just a thought. It's how I always do it.
i have javascript as below
html="<th>"+<?php echo __(); ?>+"</th>";
I want to add another javascript variable inside to __() function like this
<?php echo __(<js varible>); ?>
I tried
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
not working for me
can any one help me please
regards
You have a misunderstanding on how server side and client side code work.
The only way that you could possibly achieve what you are trying to do (apply a PHP localization function to a Javascript variable) would be like this (this code assumes you are using JQuery but can be done without it too):
var myvariable = 'hello';
$.get('http://yoursite.com/localize.php?text='+myvariable, function(localizedText) {
html = "<th>"+localizedText+"</th>";
console.log(html);
});
And then localize.php should look like this:
<?php
include('you localization library');
echo __($_GET['text']);
?>
Explanation: while your client side code (Javascript) is been executed in the browser it will call a URL which will execute your server side code (your PHP __(); function) in the server and then return the value to the client side code.
var myvarible=200;
html="<th>"+<?php echo __("'"+myvarible+"'"); ?>+"</th>";
console.log(html);
This would try to put the PHP variable "myvariable" into the script tag, what you want is closer to:
var myvarible=200;
html="<th>"+"<?php echo __("'myvarible'"); ?>"+"</th>";
console.log(html);
However, in this case, why not just skip PHP completely?
var myvarible=200;
html="<th>" + myvarible + "</th>";
console.log(html);
Javascript runs on client side and php on server side.
So var myvarible=200;
will be executed only on client side .
but will be get executed on server side. at that time myvariable will not be valid.
PHP is executed on the server, JS on the client. You cannot expect PHP to parse JS, in fact PHP will never see the JS statements, because they will be processed only once the server has processed the PHP.
var myvariable='<?php echo __("200"); ?>';
html="<th>"+myvariable+"</th>";
console.log(html);
However for this to work the javascript would need to be in a .php file that is being interpreted.
The OP wants to include a JS variable in a PHP call, which is not possible, unless you use AJAX. And you'll agree with me that code like this is only meant to cause big headaches and should be avoided at all costs.
Well yes and no.. i wouldnt do it this way. I use a helper that lets me do things like this in a consistent way. In my view file i have something like:
<?php js_call('jslib.myFunction(?,?)', __($value), 'some other value'); ?>
js_call its similar to using sprintf or a prepared statement except for js. The params are run through json_encode so the quoting and what not are correct. All these are stored in an array and then in the layout, just before my </body> i call:
<?php include_js_calls(); ?>
which then takes all the calls ive made with a js_call and outputs the string values inside a script tag resulting in something like:
<script type="text/javascript">
jslib.myFunction('first value', 'some other value');
</script>
Borrowed this brilliance from Apostrophe Cms
To do localization in javascript (for whatever reason), echo __() can obviously not be called directly.
There are different possible strategies
Include a localization string table in javascript when the page loads. Do lookup against it when needed. This table could be generated on server-side using echo __() then cached.
Make ajax requests for server-localized data. Might not be suitable for frequent updates.
I have the following jquery code:
while (count < 31) {
window['cday_' + count] = <?php echo $day_1 ?>;
window['tday_' + count] = (window['cday_' + count] * formfig) / formfig2;
count++;
}
But I need $day_1 in the php echo statement to reflect the variable "count", so in theory it should be something like "echo $day_count". Is it possible to pass the var to php?
php & jquery coding:
$i=0;
while ($i < $num) {
${"day_$i"}=mysql_result($result,$i,"datavalue");
$i++;
}
?>
<script type="text/javascript">
var chart1;
var count=1;
var formfig=17;
var formfig2=2;
function chartdraw(){
while (count < 31) {
window['cday_' + count] = <?php echo $day_1 ?>;
window['tday_' + count] = (window['cday_' + count] * formfig) / formfig2;
count++;
}
The short answer here is no.
To understand what's possible, you need a deep understanding of what's going on. Your PHP code is building an HTML document (with embedded JavaScript) and sending it on to the web browser. Once the web browser (which is, of course, running on the user's machine, not your server) renders that page, it will execute the javascript. This is when the javascript variables begin to actually mean something. Until then, they are just text getting sent across the network. This point is long after the PHP code has finished running. Your server has already closed down that php instance as it sent the code to the user.
Keeping that in mind, you can send the value of a javascript variable (or any number of other things) back to your server with something called an ajax request. Essentially, this will send some information (the variable's value, and the name of the page you want) back to your server, which will in turn cause your server to build a new web page, which can have PHP code in it. That web page's content will get returned to another bit of javascript you can provide -- called a 'callback' -- which can take the page created by the second php script and make use of it. This is, of course, fairly resource intensive.
Unless you plan to do something that ONLY PHP can do, I would recommend finding a way to do as much of your logic as possible in javascript. This alleviates all these complex problems and keeps all the hard work on the user's machine.
If you can structure your code so your php code provides all the data the javascript code needs before the php finishes running, you can get away without doing anything fancy with ajax. Here's an example:
<script type="text/javascript">
var days = {};
<? for($day = 0; $day < 30; $day++) { ?>
days.<? echo $day ?> = "<? echo get_day_info($day) ?>";
<? } ?>
</script>
What this will do is create a javascript object called days. Then it will fill in days.i for i from 0 to 30. It assumes you have a function called get_day_info($day) which takes a day and returns the info for that day. I'm assuming here that you're dealing with strings -- if not, you will need to remove the quotes, and possibly do other things to wrap the data depending on what format it takes.
I belive the only way is using ajax. http://api.jquery.com/jQuery.ajax/
Not without changing your approach significantly.
The problem is that PHP exists entirely on your server, where javascript exists in the browser. PHP does really know anything about javascript. PHP will completely render your page before any javascript has been run at all. So there is no way to get this value back in easily.
You can use ajax in order to run javascript which can load data or hit URLs on your server, but you cant simply substitute javascript variables in PHP. The reason you can do it with PHP variables is because the PHP actually is generating the javascript.
Have javascript store the value in a hidden field and pick up the value with PHP that way?
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.