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

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.

Related

javascript to php and viceversa communicate

I am trying to write a plug-in for firefox which would fetch all the domains from the links of the current site and display their IP addresses.
for that I have written js code containing "domians". And simple php script:
<?php
$ip = gethostbyname('www.example.com');
echo $ip;
?>
now i have to pass this "domains" array to php and return the ip values to js code in order to display the domains with ip(s).how can i do this?
I heard that ajax, json can do this. Is there is any other possible solution?
From what I understand, PHP is executed server side. This means that when the user load the plug-in/page/content, the PHP is executed and done with. This being said, JavaScript is executed Client side, meaning it can be executed during the page load, before the page load and after the page load. Unfortunately this means that you cannot pass JavaScript variables to PHP without using AJAX or going to another page.
The way you would pass information from JS to PHP would be by receiving the data you need, then making an Ajax request to a PHP script that would perform some action and then return some value. If that's what you want to do, then there are tutorials/many questions that will help you in doing that.
To pass from PHP to JS, you can do something like:
<script>
var JavascriptVariable = <?php echo $PHPVariable ?>;
</script>
But this might be bad practice, I am unsure.

PHP Array in Javascript Variable - JS Element

I have a Javascript variable which I am setting a PHP variable to.
function cancel(number) {
var message = "<?= $message[" + number + "]; ?>";
}
$message is an array. "number" is the element of the array I want to set message to. Basically, I want to set a Javascript variable to a PHP variable using a Javascript variable as the element picker. So if "number" was 2, it would select:
$message[2];
However, the above approach doesn't work, and I'm not even sure if this is possible.
It isn't. Use XHR to retrieve the value from the server.
It doesn't seem at all possible; PHP is evaluated server-side, and javascript is evaluated client-side. So PHP would see it as $message["+number+"], and try to find the value at the index of "+number+". You'd probably have to do something like an AJAX request to get the data you're looking for.
What you are doing isn't possible; since php is a server-side language, it's executed first, and the js is executed after; there isn't any way to control which is executed first. You must retrieve the variable using AJAX.
Something like this will work:
<script type="text/javascript">
var messages = <?= json_encode($message) ?>;
function cancel(number) {
var message = messages[number];
}
</script>
Of course this will output the entire array in the JavaScript source. If it is large, then you are better off using AJAX.
Tip: if you "view source" it should be painfully obvious why your method doesn't work.
You simply cannot do this using this methodology. PHP is server-side code, meaning that it runs on the server, while JavaScript is client-side code, meaning it runs on the client, or your browser.
Once the PHP runs, it generates an HTML document and sends that document in the response to the browser. Once that's complete, the only way you can get data back to the server is to send it via a form POST, send it via AJAX, or send it via script tag remoting.
Consider looking at some examples on the Internet of how to POST data back to the server via a form and via AJAX. It's clear you're struggling with some concepts regarding how to properly architect your program, and looking at some examples would be a great way for you to learn and master these techniques.
PHP Submit Form Example
PHP Tutorial
You need to use AJAX call to resolve your issue.

How to get JavaScript variable value in PHP

I want the value of JavaScript variable which i could access using PHP.
I am using the code below but it doesn't return value of that variable in PHP.
// set global variable in javascript
profile_viewer_uid = 1;
// php code
$profile_viewer_uid=$_POST['profile_viewer_uid'];
this gives me the following error :-
A PHP Error was encountered
Severity: Notice
Message: Undefined index: profile_viewer_uid
Another php code i used which give empty value
$profile_viewer_uid = "<script language=javascript>document.write(profile_viewer_uid);</script>
When I echo it shows nothing.
Add a cookie with the javascript variable you want to access.
document.cookie="profile_viewer_uid=1";
Then acces it in php via
$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];
You will need to use JS to send the URL back with a variable in it such as:
http://www.site.com/index.php?uid=1
by using something like this in JS:
window.location.href=ā€¯index.php?uid=1";
Then in the PHP code use $_GET:
$somevar = $_GET["uid"]; //puts the uid varialbe into $somevar
Here is the Working example: Get javascript variable value on the same page.
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
You might want to start by learning what Javascript and php are. Javascript is a client side script language running in the browser of the machine of the client connected to the webserver on which php runs. These languages can not communicate directly.
Depending on your goal you'll need to issue an AJAX get or post request to the server and return a json/xml/html/whatever response you need and inject the result back in the DOM structure of the site. I suggest Jquery, BackboneJS or any other JS framework for this. See the Jquery documentation for examples.
If you have to pass php data to JS on the same site you can echo the data as JS and turn your php data using json_encode() into JS.
<script type="text/javascript>
var foo = <?php echo json_encode($somePhpVar); ?>
</script>
If you want to use a js variable in a php script you MUST pass it within a HTTP request.
There are basically two ways:
Submitting or reloading the page (as per Chris answer).
Using AJAX, which is made exactly for communicating between a web page (js) and the server(php) without reloading/changing the page.
A basic example can be:
var profile_viewer_uid = 1;
$.ajax({
url: "serverScript.php",
method: "POST",
data: { "profile_viewer_uid": profile_viewer_uid }
})
And in the serverScript.php file, you can do:
$profile_viewer_uid = $_POST['profile_viewer_uid'];
echo($profile_viewer_uid);
// prints 1
Note: in this example I used jQuery AJAX, which is quicker to implement. You can do it in pure js as well.
PHP runs on the server. It outputs some text. Then it stops running.
The text is sent to the client (a browser). The browser then interprets the text as HTML and JavaScript.
If you want to get data from JavaScript to PHP then you need to make a new HTTP request and run a new (or the same) PHP script.
You can make an HTTP request from JavaScript by using a form or Ajax.
These are two different languages, that run at different time - you cannot interact with them like that.
PHP is executed on the server while the page loads. Once loaded, the JavaScript will execute on the clients machine in the browser.
In your html form make a hidden field
<input type="hidden" id="scanCode" name="SCANCODE"></input>
Then in your javascript update the field value by adding;
document.getElementById("scanCode").setAttribute('value', scanCode);
This could be a little tricky thing but the secure way is to set a javascript cookie, then picking it up by php cookie variable.Then Assign this php variable to an php session that will hold the data more securely than cookie.Then delete the cookie using javascript and redirect the page to itself.
Given that you have added an php command to catch the variable, you will get it.
You need to add this value to the form data that is submitted to the server. You can use
<input type="hidden" value="1" name="profile_viewer_uid" id="profile_viewer_uid">
inside your form tag.

jQuery / PHP mix up

I have the following jQuery function in my PHP:
echo '
function myFunction() {
return $.ajax({
type: "POST",
url: "mypage.php",
data: "name=John&location=Boston"
});
}
$.when(myFunction()).then(function(data) {
// handle data return
someOtherFunction(data);
// need to set "data" var into PHP SESSION
}, function(error) {
// handle ajax error.
});
';
After my AJAX does the majic it returns a value (data), which I pass into another function. In addition I need to be able to set that value into a PHP session:
$_SESSION['project'][data] = data;
How do I do that? The switching between PHP and JS confuses me for some reason...
That's impossible since the JS is now on the client side. You can't set PHP variables directly.
What you could do is set a cookie in JS using document.cookie, and then on the next page request PHP can get at it via $_COOKIE.
You could also just set the $_SESSION variable inside mypage.php - that may be significantly easier, if they both share the same session.
It's confusing because you're mixing the two, try to keep a distinct separation in your code. Instead of echoing your jQuery script, just close the php tag, that would also make syntax highlighting work.
As for setting session variables, you need to do it on the server side in your mypage.php, before writing the data to the output. That will happen before passing the data to the client side jQuery script for processing.
First of all you must be aware the javascript is a clientside language and PHP is serverside. Everything PHP does, it does when the page loaded and it stops after the page is loaded. Javascript takes over then.
What you could do is create mypage in a way that it also creates $_SESSION['project']['data'] as an associative array that you can use with PHP. What you're not trying to do is setting a javascript array into a PHP variable. Not that this is wrong by default, but since you're trying to SET the data using PHP my guess is you will also GET the data using PHP, thus a javascript array in that session would be useless.
So in mypage.php you've probably have something like:
echo json_encode($result);
Where $result is the array of data returned by the script. You could simply add one line above saying:
$_SESSION['project']['data'] = $result;
and have the data stored in the session to use on other pages.

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