Reuse data from jquery to php [duplicate] - php

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 years ago.
Hi again are there a way that i can get the variable "log" in a jquery code like the example bellow with out using alert, a field id, class and etc.
<script>
var log='1';
</script>
<?php
$run = log
?>
I want to get the data of a certain variable in a javascript and use it as a value of a variable in my php code

You can't do it that way.
Because:
javascript runs in browser.
PHP runs at server.
There are two ways one is form submission and other one is ajax. You have to send the values to the server to get it to echo.
As per your updates, i would suggest you to use ajax/form submit:
Ajax:
var log = '1';
$.ajax({
url: 'path/to/php/file.php',
type:'get',
data:{log:log},
success:function(data){
console.log(data); // logs: The posted value is 1
}
});
here in the data object log before : is the key while log after : is the var which refers to value '1'. So, in php you can do this:
<?php
if(isset($_POST['log'])){
$run = $_POST['log'];
echo 'The posted value is '.$run;
}
?>

You cannot get client side variable on server side without the use of AJAX or some sort of post back. In all calls to a server, the server side code is execute then returned to render client side in the browser. Therefor, the client side code is ALWAYS run after the server side.
You can look at using client side code to make an AJAX request to the server and return a value or post to to a page which will load and render it server side.
You are trying to echo a value here, this can be done client side but if there is complex server side logic to get the value then I would use an AJAX request to get it.
AJAX
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
POST a form
http://php.net/manual/en/tutorial.forms.php

Related

How to pass a variable from jQuery to PHP? [duplicate]

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 8 years ago.
I have a jQuery function, which, on click, itercepts a clicked link:
$("a").click(function(e) {
e.preventDefault();
var link = $(this).prop('href');
alert(link);
});
and it works properly, but how to pass that link to a PHP variable to 'echo' it later?
I unsuccessfully tried:
$("a").click(function(event) {
event.preventDefault();
var link = $(this).prop('href');
<?php $link = .'link'. ?>
});
I know it may be a silly question, I looked all over the web but I didn't find any proper answer.
The only way to do this is to have a script wich stores values passed to it in a session or to a DB and either output the session data later or read from the db
$("a").click(function(event) {
event.preventDefault();
var link = $(this).prop('href');
$.post('saveLink.php', {href : link});
});
the saveLink.php would be something like this
<?php
// Clean your POST variable, always clean any POST variables
// see here for a good discussion on that
// http://stackoverflow.com/questions/4223980/the-ultimate-clean-secure-function
$link = htmlspecialchars($_POST['href']);
$_SESSION['links'] = $link;
?>
then later on you can retrieve all you session data
Note
Session data is not permanent and not shareable between users so if you need to do that you would be better off with a db query also if you need to access a particular link then you will need to send some sort of id with it.
PHP is preprocessor running on a server side. jQuery is running on client side (in user's browser) and it can't comunicate with PHP like this.
Although you can send the data to PHP with Ajax request and process them in another php script, for example store them in a database.
$.ajax({
url: '/ajax_catch.php',
type:'POST',
data: {
link: link
},
success: function(m){
//what to do after its done
}
});

passing variable from javascript to php [duplicate]

This question already has answers here:
How can I pass variables from JavaScript to PHP?
(2 answers)
Closed 9 years ago.
I want to pass a variable from a function in JavaScript to PHP that is also inside the JavaScript function.
For Example:
myfunction('qwerty');
<script>
myfunctionjs(x)
{
<?php echo $x?>
}
</script>
note: code above is just a sample
Your code sample, while it expresses what you want quite clearly, should also show how impossible it is.
PHP is a server-side language whereas javascript is a client-side language. The only way for javascript to "talk" to PHP is to submit a request to the server. You can do this either through a standard HTTP-GET request or a POST request (through a form submission, or more commonly via Ajax).
The PHP isn't inside the JavaScript function. The PHP code is executed on the server.
When the Javascript is executed, the code looks like this:
myfunction('qwerty');
<script>
myfunctionjs(x)
{
alert(x); //or whatever $x is
}
</script>
If you want to pass 'x' to a PHP script, you'll have to make an AJAX request.
You can't have javascript telling PHP to do something inline. JavaScript runs client side, while PHP runs server side.
Instead, you need to have your javascript send the data to your server, and you'll have PHP do something when receiving that second request.
If you are using jQuery, have a look at the ajax method for example on how to send data: http://api.jquery.com/jQuery.ajax/
Passing variable from javascript to php right away is not possible. You will have to use AJAX for this. You have to understand the difference between server-side scripting and client-side scripting.
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-difference-between-server-side-and-client-side-programming
Read the above link and it will give you a full understanding of the process. if you have any issues let me know.
Read more

JSON return undefined from JQuery request [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return AJAX response Text?
I'm trying to put together a JQuery timeout function for a form submit action. I have something similar in place via PHP for a page reload, and have the time of the initial page load stored in $_SESSION['pageLoad']. What I'm now trying to do is grab that value and use it in some JQuery math.
After searching around SO, I have arrived at the following:
PHP
<?php
//filename: getsession.php
session_start();
echo json_encode($_SESSION['pageLoad']);
JQuery
$("#sms-creator").submit(function() {
var session;
$.ajaxSetup({cache: false})
$.get('sms_includes/getsession.php', function(data) {
session = data;
});
//at this point I just want to see what I'm getting, hence the next 2 lines...
alert(session);
return false;
});
The path to the PHP file is relative to the form page, not the .js file.
My alert only returns 'undefined'. I'm inexperienced with Javascript and its libraries, so the fault is not apparent to me. Any help appreciated.
ajax call is done asynchronously. so when $.get is executed, request is sent to server for response, however, the javascript program will not wait for the response because it is done asynchronously. when you alert(session), variable session hasn't been set to data returned by server. Try do ajax synchronously, or put alert session in the ajax callback.

move var from javascript/jquery to php script on same page [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to pass JavaScript variables to PHP?
how would I go about moving a javascript variable over to a php script without a form submission?
is it even possible?
ajax is an acceptable option but how
lets say I want to run thisnewoption.php in process sending it javascript variable imgfilename which contains a string
Once your php page has loaded, there's no going back. The best way to go about passing variables ( data ) back to the server is with ajax, so it might be time to brush up on ajax http://api.jquery.com/jQuery.ajax/
Update: Tell you what, here is what a really basic ajax call looks like, notice that is send data to the server here with POST:
$.ajax ( {type : 'POST' ,
url : 'email.php' ,
data : { variable: variable, anotherVariable: anotherVariable } ,
success : function ( data ) { $('#some-div').html ( data ) ; }
} ) ;
You cannot literally pass a javascipt variable as a PHP one as PHP is evaluated on server side where as javascript on client. You can use ajax call to pass it however.

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.

Categories