How can I access my Javascript Variables in PHP? - javascript

I have a file called lightstatuspage.php and within it, I have HTML, JavaScript and PHP code. I have used some variables within the JavaScript part of the code and I am trying to send these variables to the server by passing them to the PHP part of the code. However, this is not working.
I am using $.post("lightstatuspage.php", slider_val); and then in the PHP part, I am calling the variable by doing $_GET['rangeslider_val'];.
What am I doing wrong and what can I do differently to get the variable from JavaScript and send it to the server?
function show_value(x)
{
document.getElementById("slider_value").innerHTML=x;
event.preventDefault();
var slider_val = x;
var query = new Parse.Query(Post);
query.first({
success: function(objects){
objects.set("slider_val", slider_val);
objects.setACL(new Parse.ACL(Parse.User.current()));
return objects.save();
window.location.href = "lightstatuspage.php?rangeslider_val=" + slider_val;
}
})
}
The PHP code is:
<?php
$_GET['rangeslider_val'];
print($rangeslider_val);
?>

First Add Jquery
<script src='https://code.jquery.com/jquery-1.11.3.min.js'></script>
to the end of page before closing body tag.
To send Javascript variable to PHP. the best way is to use Ajax. and add the following code to your javascript.
Do not forget that the below code should be on an event. For example on a button click or something like that
$( document ).ready(function() {
var x = $('#input1').val();
//or var x= 15;
$.post("lightstatuspage.php",
{
'rangeslider_val': x
},
function(data, status){
//alert("Data: " + data + "\nStatus: " + status);
// you can show alert or not
});
});
and in php, you can use:
$value = $_POST['field1'];
now your variable is in $value in php.
P.S:
Backend Page and HTML page should be on same domain or you have to check Cross-Origin Resource Sharing
Second Solution
as the User accepted this solution here would be the code:
$.get("lightstatuspage.php?rangeslider_val=" + slider_val,function(res) {
console.log(res);
});
the second way is only the difference between POST and GET method
Third Solution
if you don't want to use Jquery in your project and you need pure javascript you can use below code
var str = "Send me to PHP";
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "lightstatuspage.php?rangeslider_val=" + str, true);
xmlhttp.send();

Change the order of the last 2 lines of your JS function. You are returning from the function before changing the page's location.

you forgot to store variable on print
<?php
$rangeslider_val = $_GET['rangeslider_val'];
print($rangeslider_val);
?>

You call $_GET but you don't assign the value to the variable $rangeslider_val in PHP and you are returning in JavaScript before calling the PHP script. Also you mentioned that you want to use $.post from clentside if you do it this way you have to use PHP $_POST to get it from there.

Related

How to receive HTTP POST parameters on vue.js? [duplicate]

I am trying to read the post request parameters from my HTML. I can read the get request parameters using the following code in JavaScript.
$wnd.location.search
But it does not work for post request. Can anyone tell me how to read the post request parameter values in my HTML using JavaScript?
POST data is data that is handled server side. And Javascript is on client side. So there is no way you can read a post data using JavaScript.
A little piece of PHP to get the server to populate a JavaScript variable is quick and easy:
var my_javascript_variable = <?php echo json_encode($_POST['my_post'] ?? null) ?>;
Then just access the JavaScript variable in the normal way.
Note there is no guarantee any given data or kind of data will be posted unless you check - all input fields are suggestions, not guarantees.
JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.
Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.
Use sessionStorage!
$(function(){
$('form').submit{
document.sessionStorage["form-data"] = $('this').serialize();
document.location.href = 'another-page.html';
}
});
At another-page.html:
var formData = document.sessionStorage["form-data"];
Reference link - https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage
Why not use localStorage or any other way to set the value that you
would like to pass?
That way you have access to it from anywhere!
By anywhere I mean within the given domain/context
If you're working with a Java / REST API, a workaround is easy. In the JSP page you can do the following:
<%
String action = request.getParameter("action");
String postData = request.getParameter("dataInput");
%>
<script>
var doAction = "<% out.print(action); %>";
var postData = "<% out.print(postData); %>";
window.alert(doAction + " " + postData);
</script>
You can read the post request parameter with jQuery-PostCapture(#ssut/jQuery-PostCapture).
PostCapture plugin is consisted of some tricks.
When you are click the submit button, the onsubmit event will be dispatched.
At the time, PostCapture will be serialize form data and save to html5 localStorage(if available) or cookie storage.
I have a simple code to make it:
In your index.php :
<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>
In your main.js :
let my_first_post_param = $("#first_post_data").val();
So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.
POST is what browser sends from client(your broswer) to the web server. Post data is send to server via http headers, and it is available only at the server end or in between the path (example: a proxy server) from client (your browser) to web-server. So it cannot be handled from client side scripts like JavaScript. You need to handle it via server side scripts like CGI, PHP, Java etc. If you still need to write in JavaScript you need to have a web-server which understands and executes JavaScript in your server like Node.js
<script>
<?php
if($_POST) { // Check to make sure params have been sent via POST
foreach($_POST as $field => $value) { // Go through each POST param and output as JavaScript variable
$val = json_encode($value); // Escape value
$vars .= "var $field = $val;\n";
}
echo "<script>\n$vars</script>\n";
}
?>
</script>
Or use it to put them in an dictionary that a function could retrieve:
<script>
<?php
if($_POST) {
$vars = array();
foreach($_POST as $field => $value) {
array_push($vars,"$field:".json_encode($value)); // Push to $vars array so we can just implode() it, escape value
}
echo "<script>var post = {".implode(", ",$vars)."}</script>\n"; // Implode array, javascript will interpret as dictionary
}
?>
</script>
Then in JavaScript:
var myText = post['text'];
// Or use a function instead if you want to do stuff to it first
function Post(variable) {
// do stuff to variable before returning...
var thisVar = post[variable];
return thisVar;
}
This is just an example and shouldn't be used for any sensitive data like a password, etc. The POST method exists for a reason; to send data securely to the backend, so that would defeat the purpose.
But if you just need a bunch of non-sensitive form data to go to your next page without /page?blah=value&bleh=value&blahbleh=value in your url, this would make for a cleaner url and your JavaScript can immediately interact with your POST data.
You can 'json_encode' to first encode your post variables via PHP.
Then create a JS object (array) from the JSON encoded post variables.
Then use a JavaScript loop to manipulate those variables... Like - in this example below - to populate an HTML form form:
<script>
<?php $post_vars_json_encode = json_encode($this->input->post()); ?>
// SET POST VALUES OBJECT/ARRAY
var post_value_Arr = <?php echo $post_vars_json_encode; ?>;// creates a JS object with your post variables
console.log(post_value_Arr);
// POPULATE FIELDS BASED ON POST VALUES
for(var key in post_value_Arr){// Loop post variables array
if(document.getElementById(key)){// Field Exists
console.log("found post_value_Arr key form field = "+key);
document.getElementById(key).value = post_value_Arr[key];
}
}
</script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
One option is to set a cookie in PHP.
For example: a cookie named invalid with the value of $invalid expiring in 1 day:
setcookie('invalid', $invalid, time() + 60 * 60 * 24);
Then read it back out in JS (using the JS Cookie plugin):
var invalid = Cookies.get('invalid');
if(invalid !== undefined) {
Cookies.remove('invalid');
}
You can now access the value from the invalid variable in JavaScript.
It depends of what you define as JavaScript. Nowdays we actually have JS at server side programs such as NodeJS. It is exacly the same JavaScript that you code in your browser, exept as a server language.
So you can do something like this: (Code by Casey Chu: https://stackoverflow.com/a/4310087/5698805)
var qs = require('querystring');
function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
// use post['blah'], etc.
});
}
}
And therefrom use post['key'] = newVal; etc...
POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.
SITE A: has a form submit to an external URL (site B) using POST
SITE B: will receive the visitor but with only GET variables
$(function(){
$('form').sumbit{
$('this').serialize();
}
});
In jQuery, the above code would give you the URL string with POST parameters in the URL.
It's not impossible to extract the POST parameters.
To use jQuery, you need to include the jQuery library. Use the following for that:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" type="text/javascript"></script>
We can collect the form params submitted using POST with using serialize concept.
Try this:
$('form').serialize();
Just enclose it alert, it displays all the parameters including hidden.
<head><script>var xxx = ${params.xxx}</script></head>
Using EL expression ${param.xxx} in <head> to get params from a post method, and make sure the js file is included after <head> so that you can handle a param like 'xxx' directly in your js file.

How to pass ajax val to php variable on the same page?

$('#test-test_id').change(function() {
var myValue = $(this).val();
});
// $getMyValue = $(this).val();
For example, by using the code above, I want to pass $(this).val to the php variable on the same page. How is this possible?
windown.location can reload page with parameters . You can try that in sending val to php variable like below...
<input type="text" id="test-test_id">
<?php
if(isset($_GET["val"])){
$sent = $_GET["val"];
echo "<h2>".$sent."</h2>";
}
?>
<script type="text/javascript">
$('#test-test_id').change(function() {
var myValue = $(this).val();
window.location = '?val=' + myValue; //redirect page with para ,here do redirect current page so not added file name .
});
Update code for without refresh
$('#test-test_id').change(function() {
var myValue = $(this).val();
$.get("",{val:myValue},function(data){
$("body").html(data);
});
//you can try with many option eg. "$.post","$.get","$.ajax"
//But this function are not reload page so need to replace update data to current html
});
</script>
What you want to do is a bit complicated, first you must make an AJAX request where you pass the variable from client to server, like this:
$.post('/', { variable: "your_value_here" }, function() {
alert('Variable passed');
});
This simple code, made in Javascript sends a POST Request to a URL that you pass to function as the first parameter, in this case we pass to $.post the same page. Now, in PHP you must handle the POST request:
session_start(); // We start a session where we'll set the value of variable.
if(isset($_POST['variable'])) {
$_SESSION['your_var'] = $_POST['variable'];
} else {
/* Your page code */
}
You can also register the variable in the database, but if it's a temporary variable you can just register it in the session. Remember to use session_start() in every page before using $_SESSION global variable.
Helpful documentation:
jQuery.post() ,
PHP Sessions

JS counter write to database

Is there any way I can use this JS second counter, to write to mysql:
var counter = 0;
setInterval(function () {
++counter;
}, 1000);
Can I export it as a variable and then use that variable to write to mysql?
What I'm attempting to do is save the time the user was on the page.
Is this even possible?
To help solve your ajax part (need jquery):
$.ajax({
type:'POST',
url: "yourfile.php",
data:{
"foo": filename // to add more variables you add on the spot after filename but remember the last one variable you send shouldn't have a comma
}
});
on the receiving end (php):
<?php
$filename = $_POST["foo"];
?>
basically ajax is used to send data to a php script.
Javascript is a language that is used in client side and can't write to MYsql. The code above will help you send data to your script. Your php script will run once it recieves the data through AJAX
You would need to write a bit of back-end php to handle ajax query from your front-end javascript.
Your JS may look like this:
function ajaxRequest(data) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("POST", "path/to/back-end.php", true);
xmlHttp.timeout = 1000;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) { //DONE
//success
console.log("Successfully sent to back-end.php");
}
};
xmlHttp.send(data);
}
You can refer to http://www.w3schools.com/ajax/default.asp for more information.
Then your php will retrieve the body of this POST request and insert it to mysql database accordingly.

How to pass javascript variable to php inside javascript function

I have a js file. Is it possible to do inside the js file a php coding? On my header I include my js file like this.
<script type="text/javascript" src="js/playthis.js"></script>
now inside my jsfile:
function getURL(e) {
alert(e+' javascript varibale');
<?php $url; ?> = e;
alert('<?php echo $url; ?>'+' php variable');
}
in my php file
<?php $url = "www.google.com"; ?>
<a href="#" onclick="getURL('<?php print $url; ?>');" class="title">
It's not working. Is there something wrong?
you have to make a new object for Ajax transaction named XMLHTTP REQUEST in some browsers and in I.E this is ActiveXObject basically; and this object belong to window object;
so the first step is:
if ( window.XMLHttpRequest ) {
XHR = new XMLHttpRequest();
}
else if ( window.ActiveXObject ) {
XHR = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
alert("You Cant see because Your Browser Don't Support Ajax!!!\n Change Your Browser To A Modern One");
}
now, you have the right object
in next step, there is some methods for XHR object for send and receive you should know:
1/ onreadystatechange
2/readyState
3/status
4/open
5/send
6/setRequestHeader
first open a connection with open:
XHR.open("POST", url, true);
as you know, post is method of sending, and now you have to set the url you want to information send to, for example if you want to send the variable to the test.php, then the url is test.php...
true means the request will sent asynchronously..
next is set your request header, because your are using post method, in get method you don't need this:
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
next is sending the request with send method with this format send(name, value):
XHR.send('value=' + value);
first string 'value=' is the index of $_POST that you will get in php, so in your php code, you'll give this with $_POST['value'], if you set the name to 'name=', in php you have $_POST['name'], be careful that in Ajax send param you have to use = after the name of data, but in php the = is not used...
after you sent the request; it's time to mange response:
XHR.onreadystatechange = function() {
if ( XHR.readyState == 4 && XHR.status == 200 ) {
document.getElementById('your target element for show result').innerHTML == XHR.responseText;
}
}
XHR.readyState == 4 and XHR.status == 200 means every thing is O.K.
this is the basics of Ajax as you wished for; but there is so many information for Ajax, and either you can use jQuery Ajax method that is so simple and flexible; But as you want I described the basics for you...
No it's not possible to have PHP code inside JS file.
You can make $.ajax call to a PHP file and that file can handle the setting of the variable required.
Hope this helps.
There are a few ways to handle this.
1 - Have .js files parsed by php. You will need to change your webserver configuration to do this.
2 - Use AJAX to interact with php.
3 - Have php render an additional JS snippet in the body onload event that sets this JS parameter (but still have the library as a seperate file).
this is not necessary, when you print the url with print $url in onclick attribute inside the php page as an argument for getURL function, it means the value of $url will be sent to the function with name getURL in your js file...
so, you have to write:
alert(e);
and if you are just asking, as the other friends told, you should use Ajax for this...
when you assign a variable to a function as an argument, just like getURL(e), the time that you call the function,getURL('print $url") you have to set the value of that variable, so, the program set the value you give to the function to the default variable...e = $url
you can change .js file to .php file and work with javascript and php together
change this
<script type="text/javascript" src="js/playthis.js"></script>
to this
<script type="text/javascript" src="js/playthis.php"></script>

Using AJAX to access to the Twitter API

I'm thinking about adding some twitter functions in my web-application, so I started doing some tests. I checked the way to call the search twitter URL (more info in: http://dev.twitter.com/doc/get/search) in order to get tweets that contains the searched word/sentence. I realized that you can do it in php just getting the JSON file that the search URL returns with the file_get_contents() function. Also you can do it directly in JavaScript creating a script object, appending it to the body and use the callback parameter of the search URL to process the data.
Different ways to do, but that's the way I finally did it:
MAIN HTML FILE:
<title>Twitter API JSON</title>
<script type="text/javascript">
//function that created the AJAX object
function newAjax(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//function that search the tweets containing an specific word/sentence
function gettweets(){
ajax = newAjax();
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'getsearch.php', true);
// Process the data when the ajax object changes its state
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 ) {
if ( ajax.status ==200 ) { //no problem has been detected
res = ajax.responseText;
//use eval to format the data
searchres = eval("(" + res + ")");
resdiv = document.getElementById("result");
//insert the first 10 items(user and tweet text) in the div
for(i=0;i<10;i++){
resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
}
}
}
}
ajax.send(null);
} //end gettweets function
</script>
#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>
</html>
PHP WHERE WE GET THE JSON DATA:
$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";
$json = file_get_contents($jsonurl,0,null,null);
echo $json;
And that's it, in this way it works fine. I call the PHP file, it returns the JSON data retrieved from the search URL, and in the main HTML JavaScript functions I insert the tweets in the div. The problem is that at the first time, I tried to do it directly in JavaScript, calling the search URL with Ajax, like this:
MAIN HTML FILE:
//same code above
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);
//same code above
I thought it should return the JSON data, but it doesn't. I'm wondering why not and that is what I would like to ask. Does someone have any idea of why I can't get JSON data using the Ajax object? If the search URL http://search.twitter.com/search.json?q=%23search_word&rpp=10 returns JSON data, it should be obtained in the ajax object, right?
XHR requests are generally limited to same-domain requests; e.g, if you're on bertsbees.com, you can't use an Ajax method to pull data from twitter.com.
That said, Twitter's API supports a popular data transport method known as JSON-P, which is really just a glorified injection technique. You simply pass it a callback method, and the data returned will be wrapped in your desired function, so it gets eval'd and passed in.
You cannot make a cross domain request using javascript, unless you are doing from an browser addon.

Categories

Resources