Data from PHP-include not shown in parent when using variable variable - php

I experience the following problem. By clicking the button in start.php the file fakten02.php is called with the parameter DE2 . This parameter is used as a variable variable to convert the array $DE2 into a string and display it in start.php. Unfortunately, this does not happen. If fakten02.php is directly called with the parameter, it works. If the parameter is hard-coded in fakten02.php the content of $land is shown in start.php. However, if $land is filled from $text2, $land is empty in start.php.
start.php
<!DOCTYPE HTML>
<html>
<head>
<title>Start</title>
</head>
<body>
<div id="spalten">
<button type="submit" id="land1">Klicken</button>
</div>
<?php
include("fakten02.php");
print_r($land);
?>
</body>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#spalten > button").click(function() {
$.get("fakten02.php", {sland:'DE2'});
<?php echo $land; ?>;
})
})
</script>
</html>
fakten02.php
<?php
$parameter = $_GET['sland'];
//$parameter=$_REQUEST['sland'];
//print_r($_REQUEST);
$DE2 = array("ich", "bin", "groß");
//echo "Text $text";
//$text2 = "$".$parameter;
$param2 = $parameter;
$text2 =$$param2;
for ($i=0; $i < count($text2); $i++) {
$land.="$text2[$i] "; //Does not work
$land.= "daten[$i] = '$DE2[$i]';"; //Returns expected data
}
//print( "aus 2 $land, $param2");
?>
I don't understand this behaviour. I did a lot of searching here and on Google, but I could not find a similar problem. How can I resolve this issue?

Related

php/ajax vote up down

and sry in advance because i'm new here and i'm completly new in php/ajax coding.
I use a free script (Ajax vote up/down) from this site
I have a simple php page for my shoutcast server to show the song played
<?php
require_once "inc.php";
$array = array(); // Let's store our shoutcast variables into an array.
$array['host'] = "xxx.xxx.xx.xxx"; // Your Shoutcast Host
$array['port'] = "xxxx"; // Your Shoutcast Port
$array['extra'] = "/admin.cgi?sid=1&mode=viewxml&page=1"; // The bit that follows in the url to access the xml of the stats
$array['user'] = "xxxxx"; // Admin username (Default is usually "admin")
$array['password'] = "xxxxxxx"; // Admin Password
$radioStats = new radioStats( $array['host'], $array['port'], $array['extra'], $array['user'], $array['password']);
$returnStats = $radioStats->returnStats();
$song = $returnStats['currentSong'];
?>
<div align="center">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<link href="votingfiles/voting.css" rel="stylesheet" type="text/css" />
<script src="votingfiles/voting.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
setInterval(function(){cache_clear()},54000);
});
function cache_clear()
{
window.location.reload(true);
}
</script>
<div id="radio_stats">
<?php
if( $returnStats['serverStatus'] != 0 ) {
?>
<?php
if( $returnStats['currentSong'] != "" ) {
echo $returnStats['currentSong'];
} else {
echo "Undefined";
}
?></div>
<br /><br />
<div class="vot_updown1" id="vt_$song"></div>
<?php
}
else {
?>
This radio server appears to be offline.
<?php
}
?>
My problem is :
All request Php/ajax/mysql works but actually when i make a vote, it's registered in the db like :
vt_$song 1 0
How can i do to get the real name of the song like the original php request do :
echo $returnStats['currentSong']; or echo $song;
To register in the db like :
vt_Kidd Guti-Step Everything 1 0 (or any other song played)
Example : [HERE]
Thanks in advance for any help.
In this line the $song is not parsed as PHP so the literal text $song is showing:
<div class="vot_updown1" id="vt_$song"></div>
Try:
<div class="vot_updown1" id="vt_<?php echo $song; ?>"></div>

reading Json from PHP with javaScript

My PHP code is:
<?php
class Sample{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) ){
echo "Starting to read ";
$req = $_GET[ 'request' ];
$result = json_decode($req);
if( $result->request == "Sample" ){
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}else{
echo "Not Supported";
}
}
?>
Is there anything wrong
I want to send a JSON to this php and read the JSON that it returns using java script , I can't figure out how to use JavaScript in this , because php creates an html file how Can I use $_getJson and functions like that to make this happen ?!
I tried using
$.getJSON('server.php',request={'request': 'Sample'}) )
but php can't read this input or it's wrong somehow
thank you
try this out. It uses jQuery to load contents output from a server URL
<!DOCTYPE html>
<html>
<head>
<title>AJAX Load Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(event) {
$('#responce').load('php_code.php?request={"request":"Sample"}');
});
});
</script>
</head>
<body>
<p>Click on the button to load results from php_code.php:</p>
<div id="responce" style="background-color:yellow;padding:5px 15px">
Waiting...
</div>
<input type="button" id="button" value="Load Data" />
</body>
</html>
Code below is an amended version of your code. Store in a file called php_code.php, store in the same directory as the above and test away.
<?php
class Sample
{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) )
{
echo "Starting to read ";
$req = $_GET['request'];
$result = json_decode($req);
if( isset($result->request) && $result->request == "Sample" )
{
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}
else
{
echo "Not Supported";
}
}
Let me know how you get on
It would be as simple as:
$.getJSON('/path/to/php/server.php',
{request: JSON.stringify({request: 'Sample'})}).done(function (data) {
console.log(data);
});
You can either include this in <script> tags or in an included JavaScript file to use whenever you need it.
You're on the right path; PHP outputs a result and you use AJAX to get that result. When you view it in a browser, it'll naturally show you an HTML result due to your browser's interpretation of the JSON data.
To get that data into JavaScript, use jQuery.get():
$.get('output.html', function(data) {
var importedData = data;
console.log('Shiny daya: ' + importedData);
});

get content back to javascript from PHP file in JSON format

When sending the request from the jQuery Mobile script to the specified PHP file, nothing is returned, nothing is appended to the html file. Here's the URL of the page:
localhost/basket/newstext.html?url=http://www.basket-planet.com/ru/news/9235
newstext.html:
<head>
<script src="js/newstext.js"></script>
</head>
<body>
<div data-role="page" id="newstext">
<div data-role="content">
<div id="textcontent"></div>
</div>
</div>
</body>
newstext.js:
var serviceURL = "http://localhost/basket/services/";
$('#newstext').bind('pageshow', function(event) {
var url = getUrlVars()["url"];
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText);
});
function displayNewsText(data){
var newstext = data.item;
console.log(newstext);
$('#textcontent').text(newstext);
$('#textcontent').trigger('create');
}
function getUrlVars(){
//it displays in the alert perfectly, shortening the message here
}
getnewstext.php:
<?php
include_once ('simple_html_dom.php');
$url = $_GET['url'];
$html = file_get_html(''.$url.'');
$article = $html->find('div[class=newsItem]');
$a = str_get_html(implode("\n", (array)$article));
//parse the article
header("Content-type: application/json");
echo '{"item":'. json_encode($a) .'}';
?>
I think my problem is how I'm encoding the $a variable in the PHP script. The $a variable contains html tags of all kind...how can I append it in the html file?
Where you have this line:
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText);
Change it to be:
$.getJSON(serviceURL + 'getnewstext.php?url='+url, displayNewsText, function(response){
$('#elem').append(response);
});
Where #elem is the name of the element that you want to append the data, returned from the PHP file, to.

Make PHP Click Link On Same PAge Or Process A Form

Is there any php code i can use to click a link or process a form on the page the php is on?
Im building a redirect script and what i need to do is use php to move user to next page, its mandatory that php has to be used html doesnt work. In it i have a self submit forum but it doesnt work how i load the script. Is there a way i can use php code to submit it? or remove it and put a link there then use php to click that link?
This is the code below:
if ($_GET['ref_spoof'] != NULL)
{
$offer = urldecode($_GET['ref_spoof']);
$p1 = strpos ($offer, '?') + 1;
$url_par = substr ($offer , $p1);
$paryval = split ('&', $url_par);
$p = array();
foreach ($paryval as $value)
{
$p[] = split ('=',$value);
}
//header('Location: '.$offer.'') ;
print
'
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">$("#mylink").click()</script>
Index Page
<script type="text/javascript">$("#mylink").click()</script>
<script type="text/javascript">document.getElementById("myLink").click();</script>
<form action="'.$offer.'" method="get" id="myform">
';
foreach ($p as $value)
{
echo '<input type="hidden" name="'.$value[0].'" value="'.$value[1].'">';
}
echo '</form><script language="JavaScript"> document.getElementById(\'myform\').submit();</script></body></html>';
}
Looks like you're trying to make this too complicated.
You're loading a page that submits a form using GET.
Is there any reason you can't use
header("Location : ".$offer."?".http_build_query($p));
http_build_query being a function to generate an URL string from an array. Assuming $p is the array containing all form fieldnames+values.
example of http_build_query:
$data = array('foo'=>'bar',
'baz'=>'boom',
'cow'=>'milk',
'php'=>'hypertext processor');
echo http_build_query($data);
will result in:
foo=bar&baz=boom&cow=milk&php=hypertext+processor

Use php for Output Buffering and jQuery to send ob_get_contents

I am trying to capture the contents of my php page using output buffering:
<?php
function connect() {
$dbh = mysql_connect ("localhost", "user", "password") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db("PDS", $dbh);
return $dbh;
}
session_start();
if(isset($_SESSION['username'])){
if(isset($_POST['entryId'])){
//do something
$dbh = connect();
$ide = $_POST['entryId'];
$usertab = $_POST['usertable'];
$answertable = $usertab . "Answers";
$entrytable = $usertab . "Entries";
$query = mysql_query("SELECT e.date, q.questionNumber, q.question, q.sectionId, a.answer FROM $answertable a, Questions q, $entrytable e WHERE a.entryId = '$ide' AND a.questionId = q.questionId AND e.entryId = '$ide' ORDER BY q.questionNumber ASC;") or die("Error: " . mysql_error());
if($query){
//set variables
$sectionOne = array();
while($row=mysql_fetch_assoc($query)){
$date = $row['date'];
$sectionOne[] = $row;
}
}else{
//error - sql failed
}
}
?>
<?php
ob_start();
?>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src = "jQuery.js"></script>
<script>
$(document).ready(function(){
$("#export").click(function(e){
//post to html2pdfconverter.php
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
$("#nm").val("Entry Report.pdf");
$("form#sendanswers").submit();
});
});
</script>
<title>Personal Diary System - Entry Report - <?php echo($date); ?></title>
</head>
<body>
<h1>Entry Report - <?php echo($date); ?></h1>
<div id = "buttons">
<form id = "sendanswers" name = "sendanswers" action="html2pdfconverter.php" method="post">
<input type = "hidden" name = "link" id = "link" value = "">
<input type = "hidden" name = "nm" id = "nm" value = "">
<input type = "button" name = "export" id = "export" value = "Export As PDF"/>
</form>
</div>
<h3>Biological Information</h3>
<?php
echo('<p>');
$i = 0;
foreach($sectionOne as &$value){
if($i == 1 || $i == 3){
$image = "assets/urine".$i.".png";
echo("<br/>");
echo($value['question']." <br/> "."<img src = \"$image\"/>");
echo("<br/>");
}else{
echo($value['question'].' : '.$value['answer']);
}
echo("<br/>");
$i++;
}
echo('</p>');
?>
</body>
</html>
<?php
}
$contents = ob_get_contents(); //THIS WORKS
ob_end();
?>
I assign the contents of ob to $contents using ob_get_contents(); This works, and echoing $contents duplicates the html page.
However, in my jQuery, I am trying to assign this to a hidden text field ('link') using:
$("#link").val("<?php echo($contents); ?>");
This doesn't work however..And I have a feeling its because I am accessing $contents too eraly but not too sure...any ideas?
$("#link").val("<?php echo(ob_get_contents()); ?>"); //THIS DOESN'T WORK
at the point you do that ob_get_contents call, you've only output about 10 lines of javascript and html. PHP will NOT reach back in time and magically fill in the rest of the document where you do this ob_get_contents().
You're basically ripping the page out of the laser printer the moment the page starts emerging, while the printer is still printing the bottom half of the page.
I fail to see why you want to embed the contents of your page into an input field. If you want to somehow cache the page's content in an input field, you can just use JS to grab the .innerHTML of $('body').
Well, you have two problems.
The first is what you suspect. You can't access that stuff until later. The second problem which you may not realize is that you will have quoting issues in JavaScript even if you manage to find a way to reorder this and make it work. It's recursive, in a bad way.
What you should do instead is change your $('#export').click handler to do an Ajax call, render the HTML you need to appear in the link on the server in a separate PHP script (no output buffering necessary) and then have your code inject the result of that call into the page the way you're trying to do in your click handler now.

Categories