I've seen many posts related to what I'm asking, but I can't seem to find an appropriate answer, and I'll admit I'm a n000b to both Javascript and PHP. I've followed some tutorials, but I can't seem to do what I want:
I have a HTML document that is subscribing to a SSE like so:
var eventSource = new EventSource("http://thewebsite.com/events/?access_token=" + accessToken);
I don't want to put the accessToken in the HTML page because it's insecure, so I'd like to hide the access token in a separate PHP file in the same directory, something like this:
code.php
<?php
$accessToken = "12345ABCDE";
?>
I can't figure out how to write the javascript to ask code.php for the accessToken.
echo should do the trick:
fetch.php
<?PHP
echo "12345ABCDE";
?>
but you need to use ajax to call the php:
$.post("fetch.php",function(data){access(data);},"text");
or
$.ajax({
type: "POST",
url: "fetch.php",
success: function(data){access(data);},
dataType: "text"
});
using token:
function access(incoming){
var eventSource = new EventSource("http://thewebsite.com/events/?access_token=" + incoming);
}
how safe it is to output your token from PHP is another story, but at least that's how it can be done.
Related
I have an HTML input with a function and parmeter set to it like so
<input onclick='myFunc($count)' type='button' value='ClickMe'>;
I also have script references to JQuery and my script file
<script src="jquery.js"></script>
<script src="myscript.js"></script>
Inside my myscript.js file I have the contents as such
function myFunc(x) {
alert(x);
$(document).ready(function() {
$.ajax({
url: "myphp.php",
method: "post",
data: { param1: "x" },
dataType: "text",
success: function(strMessage) {
}
})
})
}
Here is my myphp.php file
<?php
$param1 = $_GET['param1'];
echo $param1;
?>
As you can see in the javascript file, I have alert(x); to test that the function is grabbing the $count variable and so far that is working (the correct value appears in the alert box). However, I want to pass that x parameter to the PHP script but my PHP script won't echo anything, I assume the line where I have param1 is wrong. Any tips?
In your AJAX call you are using a POST method, so in order to catch the variable in PHP you need to access it from $_POST:
<?php
$param1 = $_POST['param1'];
echo $param1;
?>
You're making the XHR with POST method
method: "post",
and youre looking for it in the GET array
$_GET['param1'];
Change either to post or get (keeping in mind your scenario) and you should be good imo.
read more here to know about the different methods of sending http requests: https://www.guru99.com/php-forms-handling.html
You are using post method in AJAX but trying to grab the value in $_GET which is wrong.
In your PHP code, just replace $_GET['param1'] with $_POST['param1'] and it works.
or If you like to use $_GET in your PHP code then change the method in AJAX or use $.get. Examples can be found on W3School.
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp
So my goal is to use PHP to get data from a PostGreSQL database. I want to use this data in a separate javascript file so I can display it on the screen a certain way that I have my website configured. All the tutorials that I have seen online just puts a script tag inside the PHP file but I cannot do that because my website display javascript code is in the separate file. I just need the numbers to be in the javascript file that I got from the PHP file that got its data from the PostGreSQL database. How can I do this?
I just need help with the means to get to the ends because I have researched on my own but it is always not exactly what I want.
PHP:
<?php
$myPDO = new PDO('pgsql:host=myHost; dbname=myDBName', 'myUsername', 'myPassword');
?>
$result = $myPDO->query("SELECT * FROM table WHERE id = 'someID'");
Now I want to use this row's values in another javascript file. How can I do this?
You could use Ajax for this.
You could so something like this in your JS file:
$.ajax({
type: "GET",
url: 'FILENAME.php',
success: function(data){
alert(data);
}
});
and then in your FILENAME.PHP just return the values.
Your JS should then pull through whatever has been returned, in this case, your database query.
Your JS file needs to request the data from your PHP controller, via an AJAX request. You can then manipulate the returned data object whichever way you like.
We have mainly two methods to pass php value to javascript variable
Simple variable method at the time of first page load
<script>
var js_variable = <?php echo $data_php_variable; ?> ;
//this is working only at the first time of the page load
//you can also parse the data to any format
</script>
Use AJAX call to trigger a PHP request and manipulate return PHP value in JS
$.ajax({
type: "GET", //get or post method
url: 'FILENAME.php', //php request url
data :{}, //optional ,you can send data with request
success: function(res){
// this 'res' variable is the php return data in the form of js data
console.log(res);
}
});
ajax method is more dynamic ,it can use any time request handling
use the javascript ajax to call a php api
pass your data at php in your view file , use something like:
var phpData = JSON.parse("<?php echo json_encode($data)); ?>");
I would need to echo php variables (from the server and related to service behaviour) into javascript. For example, "ssl" => "true" and adapt accordingly in javascript. The thing is I'm doing this for some API files I'm writing and I want the client to have direct access to these files (<script src="... .js">) and this forces me to hardcode info that might change in the future across multiple file references. What I'd like to do was something like this, is it possible? (the content to fetch must remain completely private - from the server folders to the php script files - and so it is really not an option to fetch this info using javascript):
api.js
<? //PHP here. (I know...)
(...)
?>
//some javascript
var is_secure = <? echo "true"/"false" ?>
(...)
So that when doing <script src="api.js"/> the user only fetches:
var is_secure = "true";
(...)
or
var is_secure = "false";
(...)
Any idea on how I could do something similar? Thank you very much...
You could just create your PHP file with this line before everything :
header("Content-Type: application/javascript");
EDIT:
I did misunderstood the question. If you want js in an php file, you should do it like this:
header("Content-Type: application/javascript");
OLD ANSWER:
I don't know if you know, but client can't see your php code...
So if You'd:
echo "Something"
The client would only see Something.
It's not clear, what you're trying to do...
If you don't want to see Something when you go directly into your "secret" php page, then you should do it like this:
JS:
jQuery.ajax({
type: "POST",
url: 'secretfile.php',
dataType: 'html',
data: {apiRequest: 1},
success: function (response) {
yourVar = response;
}
});
PHP:
If ($_POST['apiRequest']==1){
echo "Something";
}
yourVar would be = "Something"
If you'd go to this page, it wouldn't display anything;
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');
I'm using Joomla, and I intend to be checked in a database of Joomla user table is right there through a code in order to perform the registration.
Well, 3 days ago I'm trying to use an ajax function that invokes a php function.
What happens is that when I try to read the response from the server (php function) can only get HTML page. Not sure what is happening. I saw several articles and questions and still not know what's going on.
What I'm doing is when the writing is detected in a given field, performs the function to check if the code exists in the database
I am unsure if I am correctly access to my validatePartner.php
Here is my script:
<script language="javascript" type="text/javascript">
jQuery(document).ready(
function($){
$('#jform_username').bind('input', function() {
alert("FINE");
var data =" hello world";
var data2=" hello all";
$.ajax({
url: 'validatePartner.php',
data: {'q': data,'z':data2},
type: "POST",
success: function(data) {
alert("Here: " + data);
}
});
});
});
</script>
Here is my validatePartner.php:
<?php
function myfunction() {
$myvar = $_POST['q']." how are you?";
$myvar2 = $_POST['z'];
echo $myvar."\n".$myvar2;
}
myfunction();
?>
I have this teo files in the same directory.
Thanks for your help!
SOLUTION:
Using #jonasfh tips, I got what I need!
I created a component with two files that he tells me and in ajax function I used:
<script language="javascript" type="text/javascript">
. . .
$.ajax({
url: '?option=com_validatepartner&format=raw',
. . .
</script>
Instead:
<script language="javascript" type="text/javascript">
. . .
$.ajax({
url: '?option=com_validatepartner&tmpl=json',
. . .
</script>
Thanks for the help!
you should probably make a component to return your ajax call as outlined by #MrCode. The component can be super simple, but needs at least 2 files(possibly some more?): an xml definition file, and the entry point, like this:
/administrator/components/com_validatepartner/validatepartner.xml and
/components/com_validatepartner/validatepartner.php
Syntax and format of the xml-file is described here. The file validatepartner.php can be as simple as:
defined('_JEXEC') or die;
#get a database object
$db=JFactory::getDbo();
$db->setQuery('select * from #__thetable');
$list=$db->loadAssocList();
# you probably want to return some json-data or something:
echo json_encode($list);
Now one more trick: In your template folder add the following file:
json.php
containing:
defined('_JEXEC') or die;
<jdoc:include type="component" />
Now you can test your component by going to:
index.php?option=com_validatepartner #result inside the normal tmpl-file
and
index.php?option=com_validatepartner&tmpl=json # to use your json.php tmpl-file
Finally call the file similar to what #MrCode suggested, with small changes
$.ajax({
url: 'index.php?option=com_validatepartner&tmpl=json',
data: {'q': data,'z':data2},
type: "POST",
success: function(data) {
alert("Here: " + data);
}
});
Also remember to register the component in the joomla backend, by going to extensions->extension-manager and then Discovery.
regards Jonas
Edit: Changed layout to tmpl in the above code and examples. Also changed some of the file layout etc.
Your request to validatePartner.php is probably being rewritten to the Joomla! index.php. In any case, you should create a native Joomla! component that can be called via the Joomla! index.php, instead of creating a separate script file. Your separate PHP script won't have access to the Joomla! database or session etc.
It would then be called like:
$.ajax({
url: 'index.php?option=com_myComponent&task=validatePartner',
data: {'q': data,'z':data2},
type: "POST",
success: function(data) {
alert("Here: " + data);
}
});
Developing a Basic Joomla! Component
I had the same problem. I was working on dependent drop down lists using jQuery in joomla component. The second drop down list as result of call display empty and loads with html page. At last I found the solution: the requisite file should be placed outside the components directory. As a result, we won't be able to get the entire html page, but at that page we have to include libraries externally.
Here are the libraries:
define( '_JEXEC', 1 );
define('JPATH_BASE', dirname(__FILE__));
define( 'DS', DIRECTORY_SEPARATOR );
require_once ( JPATH_BASE .DS.'includes'.DS.'defines.php' );
require_once ( JPATH_BASE .DS.'includes'.DS.'framework.php' );
$mainframe =& JFactory::getApplication('site');
$mainframe->initialise();