I have a PHP file that has some radio inputs on them which I wish to use to create a two variables (text string and a integer) via an AJAX (Not JQuery) call which I can use in the PHP file. I can work with a single variable which out puts to "getElementById" but as soon as I add a second, the code fails.
1/ How do I get more than one variable back from the AJAX?
2/ I can work with "getElementById" for collecting the new PHP variables but as I just want to set a couple of PHP variables for use later, I'm not sure this is the best method of collecting the response.
After reading around the web and Stackoverflow, I have got as far as the code below but no success.
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("Div1").innerHTML="";
document.getElementById("Div2").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)
{
var response = (ajaxRequest.responseText).split(';',2);
var intVariable = response[0];
var StringVariable = response[1];
document.getElementById("Div1").innerHTML=xmlhttp.intVariable;
document.getElementById("Div2").innerHTML=xmlhttp.StringVariable;
}
}
xmlhttp.open("GET","ajax_info.php?bookingstate="+str,true);
xmlhttp.send();
}
</script>
<form name='users'>
<radiogroup>
<input type="radio" name="user" value="1" onclick="showUser(this.value)" <?php if ($select_state == '1') echo 'checked="checked"'; ?> >1
<br>
<input type="radio" name="user" value="2" onclick="showUser(this.value)" <?php if ($select_state == '2') echo 'checked="checked"'; ?> >2
<br>
<input type="radio" name="user" value="3" onclick="showUser(this.value)" <?php if ($select_state == '3') echo 'checked="checked"'; ?> >3
<br>
</radiogroup>
</form>
And my ajax_info.php file
<?php
if ($bookingstate == "1") {
$select_state_name = "Booking state: 1";
$select_state1 = "1";
} elseif ($bookingstate =="2") {
$select_state_name = "Booking state: 2";
$select_state1 = "2";
} elseif ($bookingstate == "3") {
$select_state_name = "Booking state: 3";
$select_state1 = "3";
}
echo '$select_state1;$select_state_name;';
?>
you are settings those variables locally so
document.getElementById("Div1").innerHTML=xmlhttp.intVariable;
document.getElementById("Div2").innerHTML=xmlhttp.StringVariable;
should just be
document.getElementById("Div1").innerHTML=intVariable;
document.getElementById("Div2").innerHTML=StringVariable;
Related
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>
Im using AJax to call a php file and get the values, however, on submission, everything works fine but returning unidentified variable from the called php file.
This is my script
<script>
function showPrice(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET",'getcurrentpumpprice.php?q='+str,true);
xmlhttp.send();
}
var pumpprice1 = document.getElementById('pumpprice').value;
var amount1 = document.getElementById('amount').value;
document.getElementById('litre').value = (amount1) / (pumpprice1);
}
</script>
and this is my php code
$q = isset($_GET['q']);
$outletid = $session->userinfo['retailoutlet'];
if($q == 'PMS'){
$query = "SELECT pms_price FROM ".TBL_RETAIL_OUTLETS." WHERE outlet_id= '$outletid ' ";
$result = $database->query($query);
$row = $result->fetch_assoc();
$pump_price = $row['pms_price'];
}
echo '<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Current Pump Price <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input id="pumpprice" name="pumpprice" class="form-control col-md-7 col-xs-12" required="required" type="text" value="'.$pump_price.'" readonly="readonly">
</div>
</div>';
Im using AJax to call a php file and get the values, however, on
submission, everything works fine but returning unidentified variable
from the called php file.
Cause
In your case variable $q will never be 'PMS' because you got
$q = intval($_GET['q']); so if($q == 'PMS'){ evaluates false, and variable $pump_price will be undefined
always
Example below one evaluates false reason intval(),
if($q == 'PMS'){
then
variable ($pump_price) you are using in echo will be undefined variable
Either you should use echo inside your if statement
if($q == 'PMS'){
echo 'your html';
}
OR
if(isset($pump_price)){
echo 'your html';
}
Better you validate before querying, also good if you use PDO
if( isset($_GET['q']) && is_int($_GET['q']) ){
$q = intval($_GET['q']);
// your remaining code
}else{
echo 'invalid input';
}
Following the example from http://www.w3schools.com/ajax/ajax_aspphp.asp and am using a php file to send back suggestion related to words within the array. I want to display them in html but when I put the paragraph tag round the php file the whole array is printed to screen not the selected words, please help my code for javascript and the form are below
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
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","gethint.php",true);
xmlhttp.send();
}
</script>
My PHP file is then
<?PHP
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
// get the q parameter from URL
$q=$_REQUEST["q"];
$hint="";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{ $q=strtolower($q); $len=strlen($q);
foreach($a as $name)
{ if (stristr($q, substr($name,0,$len)))
{ if ($hint==="")
{ $hint=$name; }
else
{ $hint .= ", $name"; }
}
}
}
// Output "no suggestion" if no hint were found
// or output the correct values
echo $hint==="" ? "no suggestion" : $hint;
?>
It seems that your are not passing your q get param to the php script via ajax at all
xmlhttp.open("GET","gethint.php",true);
should be
xmlhttp.open("GET","gethint.php?q="+str,true);
Check if your copy is IDENTICALL with mine. Working copy:
http://pastebin.com/zWDtqvka
This one works for me with no problems, i tested the php and html in isolation and running both.
===============================
HTML FILE
===============================
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length == 0)
{
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", "hints.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
=================================================================================================================
PHP hints.php
=================================================================================================================
<?php
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
$q = isset($_REQUEST['q']) ? $_REQUEST['q'] : '';
$hint = '';
if ($q !== '') {
$q = strtolower($q);
$len = strlen($q);
foreach ($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === '') {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
echo ($hint === "") ? "no suggestion" : $hint;
?>
Also, if you are running it in netbeans make sure, you installed php, and check this config after clicking your project name by right mouse button in projects view
this is my index.php (submit a form by ajax and retrun an alert)
<form>
<input id="email" type="text">
<input id="cellphone" type="text">
<input type="button" value="submit" onclick='runajax()'/>
</form>
<div id="display">
this is js code:
<script type="text/javascript">
function runajax() {
var xmlhttp;
var val1=document.getElementById('email').value;
var val2=document.getElementById('cellphone').value;
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("display").innerHTML = xmlhttp.responseText;
console.log(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "doForm.php?email="+val1+"&cellphone="+val2, true);
xmlhttp.send(null);
}
</script>
and this is "doForm.php"
<?php
echo "your email is".$_GET['email'];
echo "<script>alert(your email is".$_GET['email'].")</script>";
?>
the problem is this
first echo in doform.php print currectly
but second echo (include an alert javascript code) do not run!
how can I run javascript alert in php output?
try changing this line:
echo "<script>alert(your email is".$_GET['email'].")</script>";
to:
echo "<script>alert('your email is".$_GET['email']."')</script>";
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;
}