How to get <span id= var - javascript

I’m working at a web GUI for an audio mixer. Therefor I have lot of repetitive faders. All looking the same, just differing by ID. The ID is a three digit number. The first digit is provide by the main php page, the other are repetitive in each fader section. I’m trying to get the result back from the server and posting it into a span field. The problem is that the span id depends on the full id.
The span id should be “result111”.Not hardcoded as it is but dynamically generated by the provide id followed by the identifier 11.
GUI php
<script>
function transfer(value,id)
{
if (window.XMLHttpRequest)
{
// AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
xmlhttp=new XMLHttpRequest();
}
else
{
// AJAX mit IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result"+id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","backEnd.php?v="+value+"&id="+id,true);
xmlhttp.send();
return;
}
</script>
backEnd.php
<?php
$id = 10;
$value = 7;
$result = 6;
if ( isset($_GET['id']) )
{
$id = $_GET['id'];
}
if ( isset($_GET['v']) )
{
$value = $_GET['v'];
$result = $value;
}
echo ("$id + $result");
?>
GUI.php
<?php
$id = 1;
include 'fader.php';
?>
fader.php
<script>
var id = <?php echo "$id"; ?>;
function setName (id2){
var fullId =""+ id + id2;
return fullId;
}
function setNameReturn (id2){
var fullIdReturn =""+ id + id2;
return fullIdReturn;
}
</script>
<form oninput="transfer(auswertung.value,setName(11))">
<input type="range" name="auswertung" min="0" max= "63" value="30" orient="vertical">
<br>
<span id="setNameReturn (11)">n.a.</Span>
</form>

You passing value to your function in next way
transfer(auswertung.value,setName(11))
11, while expecting 111
is this your problem?
Update:
Just to be clear, everything you generated in PHP stays in PHP, you need to geenrate JS assignment to pass value to JS. You currently have hardcoded value of 11 at your transfer function, and span result111.

This might work or it might not. It is just an attempt, because you asked me for it in the comments. Have a try and see, what happens.
GUI.php
<?php
$id = 1;
function getSpanId($addedid){
$spanid = $id + $addedid;
return $spanid;
}
?>
<script>
function transfer(value,id)
{
if (window.XMLHttpRequest)
{
// AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
xmlhttp=new XMLHttpRequest();
}
else
{
// AJAX mit IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result"+id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","backEnd.php?v="+value+"&id="+id,true);
xmlhttp.send();
return;
}
</script>
<?php
include 'fader.php';
?>
fader.php
<form oninput="transfer(auswertung.value,<?php getSpanId(11); ?>)">
<input type="range" name="auswertung" min="0" max= "63" value="30" orient="vertical">
<br>
<span id="<?php getSpanId(11); ?>">n.a.</Span>
</form>

Related

How to use the response PHP variables in a XHR call?

I have two pages say, page1.php and page2.php. In page1.php I have a button, when clicked it makes XHR call to page2.php and shows the response in a defined divison i.e. "print" in page1.
Code for page1.php
<html>
<button type="button" onclick="randomFunction()">Request data</button>
<div id="print"></div>
<script type="text/javascript">
function randomFunction()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("print").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","page2.php",true);
xmlhttp.send();
}
</script>
</html>
Code for page2.php
<?php
$a = "apple";
$b = "banana";
echo $a;
echo $b;
?>
Output I am getting now, http://imgur.com/tyqEOgW
I want to manipulate with the response I'm getting from page2. As in I want to show "apple" in red and "banana" in blue on page1.php
How do I do that?
Send back JSON from page2.php and then add your custom HTML with that data to page1.php.
page1.php
<html>
<button type="button" onclick="randomFunction()">Request data</button>
<div id="print"></div>
<script type="text/javascript">
function randomFunction()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
var html = '<span class="apple">'+data.a+'</span><span class="banana">'+data.b+'</span>';
document.getElementById("print").innerHTML = html;
}
}
xmlhttp.open("POST","page2.php",true);
xmlhttp.send();
}
</script>
</html>
page2.php
<?php
$a = "apple";
$b = "banana";
echo json_encode( array( 'a' => $a, 'b' => $b ) );
?>
Now you could style these spans like you want. Of course you can edit the HTML structure to your desire.
Only PHP
page1.php
<html>
Request data
<div id="print">
<?php
// Show data only, if our link was clicked
if( $_GET['showData'] == 1 ){
// Get page2.php
require_once('page2.php');
echo '<span class="apple">'.$a.'</span><span class="banana">'.$b.'</span>';
}
?>
</div>
</html>
page2.php
<?php
$a = "apple";
$b = "banana";
?>

is it possible to add these up as a grand total using this code?

Is it possible to calculate a grand total with this code. I want compcase and caselight to give a grand total after the buttons are pressed. Any help would be appreciated as I can't work out a possible way of calculating it all.
index.php
function casePrice(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","caseprice.php?q="+str,true);
xmlhttp.send();
}
function caselightPrice(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","caselightprice.php?q="+str,true);
xmlhttp.send();
}
</script>
<Form name ="pc" Method ="Post" ACTION ="radiobutton.php">
<Input type = 'Radio' Name ='compcase' onchange="casePrice(this.value)" value= '1' />NZXT Phantom Enthusiast USB3.0 Full Tower Case - White <br />
<Input type = 'Radio' Name ='compcase' onchange="showPrice(this.value)" value= '2' />Corsair Obsidian 750D Large Tower Case Black <br />
<Input type = 'Radio' Name ='compcase' onchange="showPrice(this.value)" value= '3' />Cooler Master CM Storm Trooper Black Full Tower Gaming Case <br /><br />
<Input type = 'Radio' Name ='caselight' onchange="caselightPrice(this.value)" value= '1' />Red<br />
<Input type = 'Radio' Name ='caselight' onchange="caselightPrice(this.value)" value= '2' />Green <br /><br />
<div id="txtHint"><b>Show price here</b></div>
caseprice.php
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','test');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"compcase");
$sql="SELECT * FROM compcase WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['case_price'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Do you want the grand total of the cases?
If so, make your select query as such:
SELECT SUM('case_price') AS grand_total FROM compcase WHERE id = '".$q."'";
Then when you go through the foreach loop, use $row['grand_total'].

Progress bar AJAX and PHP

I want to create a progress bar for a server-side task ( written in php )
For learning purposes the example and task would be very simplistic.
I would have a text field on the client page, read a number, pass it to the php script with ajax and make it calculate the sum of all numbers from 0 to number ( simplistic task that would take some time for big numbers, just to simulate some server-side work)
in the .html file I would create a timer that would call a function every n seconds getting the index that my for loop got to and update a progress bar.
My question is :
Is it possible to have in the same php file two functions , and how can I call a specific function with ajax : one that would block looping to number and another one I would call to get the current index the for-loop got to.
The code I have so far :
<!DOCTYPE html>
<html>
<head>
<script>
function myTimer()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("percentageDiv").innerHTML=xmlhttp.response;
alert(xmlhttp.response);
}
}
xmlhttp.open("GET","getter.php",true);
xmlhttp.send();
}
function loop(){
var loop_index = document.getElementById("loop_nr").value;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("sumDiv").innerHTML="Total sum = " + xmlhttp.response;
clearInterval(myVar);
}
}
xmlhttp.open("GET","server_side.php?nr="+loop_index,true);
xmlhttp.send();
var myVar=setInterval(function(){myTimer()},1000);
}
</script>
</head>
<body>
<div id="percentageDiv"> Percentage div</div>
<div id="sumDiv"></div>
<input type="text" id="loop_nr">
<input type="submit" onclick="loop()">
</body>
</html>
server_side.php
<?php
session_start();
$index=$_GET["nr"];
$progress = 0 ;
$sum = 0 ;
for ($i = 1; $i <= $index; $i++) {
$sum = $sum + $i;
$progress++;
$_SESSION['progress'] = $progress;
}
echo $sum;
?>
getter.php
<?php
session_start();
$progress = $_SESSION['progress'];
echo $progress;
?>
Thank You!
Not only one question in here
Your question would be two:
How can I do AJAX calls to specific functions in PHP?
How can I do a progress bar with AJAX?
How can I do AJAX calls to specific functions in PHP?
Your AJAX code is fine. The only thing you have to do in your PHP is receive this call.
Look at your request. You send a variable nr with your request:
server_side.php?nr="+loop_index
That will help us in the php code to determine that this is an AJAX call to do the sum operation. Now in the PHP:
<?php session_start();
//We look at the GET php variable to see if the "nr" is coming
if(isset($_GET['nr'])) {
//Its coming!. Now we procede to call our function to sum
sum($_GET['nr']);
}
function sum($nr) {
$progress = 0 ;
$sum = 0 ;
for ($i = 1; $i <= $nr; $i++) {
$sum = $sum + $i;
$progress++;
$_SESSION['progress'] = $progress;
}
echo $sum;
}
Thats it.
How can I do a progress bar with AJAX?
We need to make other AJAX call to request the progress to PHP.
First, we do another AJAX call to retrieve the progress with a timer!
var timer;
//try to delete duplications. Do a generic function that does the request to php
function makeRequest(toPHP, callback) {
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
callback(xmlhttp.response);
}
}
xmlhttp.open("GET",toPHP,true);
xmlhttp.send();
}
function loop() {
var loop_index = document.getElementById("loop_nr").value;
makeRequest("server_side.php?nr="+loop_index, function(response) {
document.getElementById("sumDiv").innerHTML="Total sum = " + response;
clearInterval(timer);
});
timer=setInterval(makeRequest("getter.php", function(response) {
document.getElementById("percentageDiv").innerHTML=response;
}),1000);
}
Then in the php side we retrieve this call as we did before and echo the $_SESSION['progress'] (as you already have)
<?php
session_start();
$progress = $_SESSION['progress'];
echo $progress;
?>
And that's it!
Edit: Sessions must not be saved to a file (default PHP behaviour) because if you do that the "progress" AJAX will be blocked. You should store your sessions in a key-value database such as Redis to achieve parallelism and horizontal scalability.
Here is the solution to made progress bar in PHP without javascript only on server side:
echo "<div style=\"float:left;\">Start... </div>";
for ($i = 0; $i<20; $i++){
echo '<div style="float:left;background-color:red;height:20px;width:'.$i.'px"></div>';
ob_flush();
flush();
usleep(100000);
}
echo "<div style=\"float:left\"> Done!</div>.";
ob_end_flush();exit;

AJAX Response Text Empty

I'm creating a system that interacts with Minecraft server using AJAX. My JavaScript code is as follows:
function doMessage(name, message)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://duncan.usr.sh/omnicraft/api/broadcast-msg.php?message=" + message + "&user=" + name,false);
xmlhttp.send();
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
My PHP code is as follows:
<?php
header('content-type: text/plain');
echo "OmniCraft/Api/RequestHTTP";
if($_GET['message'] == "" or ctype_space($_GET['message']) or $_GET['user'] == "" or ctype_space($_GET['user']))
{
echo "\nOmniCraft/Api/Request/Failed";
echo "\nRequest invalid: No message specified";
exit;
}
include_once '../MinecraftQuery.class.php';
$Query = new MinecraftQuery( );
try
{
$Query->Connect( 'localhost', 25565 );
$info = $Query->GetInfo( );
}
catch( MinecraftQueryException $e )
{
echo "\nOmniCraft/Api/Request/Failed";
echo "\nServer not online";
exit;
}
include_once("rcon.class.php"); //Include this file
$r = new rcon("127.0.0.1",25575,"notRealPasswordHere"); //create rcon object for server on the rcon port with a specific password
if($r->Auth()) //Connect and attempt to authenticate
{
$message = $_GET['message'];
$user = $_GET['user'];
$r->rconCommand("/tellraw #a {'text':'<$user using OmniMessage> $message','color':'white'}"); //send a command
echo "\nOmniCraft/Api/Request/Success";
echo "\nMessage sent successfully!";
}
else
{
echo "\nOmniCraft/Api/Request/Failed";
echo "\nUnable to authenticate to RCON";
exit;
}
?>
My form is as follows:
<form >
<div class="input">
<input type="text" placeholder="Message" style="padding: 20px 28px;font-size: 25px;" required="true" name="message">
</div>
<div class="input">
<input type="text" placeholder="Name" style="padding: 20px 28px;font-size: 25px;" required="true" name="name">
</div>
<button class="btn btn-large btn-success" type="button" onclick="doMessage(this.form.name.value, this.form.message.value)">Send</button>
<div>
<p class="lead" id="preview">< using OmniMessage></p>
<div>
<div id="response">
</div>
The AJAX query executes well, except for the fact that the responseText variable seems to not contain the response text (i.e. the DIV with the id 'response' remains empty after the query is complete).
The correct contents of the response DIV should be:
OmniCraft/Api/RequestHTTP
OmniCraft/Api/Request/Success
Message sent successfully!
However, this is not the case. What am I doing wrong?
EDIT: More Info:
I get the following error:
[20:14:21.855] NS_ERROR_FAILURE: Failure # http://omnicraft.duncan.usr.sh/omnimessage/:154
Line 154 is: xmlhttp.send();
(or maybe document.getElementById("response").innerHTML=xmlhttp.responseText;
Try this
You haven't handled onreadystatechange
function doMessage(name, message) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://duncan.usr.sh/omnicraft/api/broadcast-msg.php?message=" + message + "&user=" + name,false);
xmlhttp.send();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("response").innerHTML=xmlhttp.responseText;
}
}
}
Try removing the header call in your PHP code. I’m having a very similar issue that only goes away when I no longer issue a Content-Type header through PHP.

PHP & AJAX & MySQL integration

I'm trying to get the code below working so that it will call a JS function to pass a value to my PHP file which will return a number of values from a MySQL database. This is part of an assignment I thought would be quite straightforward but I think my problem is with the JavaScript event handler - how to reference the input value maybe?
The HTML:
<form>
<input type="text" name="users" onkeydown="showUser(this)"/>
</form>
<div id="txtHint">
<p id="responder"><b>Person info will be listed here.</b></p>
</div>
The showUser() function:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("responder").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("responder").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","php/student_query.php?q="+str,true);
xmlhttp.send();
}
</script>
The PHP:
<?php
$q=$_GET["q"];
// Step 1
$conn = mysql_connect("localhost", "root");
// Step 2
mysql_select_db("collegeData", $conn);
//Step 3
$sql="SELECT * FROM studenttable WHERE studentID = '".$q."'";
$result = mysql_query($sql);
// Step 4
while ($row = mysql_fetch_array($result))
{
// Step 5
echo "Hello $row[firstName] $row[lastName]<br/>";
echo "Your two course modules are $row[moduleNo1] and $row[moduleNo2]<br/>";
echo "<tr><td> $row[firstName]</td><td> $row[lastName] </td> <td> $row[studentID] </td> </tr>";
echo "<br/>";
}
// Step 6
mysql_close($conn);
?>
Like I said, i think my problem is in the event handler, I'm not great with JS. I'd appreciate any help.
Looks like you're sending the input element to your function, not it's value. Try
<input type="text" name="users" onkeydown="showUser(this.value);" />
Also, you should protect your database query from protection by changing your PHP to
$q = mysql_real_escape_string(trim($_GET["q"]));
if($q == "")
{
echo "";
exit;
}

Categories