How to pass a value from JavaScript in php? - javascript

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;

Related

How do I transfer the PHP variables to another javascript file?

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)); ?>");

Wordpress get post id with a php file

I have been stuck on this for weeks. I have an HTML slide presentation using Reveal.js. I want to run a php script on the very last slide.
This is an HTML button on the last slide within a Wordpress post:
<button onclick="myFunction()">Open php file</button>
<script>
function myFunction() {
window.open("../../testing/test.php", "_self");
}
</script>
This is the code inside the test.php file that I am trying to run but it returns null:
define('WP_USE_THEMES', false);
require_once('../wp-load.php');
echo "Post ID: ".get_the_ID(); // Returns nulls but I want this to return 86.
The post id is 86. I can hard code it into the html (if I have to) but I don't want to hard code it into the php file. Also, I would prefer not to use jquery. How can I get the post id into the php file? Thanks.
Have you tried using global $post variable??
global $post;
And after that, you can get the id,
echo "Post ID: ".$post->
Another approach is using $wpdb global variable to make database queries.
You can also use JavaScript to send your post id to another php file using javaScript forms, Ajax or jQuery. jQuery Post.
Maybe the most easiest approach for you is something like this
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
On your myphpfile.php you can use $_GET['name'] after your javascript was executed.

Adding a parameter to the url in a Yii AJAX call

I have a CHTML:ajax function that does some AJAX stuff on a select dropdown - I simply want to do something which says..
"on change, grab the selected value & pass that as param childID in the URL"
This should then display the following in the url section of the
CHTML::ajax function:-
'url' => 'isAjax=1&childID=5134156'
I've tried to append the variable selected onto the url but it doesn't work - can anyone see what I'm doing wrong
jQuery(function($) {
$('#child-form select[name="Child[user_id]"]').bind('change', function(e){
var selected = this.value;
console.log('selected : '+selected ); // outputs an ID to the console.
<?php echo CHtml::ajax(array(
'url' => '?isAjax=1&childID='+selected,
'type' => 'post',
'update' => '#parents-sidebar',
// rest of the ajax function (quite long...)
You can't take a value extracted from the dom using javascript and inject it directly into PHP code.
From the PHP.net documentation:
Since Javascript is (usually) a client-side technology, and PHP is
(usually) a server-side technology, and since HTTP is a "stateless"
protocol, the two languages cannot directly share variables.
CHtml::ajax() is primarily a shortcut for generating javascript code. So the easy solution would just be to write your javascript manually. That will allow you to use your selected variable.
Note:
You might try Taron Saribekyan's solution, posted in the comments. The idea is that the javascript expression ('...+selected') will be printed by PHP as a string, and thus be evaluated by javascript. In theory, this should work.
That is obvious. You have defined a javascript variable and you are using it in your php code! Everything inside <?php ?> block, will interpret on the server and before javascript. So, I think you should use normal jquery ajax method in your case. Something like this:
$.ajax({
"url": <?php echo Yii::app()->baseUrl.'/controller/action' ?>'?isAjax=1&childID='+selected,
'type' => 'post',
...
})

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'];
}

Ajax after success, how to pass data to a variable to php

I have script like this
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
I don't know how I can pass data response to php code ?
For Example: if I alert response, it's show 123 .so I want pass value 123 to a variable in php
$id = 123
response is the result passed BY php, not TO php. What's passed to php is the id and the task.
In your tab.php, you can access these two values :
<?php
$id = $_POST['id'];
$task = $_POST['task'];
//do anything you want with it...
?>
This is not the right workflow. PHP executes on runtime, so every time the page has finished loading you can't really put variables back into PHP (unless you reload the page). This is where AJAX comes in, so you can call PHP scripts from JavaScript / jQuery and don't have to reload the page every time.
The right thing to do is to either store the variable you have generated in the tab.php script in a database, $_SESSION, $_COOKIE or something similar like so:
//put this at the top of all your php scripts you want to use the variable in
session_start();
//now store the variable you wanted to pass (in tab.php)
$_SESSION['returnValue'] = $myValue;
Now if you want to use the variable in other pages just echo it like so (remember to add session_start() at the top of the PHP script.
echo $_SESSION['returnValue'];
First of all, start by reading this
To answer your question,
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
The result from id and task are sent via $_POST (type:"POST") to the page tab.php (url:"./tab.php"). If you want to do that on a different page, just change the url in your ajax call: url:"./any_other_page.php" and the posted values will be sent there
Finally, read THIS post as well. It is greatly written and very well explained.
Hope it helps!
Keep on coding!
Ares.

Categories

Resources