Cannot get data passed to a php file using AJAX - javascript

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.

Related

Can we send ajax from a javascript file?

since I wrote this code and it turned out that it is not entering the if statement ,My target was to bring the array from php(db) and put it in array in js,what to do?Here is the code ,is the problem that it is located in an extension js file ?Moreover php file getusercatpref.php is returning ["violen","ios","programming","nodjs"].
var arr = new Array();
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
arr = myArr;
}
};
xmlhttp.open("GET", "getusercatpref.php", true);
xmlhttp.send();
PHP Code
<?php
$name="root";
$pas="";
$dbname="jobpursuit";
$con=mysqli_connect("localhost", $name, $pas,$dbname);
$arrayCategories = array();
$sql="Select * FROM preferences where username='12' ";
$result=mysqli_query($con,$sql);
$index=0;
while($row = mysqli_fetch_assoc($result)){
$arrayCategories[$index] = $row['categoryname'];
$index=$index+1;
}
echo json_encode($arrayCategories);
?>

Repeat PHP function every 2 seconds

So I have a code, where a number is retrieved from a text file and is displayed through HTML.
The thing is that it only retrieves the number when I refresh the page. If I change the number on other page, it doesn't change on the other page.
I've seen similar questions before, most of them said to use AJAX, but I don't understand much about AJAX and I only need it for this bit of code, it's not like I'm going to constantly use it. I would like to know if there is any other besides AJAX and if there is only AJAX, please present examples of code.
PHP code:
<?php
$file = "num.txt"; //Path to your *.txt file
$contents = file($file);
$num = implode($contents);
?>
JavaScript code. Basically it gets the PHP value and outputs to the html.
document.getElementById("num").innerHTML = '<?php echo $num; ?>';
Keep in mind, I don't want to refresh the page. Just the variable.
EDIT: PHP code - Getting an error - Notice: Undefined index: keynum in C:\xampp\htdocs\num.php on line 3
Here is the code of the PHP
<?php
$keynum = $_POST['keynum'];
$post = "INSERT INTO post (keynum) VALUES ($keynum)";
$fileLocation = getenv("DOCUMENT_ROOT") . "/num.txt";
$file = fopen($fileLocation,"w");
$content = $keynum;
fwrite($file,$content);
fclose($file);
echo 'Response';
die();
?>
You can achieve what you want using XMLHttpRequest, like this:
function updateData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('num').innerHTML = this.responseText;
}
};
xhttp.open('GET', '/num.php', true);
xhttp.send();
}
setInterval(updateData, 2000);
If you want to refresh the variable without refreshing the page, then you need to use an asynchronous request. It doesn't need to be AJAX, you can use the native XMLHttpRequest() function.
If you want more info: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests
or with jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
setInterval(function(){
$.ajax({url:"num.php", success:function(result){
$("#num").html(result);
}});
}, 3000);
</script>
<textarea id="num"></textarea>
get_nbr.php
<?php
$file = "num.txt"; //Path to your *.txt file
$contents = file($file);
$num = implode($contents);
echo $num;
?>
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!---trigger get_nbr() on page load on an infinite loop every two seconds -->
<body onload="setInterval(get_nbr, 2000)">
<script>
function get_nbr() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("num").innerHTML = this.responseText;
}
};
xhttp.open("GET", "get_nbr.php", true);
xhttp.send();
}
</script>
<p id="num"></p>
like this.
let url = ""; //whatever url your requesting.
setInterval(function(){
var x = new XMLHttpRequest();
x.open("GET" , url , true);
x.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200)
{
document.getElementById("num").innerHTML = x.responseText;
}
}
x.send();
} , 2000);
-- UPDATE , added post --
setInterval(function(){
var x = new XMLHttpRequest();
x.open("POST" , url , true);
x.setRequestHeader("Content-Type" , "application/x-www-form-urlencoded");
x.onreadystatechange = function(){
if(x.readyState == 4 && x.status == 200)
{
document.getElementById("num").innerHTML = x.responseText;
}
}
x.send("postVar1=123");
} , 2000);

How to set the values of select boxes and input boxes based on a MySQL query, using AJAX

I have a web page with a large number of select boxes plus a few other types of inputs. I want to populate these select boxes and input boxes with values held in a MySQL database based on the values selected in two of the select boxes.
I have tried to use AJAX to request the data but cannot see how to return the data held in a database to a specific select box from the server php script.
jscript used to request the data is as follows
<script>
function venueChange(str) {
if (str == "") {
document.getElementById("Venue").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("Player1").innerHTML = this.responseText;
}
};
var opponent_name = document.getElementById("Opponents").value
var variables = "venue_name=str&opponent_name=Hello World";
xmlhttp.open("GET","getTeamPHP?" + variables,true);
xmlhttp.send();
}
}
</script>
The getTeamPHP files is as follows;
<?php
require '../../configure.php';
$q = intval($_GET['venue_name']);
$v = $_GET['opponent_name'];
$database = "matchmanagementdb";
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASS,$database);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
//mysqli_select_db($con,$database);
$sql="SELECT * FROM user WHERE Opponents = '".$q."' AND Venue = '".$v."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo document.getElementById("Player1").innerHTML = $row['FirstName'] ;
}
mysqli_close($con);
?>
I have decided that the solution lies in creating three scripts to;
1) read the search details
2) search the database and populate the form
3) allow updates.
As per http://www.dynamicdrive.com/forums/showthread.php?45895-How-to-populate-php-html-form-with-MySQL-data.
So closing this question.

Pick out link Ids form database with ajax

Just learning ajax today and am stock somewhere. Trying to link my php links to work with ajax so the data with that link Id would be displayed without refreshing the page. Below are the codes of what I have tried.
index.php
<div class="page">
<ul>
<?php
$sql = <<<EOF
SELECT * FROM addcategory ;
EOF;
$ret = $db->query($sql);
While ($row = $ret->fetchArray(SQLITE3_ASSOC)) {
$catname = $row['catname'];
$catid = $row['catid'];
echo "<li><a href='index.php?category_id=$catid'>$catname</a></li>";
}
?>
</ul>
</div>
<div class="cat_question">response displays here</div>
php script
require_once ("db.php");
$db = new MyDb();
$catid = (int)$_GET['category_id'];
$csql = <<<EOF
SELECT * FROM questions WHERE category_id = {$catid};
$cret = $db->query($csql);
While ($crow = $cret->fetchArray(SQLITE3_ASSOC)) {
$catquestion = $crow['question'];
$catans = $crow['answer'];
echo "<div>$catquestion</div><p>$catans</p>";
}
JavaScript
$('.page a).click(function(e) {
e.preventDefault();
If (window.XMLHttpRequest) {
var xhttp = new XMLHTtpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
If (xhttp.readyState == 4 && xhttp.status == 200) {
var response = xhttp.responseText;
$('.cat_question').html(response);
}
};
xhttp.open("GET", "category.php?category_id=$catid", true);
xhttp.send();
});
I know if i change the xhttp URL to category.php?category_id=1 or any id it works but that would mean in would have to write ajax request for each a tags. Please what is the way to solve this block. Thanks in advance.

How to get Json data in ajax after a mysql query

For my bookshop, I started to built a cashdesk script. This is a very simple form, with an ajax dynamic search. This is a script for a local PC, so the script will not be publish on the web.
When I scan the EAN code, I've my form fill with title, author, editor and price. The book is ready to add in the basket.
Now I'm trying to introduce Json in this script : but I don't understand how to get the values of the mysql query in the script, and put them in the correct fields of my cashdesk form.
I've tested the Mysql query and the Json.
The query
<?php
header('Content-Type: text/html; charset=ISO-8859-1');
include('connexion.php');
$connect_db = connect();
$i = 0;
$tmp = array();
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$tmp[$i] = $row;
}
echo json_encode($tmp);
close();
?>
A json exemple :
[{"product_id":"7097","product_name":"Paix pour tous - Livre audio","product_author":"Wayne W. Dyer","product_editor":"Ada","product_price":"20.28"}]
The ajax script
var xhr = null;
function getXhr()
{
if(window.XMLHttpRequest) xhr = new XMLHttpRequest();
else if(window.ActiveXObject)
{
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
else
{
alert("Not Working");
xhr = false;
}
}
function ajaxEAN()
{
getXhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var data = '{"product_id": "product_id", "product_name":"product_name", "product_author":"product_author", "product_editor":"product_editor", "product_price":"product_price"}';
oData = JSON.parse( data);
for( var i in oData){
document.getElementById( i).value = oData[i];
}
}
}
xhr.open("POST",'ajaxrecupaddr.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
EAN = document.getElementById("EAN").value;
xhr.send("EAN="+EAN);
}
Thanks for any help !
As far as understand, you simply can't take a JSON from response. If so, than you simply should do:
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200) {
oData = JSON.parse(xhr.responseText);
for(var i = 0; i < oData.length; i++) {
for( var key in oData[i]){
document.getElementById(key).value = oData[i][key];
}
}
}
There, xhr.responseText will return a string with JSON received from server.
Also, few notes:
Instead of
header('Content-Type: text/html; charset=ISO-8859-1');
you should better use:
header('Content-Type: application/json;');
Also, in line below you are opened to SQL Injections:
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '$_POST[EAN]'");
instead of simply doing WHERE product_EAN = '$_POST[EAN]' you should do, at least, WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "':
$fetch = mysql_query("SELECT jos_vm_product.product_id,product_name,product_author,product_editor,jos_vm_product_price.product_price FROM jos_vm_product INNER JOIN jos_vm_product_price ON (jos_vm_product.product_id = jos_vm_product_price.product_id) WHERE product_EAN = '".mysql_real_esape_string($_POST["EAN"]) . "'");
See more about mysql_real_escape_string. It will correctly escape all potentially dangerous symbols and will save you from errors when you have ' symbol in EAN. Also, read warning shown on a page linked above. You should better change your database extension as MySQL extension is deprecated.

Categories