I want to get some keyword by a textarea by using this js code. Obviously, I need PHP code too, but I have a problem with the string - var ehy = "php echo $dunno". Why this? Can anyone help me?
<?php
if (isset($_POST['line'])) {
$line = $_POST['line'];
$dunno = (explode(" ", $line));
}
?>
<script>
function countLines(){
var stringLength = document.getElementById("myText").value.length;
var count = Math.ceil( stringLength / document.getElementById("myText").cols );
// just devide the absolute string length by the amount of horizontal place and ceil it
return count;
}
function what(){
var n = countLines()
var tarea = document.getElementById('myText')
var lines = tarea.value.split("\n")
//for(var x = 0; x < lines.length; x++) {
$.ajax({
type: "POST",
url: "",
data: "line="+lines,
success: function(){
var ehy = "<?php echo $dunno; ?>"
$('#what').text(ehy)
},
});
//}
}
</script>
</head>
<body>
<h1>SearchFunction()</h1>
<textarea rows="10" cols="70" id="myText"><?php echo "what the hell?";?></textarea>
<input type="button" onclick="what()"/>
<p id="try"></p>
<p id="what"></p>
</body>
</html>
What you have there is some HTML-like page with little bits of PHP in it.
<html>
<?php echo 'hi' ?>
</html>
On your server, the php gets processed and all the tags get replaced:
<html>
hi
</html>
In your particular situation, the place where you echo $dunno is in the middle of some embedded javascript.
All of this happens on the server. The client (browser) did nothing so far.
Now that the page is ready, it gets to the browser which interprets it. The browser doesn't get the bits because they have already been interpreted. The browser simply gets a HTML with some JS:
var ehy = 5
At an even later point, when the what function is executed, it will trigger an ajax request that on success sets the text of #what to the value determined a long time ago by the PHP interpreter.
I hope that answers your question.
Related
I am working on a webpage that takes HTML form input, processes it on a loop using PHP, then displays the PHP echo output in a div using jQuery, then TTS speaks a message using ResponsiveVoiceJS.
The problem that is visible right now is that, upon loading of the page, the TTS starts speaking the webpage file name and some random PHP on a loop, then displays the form twice.
It shouldn't do any of that!
Since I am not sure which part of the code is causing the issue, here is the code in its entirety:
<html>
<head>
</head>
<body>
<form action="<?php
echo $_SERVER['PHP_SELF'];
?>" method="post">
What is your URL? <input type="text" name="pastedurl"><br>
What is your minimum interval? <input type="text" name="interval"><br>
<input type ="submit">
</form>
<?php
set_time_limit(18000);
if (isset($_POST['submit']))
{
// echo "stopped here";
// die; //THIS DOESN'T WORK EITHER
$pastedlink = $_POST['pastedurl'];
$pastedlink2 = $_POST['pastedurl'];
$rate = $_POST['interval'];
parse_url($_POST['pastedurl'], PHP_URL_HOST);
if (parse_url($_POST['pastedurl'], PHP_URL_HOST) == 'www.instructables.com')
{
for ($z = 0; $z < 2880; $z++)
{
$tutorial_json = file_get_contents($pastedlink);
$tutorial_array = json_decode($tutorial_json, true);
$oldviews = $tutorial_array['views'];
sleep(30);
$tutorial_json2 = file_get_contents($pastedlink);
$tutorial_array2 = json_decode($tutorial_json2, true);
$currentviews = $tutorial_array2['views'];
$viewcount1 = (int) $oldviews;
$viewcount2 = (int) $currentviews;
$change = $viewcount2;
$change -= $viewcount1;
$rateasint = (int) $rate;
if ($change >= $rateasint)
{
$sayit = "Alert! Your Tutorial has gained " . $change . " more views";
echo $sayit;
}
}
}
else
{
exit("Error: URL submitted was not from www.instructables.com");
}
}
?>
<script src="http://code.responsivevoice.org/responsivevoice.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js"></script>
<script>
$(document).ready(function(readyEvent) {
speakInnerHTML();
});
function speakInnerHTML() {
var speek = document.getElementById("load_updates");
responsiveVoice.speak(speek.innerHTML);
}
</script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load_updates').load('<?php
echo $_SERVER['PHP_SELF'];
?>',speakInnerHTML).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
<div id="load_updates"> </div>
</body>
</html>
Sorry about the poor formatting, I am a noob and don't know the methods of formatting these programming languages!
Here is a video of the error in action:
youtube
1.
die; //THIS DOESN'T WORK EITHER
die() is a function, and despite the wonders of echo, all functions are called with parentheses.
2.
isset($_POST['submit'])
This doesn't work because there are variables with the name submit.
To fix that, add the name attribute to your submit control, like this:
<input type="submit" name="submit">
3. You are loading the page itself with jQuery, even though it contains... well... itself. It's going to recursively fill the page with its own instances every 10000ms. And every one of that instance is going to do that too. You need to query the page with the data from the form, not just load it. And add a conditional so that if there is $_POST data, the page does not display all the HTML.
HTML:
<section class="clientbox">
<div class="container">
<div class="col-lg-10 col-lg-offset-1">
<h2>WHAT CLIENT SAYS</h2>
<h4>POSITIVE REVIEWS FOR LOVING PROBLAM.COM </h4>
<p id="testimonial"><?php echo $alldata[0]['text'] ?></p>
</div>
</div>
</section>
javascript:
<script type="text/javascript">
<?php $i = 1; ?>
setInterval(function()
{
document.getElementById('testimonial').innerHTML = "<?php echo $alldata[$i]['text'] ?>";
<?php $i++; ?>
}, 3000);
What actually I am trying to do is change the text of 'testimonial' from values stored in $alldata array every 3 secs.
The problem is that the php variable $i is not getting updated. It stays 1 only.
You mixed the server side logic (PHP) with the client side logic (JavaScript).
When the client request your web page, PHP render the contents which contains HTML, CSS, JavaScript and some other contents and the web server send these contents to the client side.
The web browser receives these contents and then execute the JavaScript and render the HTML according to the styles.
You need to generate all the contents needed by the JavaScript setInterval on the server side, and adjust your JavaScript logic to iterate on these data.
The logic may looks like the following. I'm not familiar with PHP, not sure if this is valid. The JavaScript doesn't check if all data has been consumed.
<script type="text/javascript">
<?php
function get_data($e) {
return($e['text']);
}
$data = array_map("get_data", $alldata);
?>
var js_alldata = <?php echo json_encode($data) ?>;
var i = 1;
setInterval(function()
{
document.getElementById('testimonial').innerHTML = js_alldata[i % js_alldata.length];
i++;
}, 3000);
You can't mix PHP and Javascript like that. PHP runs first, producing some data for Javascript to interpret. From Javascript's perspective, it can only see this:
<script type="text/javascript">
setInterval(function()
{
document.getElementById('testimonial').innerHTML = "some data";
}, 3000);
</script>
You would need to pass all of the data to Javascript so it can iterate over it.
See this answer for how to mix PHP and Javascript.
I've made this code and it is working. As people above told you, server side cannot work with the client-side iterations or setIntervals, therefore you should send the whole data beforehand.
Example:
$array = array();
$array[0]['text'] = 'hi';
$array[1]['text'] = 'hey';
$array[2]['text'] = 'hou';
$js_array = json_encode($array);
?>
<p id="testimonial"><?php echo $array[0]['text'] ?></p>
<script>
var json;
var i=1;
json = <?php echo $js_array; ?>
setInterval(function()
{
document.getElementById('testimonial').innerHTML = json[i]['text'];
i++;
}, 3000);
console.log(json);
</script>
I'm having a little trouble with Javascript/php/html. I have written this code below to display "GetM" if the time is > 480 seconds this seems to work great when there is just one instance of this. However, I have 14 blocks and any other blocks do not show their GetM values. Below is an image of what U mean by "blocks". The value for GetM on the first block is the percentage
<div id ="ZL01001Percent" class="BottomboxPercent">
<script type="text/javascript">
var time = <?php echo $machine1->data(); ?>;
var M = <?php echo $machine1->GetM(); ?>;
var P = M.toFixed(1);
if (time > 480) {
document.write(P * 100 + '%');
}
</script>
</div>
Any help would be much appreciated
I strongly recommend you create a JS Object representation of your data. If you create a PHP array, you can use json_encode to generate
var machines = <?PHP echo json_encode($myValues); ?>
which should result in
var machines = {
ZL01001: { time:500, M : 733},
ZL01002: { time:600, M : 556}
}
and then you can do
window.onload=function() {
for (var m in machines) {
var machine = machines[m];
document.getElementById(m+"Percent").innerHTML=machine.time>480?(machine.M.toFixed(1)*100)+"%":"";
}
}
I'm not sure if it's just me or what but this seems really odd. When I click a button I have jquery send out javascript variables to a php site to be handled there. However on the php site they come up as undefined indexes. The weird part, is that they show on the html page through php's echo. NOTE: The html button is an input type="button", not a submit because I don't want to reload the page.
jquery:
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
php:
//used for troubleshooting, returns Array() on the php page and Array ( [posttimestampst] => 1399973296 [postobjNamest] => test2-1
print_r($_POST);
//when the if and else are used it the php page always echos Not Working, meaning that the $_POST is not set somehow. However, the html page shows the echoed variables in the "divResult" as it should.
//when I try the code without the if and else, the php page returns Undefined Index: posttimstamp/postobjNamest. However, the html page still shows the echoed variables.
if(isset($_POST["posttimestampst"])){
$timestamp = $_POST["posttimestampst"];
echo $timestamp;
echo "<br>";
$objName = $_POST["postobjNamest"];
echo $objName;
echo "<br>";
}
else{
echo "Not Working";
}
Any help is greatly appreciated!
EDIT:
//gets selected object from a dropdown menu
selectedObj = document.getElementById("selectObj").value;
//objName in javascript taken from $objName var in php that is and the beginning of the html page.
objName = <?php echo json_encode($objName); ?>;
//objInst takes the value of the dropdown menu and assigns it as the [] in objName array
objInst = objName[selectedObj];
//timestamp is set in php and imported to java
var timestamp = <?php echo $timestamp; ?>;
EDIT 2:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js""> </script>
</head>
<h3>Optionen und Berechnen</h3>
<form name="myForm" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<div id="divCalc">
</div>
<input id="addObject" type="button" onclick="addObj()" value="Add Object">
<br>
<br>
<div id="divAddObj" hidden="true">
</div>
<br>
<div id="divCalc">
</div>
<div id="divResult"></div>
</form>
<script type="text/javascript" name="addObject">
var objName;
var selectedObj;
var objInst;
var timestamp = <?php echo $timestamp; ?>;
//Start select dropdown
var select_element = document.createElement("select");
select_element.setAttribute("id", "selectObj");
select_element.setAttribute("name", "selectObject");
options = new Array();
objName = <?php echo json_encode($objName); ?>;
for ( var i = 0; i < (<?php echo $arrayNum; ?>); i++ ){
options.push(new Option(objName[i], i, false, false));
}
options[0].selected = true;
for ( var option in options ){
select_element.appendChild(options[option]);
}
//End select dropdown
//check selected object
selectedObj = document.getElementById("selectObj").value;
objInst = objName[selectedObj];
var timestampst = $(timestamp).val();
var objNamest = $(objInst).val();
$.post("sendCalc.php", {
postobjNamest:objInst,
posttimestampst:timestamp},
function(data){
$("#divResult").html(data);
});
</script>
Change your code to:
objNamest = objInst.value;
timestampst = timestamp.value;
$.post("sendCalc.php", {
postobjNamest: objNamest,
posttimestampst: timestampst },
function(data){
$("#divResult").html(data);
});
You are missing the data parameter of $.post().
From the docs about post():
data
Type: PlainObject or String:
A plain object or string that is sent
to the server with the request.
Your params postobjNamest & posttimestampst do not exist for the $.post() method
It should be
$.post("sendCalc.php", {
// An "on-the-fly" created JavaScript object, which is valid
data: {
postobjNamest: objInst,
posttimestampst: timestamp
},
function(data){
var content = $.parseJSON(data);
window.console.log(content.postobjNamest);
window.console.log(content.posttimestampst);
}
});
From the docs about parseJSON():
Description: Takes a well-formed JSON string and returns the resulting
JavaScript object.
And in the PHP:
$objName = $_POST['postobjNamest'];
$timestamp = $_POST['posttimestampst'];
// Returning your values to client
// Don't echo them in PHP
echo json_encode(array(
'postobjNamest' => $objName,
'posttimestampst' => $timestamp
);
From the docs about json_encode():
json_encode — Returns the JSON representation of a value
The Javascript Object:
// Declaration
var Obj = {
propertyOne: 'value', // string
propertyTwo: 52.3654, // float
methodOne: function () {
// your function code
},
methodTwo: function () {
// your function code
}
}
//Instances
var objOne = new Obj();
objOne.methodOne();
objOne.propertyTwo;
var objTwo = new Obj();
objTwo.methodOne();
objTwo.propertyTwo;
I am looking to create a basic graphic calculator using only html, php, and javascript. The code below refreshes the page so the javascript never gets a chance to draw the graph. The way this is supposed to work is that the php grabs the data from the form and outputs the results of the equation point by point into an array. The array is passed to the javascript which uses the index of the array for the x value and the value at that index for the y value. I tried having the form target a separate iframe but the graph still isn't drawing and I am not sure why. I heard there is a way to do this with AJAX but the current challenge is to do this with just html,css if needed, javascript, and php.
<?php
if( isset($_POST['submit']) )
{
$val1 = htmlentities($_POST['val1']);
$val2 = htmlentities($_POST['val2']);
$val3 = htmlentities($_POST['val3']);
$results;
for($i = 0; $i < 530; $i++)
{
$results[i] = pow($i,$val1) + $i*$val2 + $val3;
if($results[i] >= 530)
break;
}
}
?>
<form action="example4.php" method="POST">
x^:
<input type="text" name="val1" id="val1"></input>
+x*:
<input type="text" name="val2" id="val2"></input>
+1*:
<input type="text" name="val3" id="val3"></input>
<input type="submit" value="send"></input>
</form>
<canvas id="c" height="530" width="530" style="border:1px solid #d3d3d3;"></canvas>
<script type="text/javascript">
var b = document.body;
var c = document.getElementsByTagName('canvas')[0];
var a = c.getContext('2d');
var data = <?php echo json_encode($results); ?>;
a.beginPath();
a.moveTo(0,530);
a.strokeStyle="black";
for(var i=0; i < data.length-1; i++))
{
a.moveTo(i,data[i]);
a.lineTo(i+1,data[i+1]);
a.stroke();
}
</script>
I think the problem is you are setting data equal to the JSON string not to an array object.
Can you change the line that reads:
var data = <?php echo json_encode($results); ?>;
To the following:
var data = JSON.parse("<?php echo json_encode($results); ?>");
EDIT: I reread your question and see you want the php variables at the top of the page to be set by the user through the form on the page. The problem with how you are surrently thinking about it is that PHP is run on the server and HTML/Javascript is rendered and run on the user's browser. So all of the php has already executed before the user sees the form.
You can run php from an HTML page though by using AJAX. So you will AJAXing to a php file that performs the computations and builds the array and ultimately echo's the JSON of the array. The JavaScript will then handle the result like I talked about in my original answer above.
For an AJAX tutorial that deals with the components you will need: http://www.simpletutorials.com/?path=tutorials/javascript/simple_ajax