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';
}
Related
I am trying to pass data back to the server and then use the reply to update the browser page.
My code for a SELECT input is as follows;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
The script code is as follows;
<script>
function findTeleNo(that){
alert("I am an alert box!" + that);
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TeleNo").value = this.responseText;
}
}
};
xhttp.open("GET", "findTeleNo.php?q=" + that, true);
xhttp.send();
</script>
The purpose of the script is to take the value selected in the dropdown (variable "that") and submit it to the php file as variable q.
And the PHP file is as follows;
<?php
$MatchCaptain = $_REQUEST["q"];
$teleNo = "";
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$teleNo = $db_field['TeleNo'];
break;
}
}
}
echo $teleNo;
function split_name($name) {
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim( preg_replace('#'.$last_name.'#', '', $name ) );
$ufullName = $first_name." ".$last_name;
return $ufullName;
}
?>
The php file requests the q variable from the url and makes it $MatchCaptain.
This will be a name like Joe Bloggs. The next piece of code connects to a MySQL table to extract players first names surnames and telephone numbers. The first names and surnames are concatenated to form the fullname which is compared with the $MatchCaptainWhen a match is made the variable $teleNo is set to the Telephone Number of that player. The echo statement rerurns the value to the script.
The field id I am trying to update is;
<p><b>Telephone Number: </b> <span id="TeleNo"> <?php echo $_SESSION["TeleNo"]; ?></span></p>
The alert in the script function findTeleNo shows me that I have entered the function but nothing happens after that.
Any help as to how I get this working would be grateful.
I have changed my script to
<script>
function findTeleNo(that){
var xhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET", "findTeleNo.php?q=" + encodeURIComponent(that), true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
// OK
alert('response:'+xhttp.responseText);
document.getElementById("TeleNo").innerHTML = this.responseText;
// here you can use the result (cli.responseText)
} else {
// not OK
alert('failure!');
}
}
};
};
</script>
The response shown by alert('response:'+xhttp.responseText); is correct and the line of code
document.getElementById("TeleNo").innerHTML = this.responseText;
does print the response to the web page.
Iam trying to make a live ajax search . When you put a word it automatically shows suggestions bellow just like w3schools. But for some reason my index file and my php doesnt exchange data value or my database doesnt connect for some reason.What i always get is "no country found". Can you check the code for errors?
this is the php file :
<?php
include_once('dbconnect.php');
$q = intval($_GET['q']);
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
$count = mysqli_num_rows($query);
//Replace table_name with your table name and `thing_to_search` with the column you want to search
if($count == "0" || $q == ""){
$s[] = "No Country found!";
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userCountry']; // Replace column_to_display with the column you want the results from
}
}
for($x = 0; $x < $count; $x++) {
echo $s[$x];
echo "<br>";
}
?>
and this is my index.php file :
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
function showCountry(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","indexsearchquery.php?q="+str,true);
xmlhttp.send();
}
}
</script>
<input id="search-box" name="q" type="text" autocomplete="off" placeholder="Search country..." onchange="showCountry(this.value)" />
<input type='image' name='search' id="search-icon" value='Submit' src="search-icon.png" >
<p style="color:white;">Suggestions: <span id="txtHint" ></span></p>
Your country name will not in integer. but you convert it into intval change your php file to
include_once('dbconnect.php');
$q = $_GET['q']; //<-----remove intval
$query = mysqli_query($conn,"SELECT * FROM `users` WHERE userCountry LIKE '%".$q."%'");
$count = mysqli_num_rows($query);
//Replace table_name with your table name and `thing_to_search` with the column you want to search
if($count == "0" || $q == ""){
$s[] = "No Country found!";
}else{
while($row = mysqli_fetch_array($query)){
$s[] = $row['userCountry']; // Replace column_to_display with the column you want the results from
}
}
for($x = 0; $x < $count; $x++) {
echo $s[$x];
echo "<br>";
}
it is important to know the content of the dbconnect.php file because it the one that contains database connection variables.
Check if your MySQL Server is up and that all variable are well set.
And my other question is that, is the code correct, will my AJAX request get to my controller ?
Here is the relevant parts on the code:
My view (I have this on a POST form cause I want to send the data on another table) :
<script> var base_url = <?php echo base_url(); ?> </script>
<label for="exampleInputEmail1">Apartament</label>
<select onchange="showUser(this.value)" name ="txtApartament1" class="form-control">
<?php foreach($getEntry as $value) { ?>
<option><?php echo $value->apartament ?></option>
<?php }?>
</select>
In the same view this is my AJAX part:
function showUser(str) {
if (str == "") {
document.getElementById("txtApartament1").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("txtApartament1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", base_url + "usercontroller/ajaxp?q="+str,true);
xmlhttp.send();
}
}
And this is my controller - usercontroller.php function:
public function ajaxp(){
echo "received";
}
I will get this error:
(index):257 Uncaught ReferenceError: base_url is not defined
at showUser (localhost/adminigniter1/:257:29)
at HTMLSelectElement.onchange (localhost/adminigniter1/:205:89)
My project filename is codeigniter1!
I did not set any config file on codeigniter. should I ? Anything else?
Try like this..
1.Load url helper using $this->load->helper('url') or in applicaiton/config/autoload.php.
2.Set base_url config item in application/config/config.php
$config['base_url'] = 'your_url';
3.In your script.Remove var.Because it creates variable as local.So you can not use inside function.
base_url = <?php echo base_url();
OR put it var base_url = <?php echo base_url(); ?> inside showUser() function.
UPDATE
var url = base_url + "usercontroller/ajaxp?q="+str; //OR var url = <?php base_url();?>+"usercontroller/ajaxp?q="+str;
console.log(url);
xmlhttp.open("GET",url,true);
xmlhttp.send();
I have the following form:
<form id="form" name="form">
<img id="close" src="images/3.png" onclick ="div_hide()">
<h2>Grade</h2>
<hr>
<input id="fn" name="fn" placeholder="Faculty number" type="number">
<select id="grade_type" name="grade_type">
<option value="test" selected="selected">Тест</option>
<option value="attendance">Attendance</option>
<option value="homework">Homework</option>
</select>
<input id="grade" name="grade" placeholder="Points" type="number">
Add record
</form>
When I click the submit button I want to add the points and the grade_type to the database. Therefore I am using JavaScript and PHP:
// Validating Empty Field
function check_empty() {
if (document.getElementById('grade').value == "") {
alert("Fill the fields!");
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
alert("xmlhttpreq");
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var grade = String(document.getElementById('grade').value);
var grade_type = document.getElementById('grade_type');
var grade_type_value = String(grade_type.options[grade_type.selectedIndex].value);
var fn = String(document.getElementById('fn').value);
xmlhttp.open("GET","getuser.php?grade="+grade+"grade_type="+grade_type_value+"fn="+fn,true);
xmlhttp.send();
document.getElementById('form').submit();
}
}
The contents of the getuser.php file are:
<?php
require "config.php";
$fn = $_GET["fn"];
$grade = $_GET["grade"];
$type = $_GET["grade_type"];
echo "<script type='text/javascript'>alert('$fn');</script>";
try {
$conn = new PDO("mysql:host=" . DB_SERVER . ";dbname=" . DB_NAME, DB_USERNAME, DB_PASSWORD);
}
catch(PDOException $e) {
die("Database connection could not be established.");
}
$sql = $conn->prepare("SELECT * FROM students WHERE fn = ?");
$sql->execute(array($fn));
if($sql->rowCount() > 0) {
$statement = $conn->prepare("INSERT INTO points (student_fn, type, grade, datetime)
VALUES (?, ?, ?, CURRENT_TIMESTAMP)");
$statement->execute(array($fn, $type, $grade));
}
else {
echo "<script type='text/javascript'>alert('No such fn');</script>";
}
$conn = null;
?>
However I think it never gets executed because I never see the result of the alert. I have never worked with XMLHttpRequest before so I don't even know whether my code is valid. I would greatly appreciate any help.
You can do this by using jquery.
$('#submit').click(function(){
$.ajax({
url: 'getuser.php',
type: 'GET',
data: $('#form1').serialize(),
success: function(result){
alert("Your data has been uploaded");
}
});
});
make sure that you need to add jquery file to your websitelike that
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;