How to have PHP in JavaScript? - javascript

I tried embedding PHP in my JavaScript code to see what happens. Nothing actually happened. Can someone suggest me a way to do this?
<head>
<script>
function myF() {
n=document.getElementById("name").value
r=document.getElementById("reason").value
<?php
$f = fopen("VisitorLog.txt", "w");
fwrite($f, "Profile viewed on "+Date()+" by "+n+" Reason= "+r);
fclose($f);
?>
document.getElementById("name").disabled=true;
document.getElementById("reason").disabled=true;
document.getElementById("register").disabled=true;
document.getElementById("link").style.display="inline";
alert("You have successfully registered.");
}
</script>
</head>
I'm new to all this stuff and still learning. Please try explaining in simpler terms. :P

First keep in mind that PHP is rendered on the server and Javascript will be interpreted at your client(Web browser). so if you echo something from PHP it will be sent with the html and it won't be executed with the Javascript as you are assuming here.
To accomplish what you want here you need to make an AJAX call to a PHP script which will update your views log.
Edit:
on update.php file
<?php
$n = $_POST['n'];
$r = $_POST['r'];
$f = fopen("VisitorLog.txt", "w");
fwrite($f,"Profile viewed on ".date("Y-m-d H:i:s")." by ".$n." Reason= "+$r);
fclose($f);
And on your javascript (assuming you have jquery loaded)
<script>
function myF()
{
$.post("update.php",
{
n : document.getElementById("name").value,
r : document.getElementById("reason").value
},
function({
document.getElementById("name").disabled=true;
document.getElementById("reason").disabled=true;
document.getElementById("register").disabled=true;
document.getElementById("link").style.display="inline";
alert("You have successfully registered.");
}));
}
</script>

The main concept you need to understand is that Javascript runs on the client side, namely the web browser, and PHP on the server. The PHP code you have added to your page is executed before any Javascript is processed.
If you want your Javascript to send data to your PHP application you need to use Ajax.
Using libraries such as jQuery will make your life a lot easier.
Here's an example of how that can work using jQuery.
PHP - log.php
<?php
$string = sprintf('Profile viewed on %s by %s Reason= %s',
$_POST['date'], $_POST['name'], $_POST['reason']);
$f = fopen("VisitorLog.txt", "w");
fwrite($f, $string);
fclose($f);
?>
Javascript
var n = $("#name").val();
var r = $("#reason").val();
var d = new Date();
$.ajax({
url: '/path/to/log.php',
method: 'POST',
data: {name: n, reason: r, date: d}
}).done(function(response){
// response contains the output of log.php
});
Reference
http://api.jquery.com/id-selector/
http://api.jquery.com/jQuery.ajax/

PHP is rendered on server-side. JavaScript is rendered on client-side.

Like everyone said. You can't mix server side code with client side code.. php is renderd/executed at server side an js in the client's browser..
If possible separate js and php. A working solution could be: (assuming jQuery for the ajax call, actually another framework or even plain js could be used)
in your js file (or in the script tag in the header)
function log(message, success, failure){
$.ajax({
url: "logger.php",
data: {
message: message
},
success: success,
error: failure
})
}
function myF(){
var n=document.getElementById("name").value,
r=document.getElementById("reason").value;
log( "Profile viewed on "+Date()+" by "+n+" Reason= "+r, function(){
console.log('I successfully logged');
}, function(jqXHR, textStatus, errorThrown){
console.log('something went wrong', jqXHR, textStatus, errorThrown);
});
document.getElementById("name").disabled=true;
document.getElementById("reason").disabled=true;
document.getElementById("register").disabled=true;
document.getElementById("link").style.display="inline";
alert("You have successfully registered.");
}
in a file logger.php
<?php
if(isset($_GET['message'])){
$f = fopen("VisitorLog.txt", "w");
fwrite($f, $_GET['message']);
fclose($f);
}
?>

PhP is executed on the server, before the page loads. So your PhP will execute, then the page loads. Then the javascript loads. So your javascript here will not trigger the PhP.
The two ways to do this:
- Run the PhP script when the page laods on the server
- Use AJAX to run a server-side php script to register the userdetails.

Javascript runs on the client side, php runs on the server side. You need to make e.g. an ajax call to some method on the server side that will do server-side tasks.

Only the server can interpret and run the php code. Make sure that the file you are editing is stored in a server with php installed (you can try WAMP or XAMPP if you want to test locally in your computer).

Related

WordPress Button triggered ajax request

So I have actually read stackoverflow questions about this, but they are somewhat quite old to work with newest version of wordpress.
My end goal is to submit to database some data from my forms but for now ajax response is not working for me. On custom page load in WP all code is loaded so all functions should work. All of this is inside of PHP file for now that why echo is used to create JS scripts. Here's the important part of my code
echo '<button id="ZapisPrace">Save</button>
<script>
jQuery("#ZapisPrace").click(function($){
var data={
action: "addToDB",
info: "nomz"
};
jQuery.post(ajaxurl,data,function(response){
alert("Response was "+ response);
});
});
</script>';
add_action('wp_ajax_addToDB','pridajDoDB');
function pridajDoDB(){
echo '<script>console.log("AAA")</script>';
wp_die();
}
Using current version of WP so variable ajaxurl is pointing to the
/wordpress/wp-admin/admin-ajax.php
No console.log is happening, response is always 0, even when I remove pridajDoDB function or add_action. It's just not triggering the ajax request correctly. Can somebody let me know why?
Also I have not used yet functions like wp_localize_script, wp_register_script or wp_enqueue_script because all of this is in one PHP file that's loaded, and I don't need to import jquery as far as I know its default available in WP. I am just learning how to use WP, PHP AJAX and jQuery, so I have still quite a lot to learn.
PS: I am supposed to use the WP way of using ajax.
Change php code as follows.
add_action('wp_ajax_addToDB','addToDB');
function addToDB(){
echo "AAA";
wp_die();
}
Ok so I didn't figure out how code above works, however I managed to get it working trough different wp structure I found online:
BTW: I used onClick function here but it works even when replaced with jQuery click event.
add_action('wp_ajax_addToDB','pridajDoDB');
echo '<button onClick='triggerAjax()'>Save</button>?>';
<script>
function triggerAjax(){
<?php $nonce = wp_create_nonce( 'subbmitData' );?>//used so ajax response can verify from where is the request coming
jQuery.ajax({
type: "post",url: "admin-ajax.php",data: { action: 'addToDB', _ajax_nonce: '<?php echo $nonce; ?>' },
success: function(html){
console.log(html);//this will console log everything that happens in ajax called php function. Echo works as well.
}
});
}
</script>
<?php
function pridajDoDB(){
check_ajax_referer( "subbmitData" );//this check from where is the request coming from
//here database commands works but if you echo or console log something it will be just passed to success function above
die();
}
?>

WordPress Plugin => How to use JS AJAX to trigger plugin PHP functions

Building my first plugin, I'm having difficulty communicating between scripts. How to use JS AJAX to call the plug-in PHP script handling my functions.
I'm finding that loading the plug-in script NOT in WordPress is (obviously) causing rendering/permission issues.
Here's a boiled down version - the plugin is instantiated via a shortcode:
[short-code]
This kicks off the WP plug-in, carrying out some preliminary tasks.
After the DOM is loaded, I use HTML5 to find the user's geolocation.
Goal: Pass HTML5 geolocation data via AJAX to a php function located in the php file. Eg: Call to undefined function register_activation_hook()
var sf_path = jQuery('#sf_path').val();
var url = '/wp-content/plugin/plugin_name/plugin_name.php?h=true&=lat='+position.coords.latitude+'&lng='+position.coords.longitude;
var jqxhr = jQuery.get( url , function(data) {
console.log( "geolocate", data );
//Response = PHP Error: Call to undefined function register_activation_hook()
});
I think I can rewrite the code to differentiate platforms and run differently based on the request (basically, unwordpressify certain functions) but it would be much handier to NOT have to do that. wp_remote_get is very handy as is.
What am I missing?
The WP ajax calls are handled through the admin-ajax.php script. First, what you need to do is to register actions -
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action_callback' );
Next, you need to define what this my_action_callback would be doing.
function my_action_callback() {
// Handle Geo Location Data
wp_die(); // this is required to terminate immediately and return a proper response
}
Once done, you can send the AJAX call
<script type="text/javascript" >
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'geo': 1234
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
});
</script>
If ajaxurl is undefined, you can define it this way -
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
You can find more about that on the documentation
Ultimately, I was able to solve this with the help of #ToshoTrajanov's help by pointing out how to get the ajaxurl variable into page. It was my stumbling block. For me, though, I kick my mark-up off in PHP and added the following to my php init function:
<?php
print "<script class='gcCleanup'>";
print 'var ajaxurl = "' . admin_url('admin-ajax.php') . '";';
print "</script>";
?>

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/

Using Ajax to require different php page

I want to use jquery ajax to change the content of my div elemnt by requiring different php files.
here is the ajax code :
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num
},
success:function(result){
$("#right_bot").html(result);
}
});
the project_functions.php would be something like :
$result = '<?php require "Panels/Project/Main/main.php" ?>';
echo $result;
I can see the value being outputted , but the html comment out the php part
<!--?php require "Panels/Project/Main/main.php" ?-->
It just comments out the php. Is there a way i load different php files into my div ?
In the main.php file , It has php code , html code , and some style tags. Can I use ajax to load all this into the div element ? or I have to echo all my html code ?
You can't do this like that. What you want is that all PHP is excecuted on the server and only the result has to be returned.
You can't send php-code back to javascript and try to run it there, PHP is a serverside language, it will only work on the server. Javascript is clientside, it will only run in the browser.
If you where to send <?php echo 123; ?> back to Javascript, you'll get exactly that as result, not 123.
The solution in your case is to make project_functions.php really require it. This will include the main.php, all it's functions and output.
require "Panels/Project/Main/main.php";
Some suggested reading:
http://www.codeconquest.com/website/client-side-vs-server-side/
A trick which might help you: Paste the link to your urlbar, and add the variables to it. The result you get in your screen is what Javascript will output. Note: This only works for method=get, not post.
In this case browse to /project/Functions/project_functions.php and do the simple require per my code above. That output will be send to Javascript.
Send a parameter in the ajax request 8for example type):
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num, type: "main"
},
success:function(result){
$("#right_bot").html(result);
}
});
And then in php-file get the type variable:
if($type == "main") {
require "Panels/Project/Main/main.php"
}
else {
require "Panels/Project/Main/sthelse.php"
}
You should also have some sort of same function name or something to output the results of the file;
<?php
function printResult() { }
echo printResult();
Try:
$result = file_get_contents('Panels/Project/Main/main.php');

PHP inside Javascript in a registration form (for validation)

I'm developing a registration form for my site. Actually when a visitor choose an username, a php query to my MySQL DB is used to control if it's already used and if so, a javascript windowd appear.
Can i use a PHP query inside Javascript for displaing a real-time notice near the form (using HTML5)?
<script>
var username = document.getElementById('username');
var userdb = <? php control_username($username); ?>
var checkUsername = function () {
if (userdb.value == true) {
username.setCustomValidity('Username already used');
} else {
username.setCustomValidity('');
}
};
username.addEventListener('change', checkUsername, false);
</script>
and here there's the php function:
<?php function control_username($username){
$db=connessione_db();
$query = "SELECT username FROM utente WHERE username = '$username';";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[0]==$username){
return TRUE;
}
else{
return FALSE;
}
$query=NULL;
}
how can i do?
You can use AJAX or jQuery AJAX to send a request to a php page, Check if the username exists, return the result, and display it using Javascript again.
Here is the jQuery sample:
<script>
$.ajax({
type: 'POST',
url : 'checkUsername.php',
data: {'username' : $('#username').html()},
cache : false,
success: function(data){
if(data == 'exists')
//username exists
alert('username already exists!');
},
error: function(request , status , error){
alert(request.resposeText);
}
});
</script>
and this should be your checkUsername.php file:
<?php
$db=connessione_db();
$query = "SELECT count(*) as count FROM utente WHERE username = '$username'";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
mysql_close();
if($row[count] > 0)
echo 'exists';
else
echo '';
PHP is run on the server, Javascript is run on the client's machine. Once your PHP script has generated a page and sent it to the user, it doesn't run any longer. Your client has no knowledge of a PHP script. It can't directly run, call, or read anything about your PHP script because it resides solely on the server (never on the client's machine). Your client's machine does, however, know about your Javscript since it has been sent along with the page. If you want to access PHP functionality from your page, you can either send a GET/POST call to the server and reload the page, or use AJAX to make the call in the background. Check out Jquery's implementation of AJAX calls, it makes using it pretty simple.
No you can't do it like that. PHP is serverside, Javascript clientside. The moment Javascript is executed is the code working clientside. All PHP code is fixed.
Compare it to the combination of HTML and PHP in an HTML page. It is fixed there as well. Same applies to PHP in Javascript.
Here are some answers from related questions on stackoverflow:
How to put php inside javascript?
How to embed php in javascript?
Here is an example from ajaxref, showing the basics:
http://ajaxref.com/ch3/asyncsend.html
This is another tutorial showing how an ajax call is handled:
http://code.tutsplus.com/articles/how-to-make-ajax-requests-with-raw-javascript--net-4855
I advice you to first understand this process and later on start using a framework like jQuery.

Categories

Resources