how to get javascript variable value in php in same file - javascript

I have a PHP file, having HTML and JavaScript code also,
I want to use the javascript variable value in the php code,
Sample code is as follows:
<script>
function dropdown(){
var e = document.getElementById("im_position");
var strUser = e.options[e.selectedIndex].value;
}
</script>
<?php
$q = //here want to use strUser(javascript varible);
?>
How do I use it ?
Help me..

You can't access to javascript variable like that. PhP is execute by the server and JavaScript by client.
You can create an ajax function in JS who call your php script.
http://www.w3schools.com/ajax/
Here you can learn to use Ajax.
JS
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
xhttp.responseText // return from your php;
}
};
xhttp.open("GET", "yourphp.php?variable="+yourjsvariable, true);
xhttp.send();
}
Php
<?php
return $_GET["variable"];
?>

You can't.
Php runs server-side. Javascript runs client-side.
This means that php compiles into html and does not reach the client. Javascript runs on the client's browser.
Your best solution would be to use ajax.

Related

Failed to Send data with external file.js to php using XMLHttpRequest()

put the javascript code directly in the HTML page, it does work. Howcome it does not work if I reference the script using the src attribute on the script
This is my HTML page:
<html>
<head></head>
<body>
<script src="file.js"></script>
</body>
</html>
I can not get the following javascript code to send data to a PHP page:
this is inside file.js
var http = new XMLHttpRequest();
var url = 'server.php';
var params = 'a=use&b=12345678';
http.open('POST', url, true); // error javascript stop always here
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200)
{ alert(http.responseText); } }
http.send(params);
and this is inside server.php:
<?php
$username = $_POST['a'];
$password = $_POST['b'];
echo 'username :' . $username;
?>
When I put the javascript code directly in the HTML page, it does work. Howcome it does not work if I reference the script using the src attribute on the script tag?
for example when i put the file.js script in online compiler like 'playcode.io' it does not work
It doesn't matter whether you put the javascript code directly in the HTML page or add it to the script using the src attribute on the script. The problem is, you aren't setting a request header with setRequestHeader(). Add the following line of code just after http.open(), but before http.send() and it'll definitely work:
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
The application/x-www-form-urlencoded format provides a way to encode name-value pairs.

Open local server file using plain javascript

I want to load locally stored data using plain javascript (no jquery for example) and then use it to display it in a table in html. My project structure looks like this:
root
- js
-- main.js
- res
-- data.csv
- index.html
I tried using a XMLHttpRequest, but somehow I get status 0 when trying to load the file and when printing the response text it prints out nothing at all.
The following method is called using window.onload:
var url = "file://../res/data.csv/";
varxmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
console.log(this.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
I don't think you can access the file system through most browsers.
Even if it worked locally, it wouldn't work as soon as you put your page up on a server. This is because the client will be asking for a file that is local to itself, not the server.
Chrome may have something for you though:
https://www.html5rocks.com/en/tutorials/file/filesystem/

producing a GET response to an ajax POST

In javascript I am POSTing with ajax and I need to get a reply from my Python program. The following code shows the javascript, but how does I produce the desired responseText from a GET on the Python side?
In this example I am want a Yes or No reply to a question for the user as to whether to change the name provided or not.
I understand how to receive the name and value in the python POST, but I don't know how to produce the response in the associated python GET.
function changeName(name,value){
var json = '[{';
json += '"name":"'+name+'",'
json += '"value":"'+value+'"}]'
loadDoc(json,"edit")
}
function loadDoc(data,url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("POST", ("/"+url), true);
xhttp.setRequestHeader("Content-type", "text"); #or something
xhttp.send(data);
}
My typical response in Python GETs follows one of the following 2 patterns, but neither seems to allow me to reply in this case.
self.response.out.write(template.render( template_values))
return webapp2.redirect("/templatename/%s" % variable)
(No PHP or jquery, please.)

Adding Datas via Javascript to existing JSON file on Server

I have following problem. I know that this is discussed quiet often, and i tried a lot of possibilities, but none is working up to now.
I have some datas in my javascript file, which i want to add to a already exsiting .json file on my server. I tried to do it the following way, but whenever i open the .json file after calling ajax_get_json(), no new datas are added.
function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open('POST', 'myyjson.json', true);
hr.setRequestHeader ("Content-type", "application/x-www-form-urlencoded");
var us = document.getElementById("firstname").value;
var msg= document.getElementById("message").value;
hr.onreadystatechange= function(){
if (hr.readyState == 4 && hr.status == 200){
var obj = JSON.parse(hr.responseText);
obj['participant'].push({"user": us, "message": msg});
var sendingObj =JSON.stringify(obj);
}
}
hr.send (sendingObj);
}
My myjson.json File has following structure:
{ "participant":[
{"user":"Steven", "message":" Hey,i m in!"},
{"user":"Tim", "message":" i wrote sth."},
{"user":"lukas", "message":"example"}
]}
Does anyone have an Idea what the problem yould be or is there a better way doing it?
Thanks in advance!
With javascript on client it's not possible to write JSON on server. If that would be possible, that would be kind of bad from the security perspective. You need to write JSON on server with what ever language you are using there (PHP, Java, javaScript). Then you call that server function from client with AJAX for example. It could go like this:
Javascript on client side request for example url www.yourserver.com/writejson.php?u=steven&m=Hi
On server you catch that request and write to JSON file. username is steven and message is Hi.
By the way, you have misunderstood XMLHttpRequest.send method. You are not sending data to be saved on server. You are firing XMLHttpRequest. Here is walkthrough how your code is executed:
function ajax_get_json(){
var hr = new XMLHttpRequest(); // 1.
hr.open('POST', 'myyjson.json', true); // 2.
hr.setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); // 3.
var us = document.getElementById("firstname").value; // 4.
var msg= document.getElementById("message").value; // 5.
hr.onreadystatechange= function(){ // 6.
if (hr.readyState == 4 && hr.status == 200){ // 8. this is called every time XMLHttpRequest state changes
var obj = JSON.parse(hr.responseText); // 9. this is called when XMLHttpRequest is completed and response is gotten
obj['participant'].push({"user": us, "message": msg}); // 10.
var sendingObj =JSON.stringify(obj); // 11.
}
}
hr.send (sendingObj); // 7. sendingObj is undefined

perl cgi talks to javascript

I want to retrieve a csv file from one online database. However, due to some XSS issues, I cant directly use ajax, but need to relay on a perl-cgi file.
I already had a working perl-cgi file that can query the csv file , and write the content of the file into a perl variable called $text. Here are some code snippets:
#!/usr/bin/perl
use strict;
use CGI;
use HTTP::Request::Common qw(POST);
use LWP::UserAgent;
# construct cgi object
my $q = CGI->new;
# create a post request
my $useragent = LWP::UserAgent->new();
my $request = POST '.....', [
#something goes here
];
my $response = $useragent->request($request);
my $text = $response->content;
print $text;
I have some general ideas of what to do next, but not so sure about the details. I will upload this perl-cgi file to the server that hosts my website, to the folder called cgi-bin. I just wonder how can I call that perl-cgi file from javascript, and write back the content of $text into javascript varaiable.
Thanks for the help
Javascript is a client-side language, while Perl is a server-side language. This means that you won't be able to directly read the value of a Perl variable into Javascript.
What you can do is have the Perl script output the results of its operations. Your Javascript then calls this Perl script via AJAX and reads the result.
Here's some pseudocode to illustrate what I mean:
Perl script: csv_worker.cgi
// retrieve csv file into $text as per OP
print "Content-type: text/csv\n\n";
print $text;
Javascript
function request() {
var xmlhttp;
if (window.XMLHttpRequest) {
// Supports newer browsers
xmlhttp=new XMLHttpRequest();
} else {
// Supports older IE versions (IE 5/IE 6)
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("result").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","csv_worker.cgi",true);
xmlhttp.send();
}

Categories

Resources