Echo php content into API javascript? - javascript

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;

Related

Using data from a PHP array in AJAX

I'm making a change to the way a site works and trying to find a solution that requires as little re-writing as possible.
At the moment, I have a file (myFile.php) which loads (using Wordpress) into a page. It uses a PHP array for outputting data. The PHP array is $property_list_featured_search and the content looks something like this:
<?php
foreach($property_list_featured_search as $individual_property){
?>
<span><?php echo $individual_property['info']['status'] ?></span>
<?php
}
?>
So in my small example, it's outputting data from $property_list_featured_search and this works OK.
My problem is that I now want to load the HTML&PHP above using jQuery AJAX. When a user clicks a button, it loads the HTML (which is stored in a file, called myFile.php into a div on the page:
function loadView(view){
$.ajax({
type: "POST",
url: 'path/to/file/property-search/myFile.php',
data: property_data,
success: function(result)
{
$("#search-page-content").html(result);
});
}
In the case above, property_data is the $property_list_featured_search data localized using Wordpress so that the file can access it. I have tested it and can confirm that the file loaded in with AJAX is able to see the data. My problem is that I now have a file with PHP echo everywhere and the data in JSON format.
Is it possible to still use this data in this way? I'm guessing because the data is JSON that it's not possible to use echo $data[key] at all like it was in the original file?
What's the best way to output all the data in the JSON file on the page?
You can try something like this:
When u get your data:
$checked = $_POST['property_data'];
$checked = array('first' => $checked[0], 'second' => $checked[1], 'third' => $checked[2], 'forth' => $checked[3]);
Then you can echo it like this:
$checked['first'], $checked['second'] and so on.
Hope this helps

Use Javascript to Fetch a Variable from a Separate PHP File

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.

Inserting Javascript variable into PHP

I want to paste two variables from javascript to PHP so I tried
$.post("index.php", {myQuery: myFinalSQL, action: "show_all_stories_sorting"});
where myFinalSQL is a string in javascript
In index.php, I try to printout the myFinalSQL with
echo $_POST['myQuery'];
But it didn't work. Would you please tell me how to insert javascript variables to PHP?
You using wrong approach.
It is bad way to interract with server by such method (inserting php variable in <? ?> tags into script tag).
You should use this:
$.post("ajax.php/myGlobalAction", params, callback);
In callback you will do with your data all what you need.
Example:
var params = {
id: 5
};
$.post( "ajax.php?action=getSqlQueryForSomething", params , function( data ) {
$( ".sqlQuery" ).html( data.sqlQuery );
});
So you have complex architecture problem if you need to work with php and js like this. Change your architecture before it's too late.
If you want to add value from PHP to Javascript you can use :
<script>
var myQuery = "<?php echo $myQuery; ?>;
</script>
But, if you want to add value from Javascript to PHP, you'r not allowed because PHP is server based and javascript is text based.
If you used $.post() :
$.post("index.php", {myQuery: myFinalSQL}, *your_javascript_action* );
in your index.php, you can use this :
if(isset($_POST['myQuery'])){ // checking method
echo $_POST['myQuery'];
}

How to pass a value from JavaScript in php?

Translate translator from Google. So that did not swear if something is not clear. Itself from Russia.
The question arose. How to pass the value of the alert in the javascript in the variable $ value in php, and write it in the case file. And another question: how to hide the alert? or use instead to visually it was not visible, but the value was passed?
//a lot of code
{
console.log(data);
alert(data['value']);
}
});
So. Also there is a PHP script that writes logs (current page and the previous one) to a file. According to this principle here:
//a lot of code
$home = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$referer = $_SERVER['HTTP_REFERER'];
$value = how the value of the java script to convey here?;
$lines = file($file);
while(count($lines) > $sum) array_shift($lines);
$lines[] = $home."|".$referer."|".$value."|\r\n";
file_put_contents($file, $lines);
It is necessary that the value of js is transferred to the php-script and write to the file. How to do it? Prompt please. I am a novice in all of this.
PHP scripts run before your javascript, which means that you can pass your php variables into javascript, but not the other way around. However, you can make an AJAX POST request from JavaScript to your PHP script, and grab the POST data in PHP through the global $_POST variable.
Assuming you use jQuery, your JavaScript would look something like:
// assign data object:
var data = { value: "test" };
// send it to your PHP script via AJAX POST request:
$.ajax({
type: "POST",
url: "http://your-site-url/script.php",
data: data
});
and your PHP script would look like:
// if the value was received, assign it:
if(isset($_POST['value']))
$value = $_POST['value'];
else
// do something else;

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');

Categories

Resources