Using a PHP Array in a JQuery script - php

I'm trying to use a php array inside some jquery script. This is what I have:
$("#domainPackage").change(function (){
"use strict";
var packID;
var info;
packID = $("#domainPackage").val();
info = "<?php echo $package[" + packID + "]['pages'] ?>";
$("#domainPageLimit").val(info);
});
But, it is outputting
<?php echo $package[2]['pages'] ?> into my input box as the value.
What is the correct way of using a PHP array in some jquery?
Thank you

This should actually be generating a PHP error which makes me suspect you do not have PHP enabled on this server, or the file extension of the file you are editing is not .php.
Once you have fixed that issue, you will need to load the values from the array into the script at run-time, or use AJAX. You cannot interact directly between PHP and jQuery as the PHP runs on the server side before the page is rendered, whereas the jQuery runs in real-time on the client side in the browser.
To load in runtime you could try the following:
$("#domainPackage").change(function (){
var data = JSON.parse(<?=json_encode($package)?>);
"use strict";
var packID;
var info;
packID = $("#domainPackage").val();
info = data[packID]['pages'];
$("#domainPageLimit").val(info);
});

The problem with your approach:
"The code I'm using is on an separate js file that is called into my php page with <script></script>
is that the script is being processed on the client without ever being seen by PHP, so it cannot process the contents of the <?php ... ?> block. Hence your output of <?php echo $package[2]['pages'] ?>. To make this work you need to output the data into an array/object in the .php file (the json_encode approach suggested by #user1491032 and #coletrain is a good one) and then access that array in your script file i.e.
PHP file:
echo "<script>var package = JSON.parse('" . json_encode($package) . "');</script>";
JS file:
info = package[packID]['pages'];
Update
As was pointed out by #DavidBĂ©langer, you don't need to use JSON.parse if the object is well built, you can just assign the variable directly i.e. in the PHP file:
echo "<script>var package = " . json_encode($package) . ";</script>";
and in the JS
info = package[packID].pages;

Related

How do I ensure a PHP variable is available in index.php after being changed in a second php file (via a jQuery load())?

In my index.php I have the following jQuery code for responding to clicking an image:
<script>
$(document).on('click',".i-give-up", function() {
$("#take-a-guess").load("get_snippet.php");
[...snip...]
generate_HSK2_circle(<?php echo $answer_data["HSK2level"]; ?>);
});
</script>
When I click the image, it loads get_snippet.php which performs and processes a MySQL query. Moreover, if I add
echo "<script>console.log('get_snippet[new] HSK2 level: " . $answer_data["HSK2level"] . "' );</script>";
to the end of get_snippet.php, I can see the correct variable for $answer_data["HSK2level"] in get_snippet.php.
The problem is that the variable $answer_data["HSK2level"] in index.php does not change as a result of loading get_snippet.php.
Question: How do I ensure a PHP variable is available in index.php after being changed in a second php file (via a jQuery load())?
It seems to me that you are actually wanting to store the php value of $answer_data["HSK2level"] in a javascript variable so each time you call generate_HSK2_circle() you pass in the most current value
Note that ajax is asynchronous also so you need to use a complete callback before proceeding with new data
To do that your js would look like:
<script>
// new js variable recieves value on page load from php
var answer_data = <?php echo $answer_data["HSK2level"]; ?>;
$(document).on('click',".i-give-up", function() {
// use complete callback of load to assure new data loaded
$("#take-a-guess").load("get_snippet.php", function(){
// new data has loaded
[...snip...]
// use the js variable in function call
generate_HSK2_circle(answer_data);
});
});
</script>
Then in your new script tag (from load) update that js variable value
echo "<script>answer_data=". $answer_data['HSK2level']. "</script>";
If this new script tag is the only data being sent from server in load() a more appropriate approach would be to send json and use $.getJSON and manually update the js variable from the response object
The index.php file is not going to change after it is already rendered, unless PHP is processed on the server.
In order to pass this data, you may want to look into using a query string and redirecting back to index.php with a get variable.
https://www.php.net/manual/en/reserved.variables.get
Then in your get_snippet.php, you would direct to index.php?answer=... and retrieve it via htmlspecialchars($_GET["answer"])

Access a PHP array element by using a JavaScript variable as index

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.

Passing value to PHP variable inside script

I have some PHP code inside the script so I need
the JavaScript value as a PHP variable, as follows:
<script>
;
var js_var = 123;
var php_var = <?php js_var ?>;
alert(php_var);
;
</script>
Using jQuery to send the value to a PHP page will return the value but not as a PHP variable:
$.get("page.php", {js_var_name: js_var}, function(data) {alert(data)});
I tried also all jQuery AJAX functions: load(), post() and the ajax() method, none of them pass back the value of PHP as above requested.
Is it possible to implement the above with jQuery?
Likely you have a syntax issue with :
var php_var = <?php js_var ?>;
Unless you used define() your php variable should start with $ and you need to echo it so that it gets printed to the page
var php_var = <?php echo $js_var ?>;
If you are assuming that php will read the prior javascript js_var=123 it won't. Javscript is a client side language and php is server side.
You cannot simply mix PHP and JavaScript. The former is executed on the server, the latter on the client, namely in the user's browser. In order to hand a value from PHP to JavaScript you need to output JavaScript code via PHP or do a AJAX-Request to a PHP-Script, as you tried. When using AJAX, it is the easiest solutions to have PHP script that returns a JSON string. When calling this script using $.get() the result will be stored in a JavaScript variable and you can access all the values from there.
Take a moment and a deep breath...and then start thinking about your scopes again.

using for loop value from javascript with php variable

I have this code that executes a for loop in javascript with a php array inside of it. Is there anyway I can use the variable for the loop inside of the php variable for example. This is all inside of php.
echo '<script>
for (var i =0; i<4;i++){
alert("hey"'.$phparr[i].');
}</script>';
I know this will not work because the $phparr is a php variable while the i is a javascript variable is there anyway I can do this?
Try:
<script>
var phparr = <?php echo json_encode($phparr); ?>;
for (i in phparr){
alert("hey" + phparr[i]);
}
</script>
PHP is a server side language which means it executes before it reaches the client (browser).
JavaScript is a client side language which means it is executed in the browser (client side).
The best tool for a new web developer is Google search.
Learn how to search effectively.
You're almost there. In order to access the php array in javascript, you first have to echo out the php array into a javascript array. Try:
$phparr_imploded = implode(',',$phparr);
echo '
<script>
var arr = ['.$phparr_imploded.'];
for (var i =0; i<4;i++){
alert("hey"+arr[i]);
}
</script>
';
If your php array is coming from a database, or contains special characters that javascript may misinterpret, make sure to sanitize before outputting.
Are the objects in your php array strings? If so, you need to surround the objects with escaped quotations BEFORE the implode.
for($i=0; i<count($phparr); $i++){
$phparr[i] = '"'.$phparr[i].'"';
};
How about storing the PHP array in a Javascript variable and looping through as kpotehin suggests?
<script>
var i = 0, name;
var myArr = <?php echo json_encode($my_array); ?>;
while (name = myArr[i++]){
alert("hey " + name);
}
</script>
You should make it this way:
var arr = ["<?php echo implode('","',$array); ?>"];
for (var i =0; i<4;i++){
alert("hey"+ arr[i]);
}
Your basic problem is that you are forgetting that the PHP code and the JavaScript code do not execute at the same time. The PHP runs to completion, outputing HTML and JavaScript. Then the browser runs the JavaScript. If the JavaScript needs dynamic access to data in a PHP variable (including an array), then the PHP needs to generate JavaScript declaring the data in a JavaScript structure. That is what all the other answers are doing.

Include PHP inside JavaScript (.js) files

I have a JavaScript file (extension .js, not .html) containing several JavaScript functions.
I want to call one of the PHP functions in a PHP file containing only several PHP functions from within one of the JavaScript functions.
Is that possible?
Would I need to "include" the .php file containing the PHP function in the .js file?
How would I do that? For example, say I had a file called myLib.php containing a function called myFunc that takes two parameters (param1 and param2). Then I have a .js file containing a function called myJsFunc. How would a call the myFunc (PHP) from within the myJsFunc (JavaScript function)? Wouldn't I need to include the PHP file somehow in the .js file?
7 years later update: This is terrible advice. Please don't do this.
If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.
<script type="text/javascript">
var phpVars = <?php echo json_encode($vars) ?>;
</script>
<script type="text/javascript" src="yourScriptThatUsesPHPVars.js"></script>
If you're trying to call functions, then you can do this like this
<script type="text/javascript" src="YourFunctions.js"></script>
<script type="text/javascript">
// assume each element of $arrayWithVars has already been json_encoded
functionOne(<?php echo implode(', ', $arrayWithVars); ?>);
functionTwo(<?php echo json_encode($moreVars) ?>, <?php echo json_encode($evenMoreVars) ?>);
</script>
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
Add the above code in .htaccess file and run php inside js files
DANGER: This will allow the client to potentially see the contents of your PHP files. Do not use this approach if your PHP contains any sensitive information (which it typically does).
If you MUST use PHP to generate your JavaScript files, then please use pure PHP to generate the entire JS file. You can do this by using a normal .PHP file in exactly the same way you would normally output html, the difference is setting the correct header using PHP's header function, so that the correct mime type is returned to the browser. The mime type for JS is typically "application/javascript"
PHP and JS are not compatible; you may not simply include a PHP function in JS. What you probably want to do is to issue an AJAX Request from JavaScript and send a JSON response using PHP.
A slightly modified version based on Blorgbeard one, for easily referenceable associative php arrays to javascript object literals:
PHP File (*.php)
First define an array with the values to be used into javascript files:
<?php
$phpToJsVars = [
'value1' => 'foo1',
'value2' => 'foo2'
];
?>
Now write the php array values into a javascript object literal:
<script type="text/javascript">
var phpVars = {
<?php
foreach ($phpToJsVars as $key => $value) {
echo ' ' . $key . ': ' . '"' . $value . '",' . "\n";
}
?>
};
</script>
Javascript file (*.js)
Now we can access the javscript object literal from any other .js file with the notation:
phpVars["value1"]
phpVars["value2"]
This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.
I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.
Actually the best way to accomplish this is to write the javascript in a .php and use jquery in a separate file to use the Jquery get script file or jquery load use php include function in the doc where the javascript will live. Essentially this is how it will look.
Dynamic Javascript File in a .php file extension - Contains a mixture of php variables pre processed by the server and the javascript that needs these variables in scripts.
Static Js File - Using http://api.jquery.com/jquery.getscript/ or http://api.jquery.com/load/
In the main html page call the static file as a regular js file. Calling the static js file will force load the dynamic data from the server.
some file.php 1:
<?php
$somevar = "Some Dynamic Data";
?>
$('input').val(<?php echo $somevar?>);
or simply echo the script such as
echo "$('input').val(".$somevar.");";
File 2:somejsfile.js:
$("#result").load( "file.php" );
File 3 myhtml.html:
<script src="somejsfile.js"></script>
I believe this answer the question for many people looking to mix php and javascript. It would be nice to have that data process in the background then have the user have delays waiting for data. You could also bypass the second file and simply use php's include on the main html page, you would just have your javascript exposed on the main page. For performance that is up to you and how you want to handle all of that.
Instead of messing with generic php-handlers do a 1-file exception using a rewrite:
Rename the .js-file to .php and rewrite the request to make it responde to a .js request. If the file is served by apache; add in .htaccess:
RewriteEngine on
RewriteRule myjsfile\.js myjsfile.php [L]
Secondly make the .php-file pretend to be a js-file. Inside the php-file start the file with:
<?php header('Content-Type: application/javascript'); ?>
Et voilĂ , you can now use php-tags in your ".js"-file.
You can't include server side PHP in your client side javascript, you will have to port it over to javascript. If you wish, you can use php.js, which ports all PHP functions over to javascript. You can also create a new php file that returns the results of calling your PHP function, and then call that file using AJAX to get the results.
Because the Javascript executes in the browser, on the client side, and PHP on the server side, what you need is AJAX - in essence, your script makes an HTTP request to a PHP script, passing any required parameters. The script calls your function, and outputs the result, which ultimately gets picked up by the Ajax call. Generally, you don't do this synchronously (waiting for the result) - the 'A' in AJAX stands for asynchronous!
You can make a double resolution of file:
"filename.php.js" in this way.
PHP generates JS in this file.
I got all parameters from DB.
This worked for me on xampp.
There is not any safe way to include php file into js.
One thing you can do as define your php file data as javascript global variable in php file. for example i have three variable which i want to use as js.
abc.php
<?php
$abc = "Abc";
$number = 052;
$mydata = array("val1","val2","val3");
?>
<script type="text/javascript">
var abc = '<?php echo $abc?>';
var number = '<?php echo $number ?>';
var mydata = <?php echo json_encode($mydata); ?>;
</script>
After use it directly in your js file wherever you want to use.
abc.js
function test(){
alert('Print php variable : '+ abc +', '+number);
}
function printArrVar(){
alert('print php array variable : '+ JSON.stringify(mydata));
}
Beside If you have any critical data which you don't want to show publicly then you can encrypt data with js. and also get original value of it's from js so no one can get it's original value. if they show into publicly.
this is the standard way you can call php script data into js file without including js into php code or php script into js.

Categories