How to pass javascript variable to php inside javascript function - javascript

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>

Related

How to use ajax for php in the same page?

Hello friends i want use ajax on same php page. But problem is i can use ajax on different pages but not in same page. I saw people accomplished it with jquery but i dont wanna use jquery. Thanks-
<?php
$gg = $_POST['day'];
echo 'today is '.$gg;
?>
<html>
<head>
<script>
function clickMe(){
// Create our XMLHttpRequest object
var req = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "example.php";
var dayName = document.getElementById("dayName").innerText;
var vars = "day="+dayName;
req.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
let return_data = req.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
req.send(vars); // Actually execute the request
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
<p id="dayName">saturday</p>
<button onclick="clickMe()">btn</button>
<br><br>
<div id="status"></div>
</body>
</html>
First of all in your php code you are getting input via $_GET and in your code you are sending a POST request which is counter intuitive. What you can do is when certain parameters are passed either through query string or request body with a post request, you can write your desired output and call die() to not display the rest of it which will interfere with the response you get. I don't see a real reason to do so in the same file but, here's an example using query string:
<?php
if(isset($_GET['day'])) {
die('Today is ' . htmlspecialchars($_GET['day']));
}
?>
Then in your javascript code make sure you send a valid request according to your needs.
It's not a good idea to use the same page to print html and do some php stuff. But, if you really want to do so, with javascript you can send another var like ajax=1 and change you php code :
<?php
if(isset($_POST['ajax'])) {
echo 'today is '.$_POST['day'];
exit;
}
?>

How can I convert this PHP code in a way that will allow me to add it in .JS using Ajax?

I have a .js file hosted on domain1.com, but for this to work correctly I need to add a PHP code at the beginning. The reason for this is to bypass some restriction on Safari for my script and it requires me to create a session. The PHP code creates a session through a url to domain2.com. There is no browser redirection or anything, the user stays in the domain1.com. I want to have a single .js file in domain1.com so maybe an AJAX solution is what I need. Here it is:
<?php
session_start();
if (!isset($_SESSION['isIFrameSessionStarted']))
{
$_SESSION['isIFrameSessionStarted'] = 1;
$redirect = rawurlencode('http://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
header('Location: domain2.com/start-session.php?redirect=' . $redirect);
exit;
}
?>
The start-session.php file is hosted on domain2.com does not need any changes, it contains this:
<?php
session_start(); // create the session cookie
$redirect = rawurldecode($_GET['redirect']);
header('Location: ' . $redirect); // redirect back to domain
exit;
?>
Let me combine what you requested in comments:
I have a .js file hosted on domain1 ... I want to have a single js file and I can't put PHP into that ... the whole purpose of this is for domain1 to not have any php code or php file. ... The reason is because I want it cross-domain and the session to be created from domain2.
It sounds like your issue might be related to the Safari iFrame session cookie problem, especially because you have if (!isset($_SESSION['isIFrameSessionStarted'])) in one of your code blocks. I will continue with this assumption.
Summary of the problem for other readers:
Upon embeding an IFrame from one domain into a website of a different domain, you will quickly realise that Internet Explorer and Safari are blocking the cookies (and thus the session variables) of the website inside the IFrame (ref).
Attempted solutions that didn't pan out:
Safari 3rd party cookie iframe trick no longer working?
Internet Explorer & Safari: IFrame Session Cookie Problem
IFrame must die
Safari: Setting third party iframe cookies
PHP Session in iFrame in Safari and other browsers
My solution:
Essentially, PHP session "hijacking". It works surprisingly well where the above solutions failed. This is the essential solution. Please do any security enhancements* and URL-prettifying you like. Basically, we retrieve the PHP session ID through redirects and pass this to the iframe. Instructions are in the comments.
In your domainA.com head place this:
<script src="session.js"></script>
session.js (on domainA.com):
// Location of the domain B session starter
var sessionScriptURL = "http://domainB.com/start-session.php";
var refQSparam = "phpsessionid";
// Check if we have the phpsessionid in the query string
var phpsessionid = getParameterByName(refQSparam);
if(phpsessionid === null) {
// Not in the query string, so check if we have it in session storage
var sessionStore = sessionStorage.getItem(refQSparam);
if(sessionStore === null) {
// We have no session storage of the PHP session ID either, redirect to get it
top.location = sessionScriptURL + "?redirect=" + encodeURIComponent(self.location.href);
} else {
// phpsessionid was found in session storage. Retrive it
phpsessionid = sessionStore;
}
} else {
// Save the phpsessionid to session storage for browser refresh
sessionStorage.setItem(refQSparam, phpsessionid);
// Optional: Redirect again to remove the extra query string data
}
// Helper to get QS values
function getParameterByName(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}
session-starter.php (on domainB.com):
<?php
session_start(); // create the session cookie
$redirect = rawurldecode($_GET['redirect']);
// redirect back with the php session ID
// Optional: encode this information
$href = $redirect . '?phpsessionid=' . session_id();
header('Location: ' . $href);
exit;
HTML (in the body, on domainA.com):
Append PHP session information to the iframe src.
<script>
document.write('<iframe src="http://domainB.com/embedded-script.php?phpsessionid='+phpsessionid+'"></iframe>');
</script>
embedded-script.php (on domainB.com, in an iframe):
<?php
// Use the phpsessionid passed in
$phpsessionid = rawurldecode($_GET['phpsessionid']);
// REF: http://php.net/manual/en/function.session-id.php
function session_valid_id($session_id) {
return preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $session_id) > 0;
}
// Check that this is potentially a valid session ID
if(session_valid_id($phpsessionid)) {
// Set the session to the one obtained in session-start.php
session_id($phpsessionid);
}
session_start(); // Only call this after session_id()!
// Rest of your code
*Considerations:
Don't actually use document.write, use jQuery or document selectors.
Encode the PHP session ID
Perform another redirect back to the base URL of domainA.com to remove the ?phpsessionid= in the URL for a cleaner look.
If you decide to call session-starter.php with AJAX instead, you will get a new PHP session ID every time for the same reason. The iframe will successfully use this session ID, but if you open a new page to domainB.com, the session will yet again be different.
If you want to run PHP within a file extended with .js, you can do this by telling your apache web server. Add the following directive to the .htaccess or directly to the apache config:
AddType application/x-httpd-php .js
After this is done, your server will run the included PHP code as soon as the file is requested from the server.
Update:
If you want to use sessions with JavaScript, you can do this with an AJAX solution. For this implement a web service on the server which should store the session values. Programming language for implementation can be PHP or another one which can be run by the web server. Request the web service with JavaScript. Here is an answer with an example.
If you want to redirect in Javascript, you can't use a PHP redirect which you have called from AJAX. You can pass the URL you create in PHP and send it back to JavaScript and do the redirect from there. You can do something like:
PHP:
session_start();
if (!isset($_SESSION['isIFrameSessionStarted'])) {
$_SESSION['isIFrameSessionStarted'] = 1;
$redirect = rawurlencode('http://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}");
echo json_encode(array('url' => $redirect));
}
JavaScript:
$.get('phpfile', function(result) {
if (!result) return;
var data = JSON.parse(result);
window.location.href = decodeURIComponent(data.url);
});
Don't know what you're trying to achieve exactly but let's say you want to go from php to js and back to php you could trying something like this:
Solution 1: Using XMLHttpRequest
In PHP (domain1.com):
<?php
$parameter = ""; //If you'll like to add a parameter here
echo "<script type='text/javascript'>window.addEventListener('DOMContentLoaded',". "function () { goToJS('$paramter');});</script>";
?>
In JS:
window.goToJS = function (parameter) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
//You can redirect back to a php file here
document.location.href = "domain1.com";
//You can view feedback from that php file you sent the stuff to here - just for testing
alert("feedback" + xmlhttp.responseText);
}
}
xmlhttp.open('GET', 'http://domain2.com/start-session.php?q=' + parameter, true);
xmlhttp.send();
}
Not sure about your redirect links and stuff but yeah this should pretty much work. Did something similar a while back
Solution 2: Using ajax
Using ajax you could have a JS script as follows. (type could be POST or GET, Used an example where you sent some json to the php file. Can change the data sent if you properly describe to me what you wish to send. Alternatively could be null also
In JS:
function init_() {
$.ajax({
type: 'POST',
url: 'http://domain2.com/start-session.php',
data: {json: JSON.stringify(selectedEvent)},
dataType: 'json'
}).done(function (data) {
console.log('done');
console.log(data);
}).fail(function (data) {
console.log('fail');
console.log(data);
});
}
In PHP:
Let's say you sent a javascript json to PHP. You could use it in PHP as follows:
<?php
$status_header = 'HTTP/1.1 ' . 200 . ' ' . 'OK';
header($status_header);
header('Content-type: text/javascript');
$json = json_decode($_POST['json']); //Do whatever you want with the json or data sent
echo "This is the returned data"; //Echo returned data back to JS or wherever
?>
why don't just use script directly (if you put this script on top of file it will wait the script to finish creating session in domain2 anyway. (I guess you have iframe in domain1 that call to domain2?)
<script src="http://domain2.com/start-session.php"></script>
USe jquery and jqxhr object for this request, no need send browser to second server, from domain1 you can request to browser load page to init session, and your client never see that.
//include jquery min library and do next code
$(document).ready(function (){
var jqxhr = $.get( "http://domain2.com/start-session.php", function() {
alert( "success" ); //some action for success
})
.done(function() {
alert( "second success" ); //when all is done (success done)
})
.fail(function() {
alert( "error" ); //some action for error
})
.always(function() {
alert( "finished" ); //some end action for anycase
});
});
you can delete .done function, .fail function, and always function as you wish.
NOTE: ready function is to make sure, that domain1 page completely load, and then run script.
reference https://api.jquery.com/jquery.get/

Ajax request to get data from php file?

I have been researching on how to make an Ajax request and came up with this:
function ajax_post(){
// Create our XMLHttpRequest object
var xmlhttp = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "http://localhost:888...-files/test.php";
// Set content type header information for sending url encoded variables in the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var return_data = xmlhttp.responseText;
document.getElementById("demo").innerHTML = return_data;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.send(); // Actually execute the request
document.getElementById("demo").innerHTML = "processing...";
}
I saved this script as a file under: http://localhost:888...ascript/test.js <-- I have tested other scripts saved at this location and they work perfectly fine. My php file contains the following data (it is named "test.php"):
<?php
echo(rand(10,100));
?>
After I make the request to the php file which should display a random number according to the php code, my html looks like this:
<div style="display:none;">
<body onload="ajax_post()"> <------ Here you can see that I have called the function which executes the AJAX Request after the page has loaded.
<script type="text/javascript" src="http://localhost:888...ascript/test.js"></script>
</body>
</div>
<div id="demo"></div>
I keep refreshing the page and nothing appears. Does it have to do with my php code? Perhaps my Ajax request is wrongly structured? In terms of Ajax request, I have tried "GET" and "POST" as well and still nothing happens. I am new at Ajax and the might syntax my not make sense... Thank you in advance for the support.
Regards!!
I added some html to the php file and everything loads except the php file (php appeared as a comment). Then, I came up with the idea to compare the php file I created with the other php files on my local server. I identified a little difference. The other php files do not close the php, i.e. <?php echo 'Hello World'; without putting ?> at the end, and now it works. My php file looks like this:
<?php
echo 'Hello World';
I also simplified my script, making my structure look like follows:
<div id="demo"><div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready( function() {
$('#demo').load('http://localhost:8888/...php-files/test.php');
});
</script>
I used JQuery .load() property as it is simpler than the normal script (same principle).

Cannot read POST array from AJAX call in external PHP file

I've tried every solution I could google, but I can't read the data from a POST array in my external PHP file. Here's the HTML of the text field.
<form>
<textarea id="comment_text_area" name="comments" rows="5" cols="40">
</textarea>
<label for="comment_text_area">Comment:</label>
<br>
<input type="submit" name="submit" value="Submit" onclick="SaveComments()">
</form>
... and the JS function making the AJAX call
function save()
{
var data = document.getElementById("comment_text_area");
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', 'save_comments.php', true);
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
alert("Comments saved!");
}
}
xhr.send(data);
}
... and the PHP file
<?php
if(isset($_POST['comments']))
{
$data = htmlentities($_POST['comments']);
$file = "comments.txt";
file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
}
else
{
$data = "empty";
$file = "comments.txt";
file_put_contents($file, $data, FILE_APPEND | LOCK_EX);
}
?>
What I know is working:
The AJAX call is completing successfully, and the script is being run and "empty" is being written.
Things I have tried:
I read that event listener functions should be attached to HTML elements before they are made, which seems counter-intuitive. Made no change.
Using
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
Didn't work. And, based on the research I've done for that, shouldn't that only seem necessary for GET calls? (I need to use POST)
Making the POST call synchronous. Nothing changed.
I Know that the name of the element you're passing needs to be what you rely on in the PHP script, but it's not working. I don't want to set form action="" because I don't want redirection, which is why I'm going through AJAX.
Finally, something I've noticed, it's changing the URL as I click submit, something I would expect from GET. That is GET specific, right? I clearly marked it as POST though.
Does anyone see what I am doing wrong?
P.S. - Please, if it's on the JS side of things, no jQuery. I've avoided it thus far, I'm trying to keep it that way.
You need a variable to pass in the request not just the value as
xhr.send("comments="+data);
So that in server side you can retrieve the data by param name.

I need a hashtag value from the url in php

I need to get the text behind the hashtag in the url (http://www.example.com/#TEXT) so i can use it in a php script. I know that I have to gather the text using javascript then save it as a cookie or something like that. The only problem is that I'm not good at javascript and I have tried but failed.
How can i do this the easiest way?
Here is one thing i have tried:
<script>
var query = window.location.hash;
document.cookies = 'anchor=' + query[1];
<?php if (!$_COOKIE['anchor']) : ?>
window.location.reload();
<?php endif; ?>
<?php
echo $_COOKIE['anchor'];
?>
Most sites that use the fragment like this (such as Facebook) will use JavaScript AJAX calls, depending on location.hash, to send its request to the server. Try that!
var xhr = new XMLHttpRequest();
xhr.open("GET","something.php?hash="+location.hash.substr(1),true);
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200) {
// do something with this.responseText
}
};
xhr.send();
The hash part of the URL is not sent to the server, so you need to do so yourself.
The cookies set by the client too are not sent to the server either; the client just remembers them when it talks to the server.
This means that you have to retrieve in Javascript, as you already did, and make an explicit call.
// Example in jQuery
jQuery.ajax({
type: "POST",
url: "/path/to/php/script.php",
data: {
hash: window.location.hash
}
});
Then in the script.php you receive a $_POST['hash'] variable and can store it in the session. But remember that when you do, the sending page has already been loaded and is "stopped". If you want to trigger a reload, you need to send back some kind of response and react to it in jQuery's return function.
You can't. hashtags don't fly to the server. that's why MEGA site is still alive. hashes live only in the browser.

Categories

Resources