jQuery / PHP mix up - php

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.

Related

Sending php variables to Javascript variables

Is there any way to do it without doing this:
send javaScript variable to php variable
OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?
I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by #MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.
On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:
$variable = $_REQUEST['javascriptVariable'];
A nice and easy way to do this is like this:
PHP
<div id="something" data-info="<?php echo $info ?>"></div>
Jquery
var info = $("#something").data("info");
EXPLANATION
Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.
There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).
The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.
To do this during page generation can be done similarly as follows:
echo "jsvar = eval('('+".json_encode($phpvar)."+')')";
Note that the eval occurs on client side within browser and is common in every major js library.
Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.
I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:
PHP side:
<?php echo json_encode($responce_object); // DONE ?>
javascript side:
on_responce(responce)
{
var res_obj = eval('('+responce+')');
fire_event(res_obj);
}
The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.
You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:
<head>
<script>
function loadDiv(url)
{
$('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes. In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";
//note this only works for sites on the same domain. You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>
<?php
//I tested this code before posting, then replaced the domain and page name for security's sake
If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this
var javascriptVariable = "John";
$.ajax({
url: '/myphpfile.php',
type: "GET",
dataType: "json",
data: {
name: javascriptVariable,
},
success: function( data ) {
// do success function here
},
error:function( xhr, ajaxOptions, thrownError ) {
// handle errors here
}
}, "json");

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 variable value from javascript to php

I am working on a project where I used ajax for asynchronous DB access.
I store the value in JavaScript variable as follows..
var content=xmlhttp.responseText;
now what I wanted is to pass this value to the php module on same page..
Please suggest me..its urgent
You'll have to make a separate AJAX request to another script to achieve this. PHP is server-sided and therefore cannot directly interact with the client.
You should handle the data (which you are assigning to content) in PHP because, as the other answers here tell you, PHP is server-side and JavaScript is on the client. If you are getting this data from a page you control, instead of var content = xhr.responseText; just modify the data BEFORE you send it. For example, if you are making an AJAX call to a process.php file on your server to get the data you are otherwise assigning to content in JavaScript, be sure to handle the data in process.php PRIOR to echo()'ing the data (which you are then storing inside content on the client):
In process.php:
// below is the normal server script which you are storing in content on the client
// echo $result;
// instead, we are going to operate on the data first:
return doSomething($result);
Then on the client:
var newContent = xhr.responseText;
And the newContent variable will contain the data you previously wished to modify with PHP. If you DO NOT have control of the server script which you are calling with AJAX, then as mentioned here already, you will need to send a SECOND AJAX call to the server with your PHP, and use $_GET or $_POST to retrieve that content data and then play with it there.
Am unclear about your need to pass value from javascript to php.
But I can give you,
A non-recommended but working approach towards your problem:
You said, you are making an Ajax call at first. While processing the corresponding server side php function, Store the response value (value of xmlhttp.responseText) into a $_SESSION variable. Finally Reload the page (using location.reload()) inside the ajax response handler function.
And a recommended approach towards your problem:
You might have added some if-else control-flow structures in the php code and expecting to execute them after getting the ajax response value (sadly you cannot do that). So if you do have some logic like that, then convert those if-else conditions to corresponding Javascript code. May be a javascript function and call that function by passing the ajax response value to it. This new function will use your ajax response value and make changes in some parts of your webpage by applying necessary logic.

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.

call a php function from jquery

I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:
JQUERY:
$.ajax({
type: "POST",
url: post_url,
success: function(group) //we're calling the response json array 'tree'
{
//WANT TO CALL THE PHP FUNCTION HERE
} //end success
}); //end AJAX
PHP:
<?php
foreach($groups as $group){
echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
In your php script that builds your response, just add an extra property to your object that is the html string you want to put into your page and then have javascript put it where it needs to go. You have no choice but to run php functions on the server.
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server. This is because javascript executes client side and PHP executes server side. Therefore, javascript does not have direct access to PHP functions.
You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.
Can you replicate the functionality of the PHP function with a JavaScript function?
Would this, or something similar, work for you:
$.ajax({
type: "POST",
url: post_url,
success: function(groups) //we're calling the response json array 'tree'
{
for(group in groups){
document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
}
}
}); //end AJAX
Alternatives:
Change the PHP that backs the original AJAX call so that, instead of sending back JSON, it sends back HTML exactly as you want it.
Chain a second AJAX call "inside" the success of the first, so that a second round-trip to the server is done for the JSON->HTML conversion.
Accept that sometimes you need to "duplicate" presentation-rules when you are working with multiple languages, and use something like EJS to do the same <option> stuff that PHP does elsewhere.
You have to be aware that you're dealing with two paradigms here, the first one is server-side logic (PHP) and the second one is client-side logic (JavaScript).
Unfortunately there is no way to call PHP from JS from the client without performing an AJAX call and rendering the content you want to show. However, you could prepare the result and set the body of the AJAX response with your requested HTML string.
If this is not possible, I suggest to look at the diverse number of JS frameworks that will provide helpers to generate options for select fields.

Categories