Adding a parameter to the url in a Yii AJAX call - javascript

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',
...
})

Related

How to display a global javascript variable in typo3 using typoscript?

I would like to output a global variable "elemenId" that is created by a javascript in typo3.
The javascript writes the ID of the touched html element in the global variable elementId:
document.addEventListener("touchstart", (e) => {
// get elementId of touched element and save as global variable elementId for further processing
window.elementId = e.target.id;
});
I would like to display the elementId value in typo3.
Is there any chance to access this variable in typo3 using typoscript? Something like:
lib.global_variable = COA_INT
lib.global_variable {
20 = TEXT
20.data = GP : elementId
}
Is there any other way to achieve that?
Thanks a lot for your help!
What do you mean with global variable elementId?
global in what context? PHP? javascript? TYPO3?
You need to distinguish between server(webserver with PHP/TYPO3) and client(Browser with javascript).
How can data be exchanged?
Anything in PHP can be written in the rendering process. The output is HTML, including CSS and javascript. Alternatively TYPO3/PHP can generate other formats like JSON, XML, PDF or CSV.
In this way PHP can transfer some information to Javascript by generating a piece of javascript which assigns the value to a (global) javascript variable:
$output = '<script>js_var = "' . $php_var . '";</script>';
echo $output;
Now the client/browser can use the value by executing this javascript code.
On the other hand any value from your client/browser can only be transferred to the server/PHP by doing a new server request. This can be done with a new page request with arguments (either POST or GET) and the server can respond with a appropriate reaction.
Or you do an AJAX call and you will get a appropriate response and some javascript can insert the response in the current document.
Another option would be that javascript only acts locally in the browser and used the information available to generate or modify the current HTML-document. that might be showing the ID of any clicked HTML element in a special HTML object.

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.

A method to pass a variable to Javascript currently run in the header

Please excuse me ignorance, I'm completely new to Javascript.
I have this code that is currently run in the header, however I need to pass it $_GET variables before it runs.
jQuery(document).ready(function() {
refresh();
jQuery('#bittrex-price').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc');
jQuery('#mintpal-price').load('http://<site>/realtime/mintpal-realtime.php?symbol=ltc');
});
function refresh() {
setTimeout( function() {
jQuery('#bittrex-price').fadeOut('slow').load('http://<site>/realtime/bittrex-realtime.php?symbol=ltc').fadeIn('slow');
jQuery('#mintpal-price').fadeOut('slow').load('http://<site>/realtime/mintpal-realtime.php?symbol?ltc').fadeIn('slow');
refresh();
}, 10000);
}
It's pretty simple, all it does is pull the latest price from another PHP script.
I need to append a $_GET variable to the URL as current I have no way to change the ?symbol=ltc depending on which page the user is visiting. Because Wordpress is being awkward, I've had to save this function in a .js file and add a hook in functions.php otherwise it won't load at all. Ideally, I'd like to be able to run the function in the body so I can modify, but I can't get that to work either :/
I hope this makes sense, I'm open to any suggestions as I'm clearly missing the point somewhere here.
Thanks
You need to use the language that is building the web page to output some javascript for use in your functions.
Thus, if you're using PHP to build your page you could do something like this in the <head> section of your page:
<?php
print '<script>';
print 'var symbol = ' . $_GET['your_get_variable'] . ';';
print '</script>';
?>
Then, in your later javascript code you have your GET variable string stored in 'symbol' and can use it however you like.
The 'your_get_variable' is what is coming in via the query string in the URL that got you to the current page. Just make sure you put this code above where you want to use 'symbol' in your later javascript.
Also, It's not really a good idea to use $_GET data directly like that without some validation, but I'm just keeping the example clean.

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;

Post hidden field containing javascript variable or function?

I feel like I must be missing something, or I'm just too clueless to search for the right question, so please pardon me (and redirect) if this is a duplicate. My issue is probably much harder than I think it should be.
I have a page with a rather lengthy block of php code (mainly MySQL queries) which generate variables that are eventually passed into JavaScript as strings. The data is then used to create some interactive form elements. The end result is a textarea field which contains a JS string which I'd like to carry into to a new page. I will also be POSTing php variables to that new page.
Sample code:
<?php //Get data from MySQL, define variables, etc.?>
<script> //Move php strings into JavaScript Strings;
//put JS vars into textareas; etc
var foo = document.getElementById('bar').value </script>
<form action="newpage.php" method="post">
<input type="hidden" id="id" name = "name" value="**JAVASCRIPT foo INFO HERE**"/>
<input type = "hidden" id="id2" name = "name2" value = "<?php echo $foo; ?>" />
<input type="submit" name="Submit" value="Submit!" />
Calling JS functions in the right order is a little sticky because they depend on php variables which aren't defined until queries are complete, so I can't do much with an onload function. I'm literate in php. I'm a novice in JavaScript. I'm fairly inept with JQuery and I've never used AJAX. I'd also really rather not use cookies.
It would be great to see an example of what the original and new page code might look like. I know I can receive the php on the new page info via
$foo = $_POST['name2'];
beyond that, I'm lost. Security isn't really a concern, as the form captures information which is in no way sensitive. Help?
If you don't need to use the failure function, you can skip the AJAX method (which is a bit heavier), so I would recommend you make use of the $.post or $.get syntax of jQuery.
Pre-defined syntax: jQuery.post( url [, data ] [, success ] [, dataType ] )
Here is the example for jQuery:
$.post('../controllerMethod', { field1: $("#id").val(), field2 : $("#id2").val()},
function(returnedData){
console.log(returnedData);
});
Otherwise, you could use the AJAX method:
function yourJavaScriptFunction() {
$.ajax({
url: "../controllerMethod", //URL to controller method you are calling.
type: "POST", //Specify if this is a POST or GET method.
dataType: "html",
data: { //Data goes here, make sure the names on the left match the names of the parameters of your method you are calling.
'field1': $("#id").val(), //Use jQuery to get value of 'name', like this.
'field2': $("#id2").val() //Use jQuery to get value of 'name2', like this.
},
success: function (result) {
//Do something here when it succeeds, and there was no redirect.
}
});
}
function init()
{
var str1 = <?php echo varname; ?> //to access the php variable use this code//
document.getElementById('id').value= str1;
}
<body onload="init()">//make sure you call the function init()`
did you try something like this

Categories

Resources