Hi im trying to use multple ajax functions which im not sure is possible.
my first one is called when your typing your username
onkeyup="UsernameTaken(this.value);"
the other one is called in the body with
onload="BattlePlayers();"
the functions are like this
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
function UsernameTaken(name){
if (name == "") {
document.getElementById("UsernameTaken").innerHTML = "";
return;
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("UsernameTaken").innerHTML = this.responseText;
}
};
xhttp.open("GET", "CheckUsername.php?q="+name, true);
xhttp.send();
}
function BattlePlayers(){
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("BattleTable").innerHTML = this.responseText;
}
};
xhttp.open("GET", "GetPlayers.php", true);
xhttp.send();
}
then the php for the battleplayer which seems to always return blank is this
<?php
$link = mysqli_connect("","","","");
if (isset($_SESSION['username'])) {
$x = 0;
$sql = "SELECT * FROM userstats ORDER BY RAND() LIMIT 5; ";
$result = mysqli_query($link,$sql);
$toecho ="";
while($row = mysqli_fetch_assoc($result)){
if($row['username'] !== $_SESSION['username']){//add so it dosent put duplicates
$toecho .="<tr>";
$toecho .="<th>".$row['username']." </th>";
$toecho .="<th>Level: ".$row['Level']." </th>";
$toecho .="<th>Player Stats:".$row['Attack']."/".$row['Defence']." </th>";
$toecho .="<th>Win Chance: ";
$toecho .= CalculateWinChance($link,$row['Defence']);
$toecho .="<input type='hidden' name='hidden1' value='".$row['Defence']."' />";
$toecho .="<input type='hidden' name='hidden2' value='".$row['username']."' />";
$toecho .="<th><input type ='submit' name = 'Attack_Btn' value ='Attack'></th>";
$toecho .="</tr>";
}
}
echo $toecho;
}
?>
it does not seem to get to the battleplayers at all i have tried echoing an alert from getplayers with nothing coming up. i have confirmed that the javascript is being called by making that alert at different stages. its just when it reaches the getplayers that is just seems to stop. what am i doing wrong here?
If you think logically about what your ajax request is doing then you'll realise that if the page being called via ajax needs access to session variables then, because it is effectively a distinct request separate from the page that initiated the request, you will need to include session_start() on that script.
If you had a standard php page like:
<?php
session_start();
include 'functions.php';
include 'classes.php';
include 'GetPlayers.php';
?>
<html>
<head>
<title></title>
</head>
<body>
<!-- stuff -->
</body>
</html>
In the above example page your script GetPlayers.php WOULD have access to the session.
<?php
session_start();
include 'functions.php';
include 'classes.php';
?>
<html>
<head>
<title></title>
</head>
<body>
<script>
xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.status==200 && xhr.readyState==4 ){
alert( xhr.response );
}
};
xhr.open( 'GET','GetPlayers.php',true );
xhr.send();
</script>
</body>
</html>
Whereas here, without session_start() at the top of GetPlayers.php the two pages do not share the same session and hence when the script checks for if (isset($_SESSION['username'])) {.....} it will fail.
Related
I have a database that contains information for x variable. I want to have php page that load datafrom mysqli with ajax and my phpapi page. so
I create my database and it fills up every 1 minute.
I create a php page that load a data from mysqli and output with
this is my php page that load data from my mysqli and it working right
this is myphpapi.php page
<?php
$con = mysqli_connect("x.x.x.x","boob","booob");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
mysqli_select_db($con,"sss");
$sql = "SELECT `x` FROM ddd order by id desc limit 1";
$result = mysqli_query($con,$sql);
$result = mysqli_fetch_assoc($result);
$output = json_encode($result);
echo $output;
mysqli_close($con);
?>
this part work well but I have another php page that contain ajax. When I push button, nothing happend
please help
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ajax test</title>
</head>
<body>
<h1>
this is ajax test
</h1>
<div id="main">
</div>
<button type="button" id="ajax_button">click me</button>
<script>
replaceText();
function replaceText() {
var target = document.getElementById("main");
var xhr = new XMLHttpRequest();
xhr.open('GET', 'myphpapi.php', true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 2) {
target.innerHTML = 'loading . . . .';
}
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
var json = JSON.parse(xhr.responseText);
target.innerHTML = json;
}
xhr.send();
}
}
var button = document.getElementById("ajax_button");
button.addEventListener("click",replaceText);
</script>
</body>
</html>
If you change the order a little within your ajax function and move the send method outside the onreadystatechange event handler it should work ~ though as pointed ut by #Barmar JSON.parse will return an object.
function replaceText() {
var target = document.getElementById("main");
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 2) {
target.innerHTML = 'loading . . . .';
}
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
var json = JSON.parse(xhr.responseText);
target.innerHTML = json;
}
}
xhr.open('GET', 'myphpapi.php', true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
}
I have a database called opera_house with a table called room that has a field room_name and a field capacity. I want to show the room_name 's that have a capacity larger than the one entered by the user.
The Available Room text disappears, but my code only shows the MySQL query if I echo it, but I'm not sure if it is reaching to search the database.
This is my script code:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
function showRoom(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","ajax_events.php?q="+str,true);
xmlhttp.send();
}
}
This is my html:
<body>
<form>
<input type="text" name="room" onkeyup="showRoom(this.value)">
</form>
<br>
<div id="txtHint"><b>Available Room...</b></div>
</body>
This is my php:
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection,"opera_house");
$sql="SELECT room_name FROM room WHERE capacity >= '".$q."'";
echo $sql;
$result = mysqli_query($connection,$sql);
while($row = mysqli_fetch_array($result)) {
echo "<td>" . $row['room_name'] . "</td>";
}
?>
My php file is called ajax_events.php
And my dbconnect.php is one that I constantly use to connect to this database.
Would really appreciate some help!!
I propose an answer using jquery. You've embedded it in your question but you're not using it ...
Explanations : You call the following url ajax_events.php with the parameter "q" only if str is defined, otherwise it fills the selector txtHint with nothing.
AJAX
if (str != "") {
$.ajax({
type: 'GET',
url: 'ajax_events.php',
dataType: 'JSON',
data : {
q: str
}
}).done(function (data) {
$('#txtHint').text = data;
}).fail(function() {
alert('Fatal error');
})
} else {
$('#txtHint').text = '';
}
With this configuration, it is important to return result with echo json_encode in your server side code.
PHP
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection, "opera_house");
$sql = 'SELECT room_name FROM room WHERE capacity >= '.$q; // Some corrections
$result = mysqli_query($connection, $sql);
$return = '';
while($row = mysqli_fetch_array($result)) {
$return .= '<td>' . $row["room_name"] . '</td>';
}
echo json_encode($return); // Return Json to ajax
?>
While thinking of JS it's fine. I think the problems are in the php code. Try this one.
<?php
include('dbconnect.php');
$q = intval($_GET['q']);
mysqli_select_db($connection,"opera_house");
$sql="SELECT room_name FROM room WHERE capacity >= " . $q;
$result = mysqli_query($connection,$sql);
if (!$result) {
echo mysqli_error();
exit();
} // this is to do debugging. remove when you get it fixed
$ret = ""; //variable to hold return string
while($row = mysqli_fetch_array($result)) {
$ret .= "<td>" . $row['room_name'] . "</td>";
}
echo $ret;
Hi i am having trouble making this ajax code work with JavaScript. The function is called studentReqHandler with a button onclick function and everything is in echo's. this is the code of the function studentReqHandler:
echo "<script type='text/javascript'>
function studentReqHandler(action,id,email,elem){
_(elem).innerHTML = 'processing ...';
var ajax = ajaxObj('POST', 'verifying.php');
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == 'accept_ok'){
_(elem).innerHTML = '<b>User Verified!</b><br />';
} else {
_(elem).innerHTML = ajax.responseText;
}
}
}
ajax.send('action='+action+'&id='+id+'&email='+email);
}
</script>
this is the onclick button :
<button onclick='studentReqHandler(\"accept\",\"".$id."\",\"".$email."\",\"user_info_".$id."\")'>accept</button> or
";
other ajax related functions:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
and last the php for this to work:
if (isset($_POST['action']) && isset($_POST['id'])&& isset($_POST['email'])){
$id = preg_replace('#[^0-9]#', '', $_POST['id']);
$email = $_POST['email'];
if($_POST['action'] == "accept"){
$sql = "UPDATE profile SET verified='1' WHERE id='$id' AND email='$email' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
mysqli_close($db_conx);
echo "accept_ok";
exit();
}
}
Can anyone figure out why this doesnt work?
I pasted this code and it works:
Minimum error, is you got some messy quotes in the <button> javascript string.
<?php
/* using this at the top to check what happens when it posts. */
if (isset($_POST['action']) && isset($_POST['id'])&& isset($_POST['email'])){
$id = preg_replace('#[^0-9]#', '', $_POST['id']);
$email = $_POST['email'];
if($_POST['action'] == "accept"){
/* I commented out the query, so you must make sure that works right */
$sql = "UPDATE profile SET verified='1' WHERE id='$id' AND email='$email' LIMIT 1";
//$query = mysqli_query($db_conx, $sql);
// mysqli_close($db_conx);
echo "accept_ok";
exit();
}
}
/* some default values. You need to make sure you get these from somewhere.*/
$id=3;
$email="oo#oooo.com";
/* ELEMENT changes when I click the button */
echo "Div Element <div id='element'>ELEMENT</div> area<br><br>";
?>
<script type='text/javascript'>
function studentReqHandler(action,id,email,elem) {
/* I used the basic document element locator */
document.getElementById('element').innerHTML = 'processing ...';
/* I posted to itself this time. */
var ajax = ajaxObj('POST', 'ajax.php');
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText == 'accept_ok'){
document.getElementById('element').innerHTML = '<b>User Verified!</b><br />';
} else {
document.getElementById('element').innerHTML = ajax.responseText;
}
}
}
ajax.send('action='+action+'&id='+id+'&email='+email);
}
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
</script>
/* There were too many quotes and \'s in the original button. */
<br>The Button<br>
<?php
echo "<button onclick=\"studentReqHandler('accept','$id','$email','user_info_$id') \">accept</button>";
?>
peace be with you All, i am new to using Ajax , the issue is, i am having 3 drop down lists connected to a database, the first one is "name" and the second one is "age" and the third one is "country"! so, i have connected to the database, and retrieved data from it in the first list "name" and then using Ajax, i have successfully retrieved matching data after selecting any option of first list and put them into the second list called "age", the problem is that when i use a very exact same way with the second list called "age" to retrieve matching data into third list called "country" it doesn't work! so please help me cuz, i am using this example to learn Ajax and then apply on a larger real project!
here is the code :-
firstly, the home.php page:-
<?php
include "config.php";
?>
<html>
<head>
<script type="text/javascript">
function agematch() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('age').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'connection.inc.php?name='+document.ajax.name.value, true );
xmlhttp.send();
}
function countrymatch() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('country').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', 'country.inc.php?age='+document.ajax.age.value, true );
xmlhttp.send();
}
</script>
</head>
<body>
<form id="ajax" name="ajax" >
Choose your name : <select name="name" id="name" select="selected" onchange="agematch();"> <option> </option>
<?php
$query = "SELECT DISTINCT name FROM info";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
echo"<option value ='".$row[0]."'> '".#$row[0]."'</option>";
}
?>
</select>
Age : <select id="age" name="age" onchange="countrymatch();"> </select>
country : <select id="country" name="country"> <option> </option> </select>
</form>
</body>
</html>
now, the page for first Ajax call :-
<?php
include "config.php";
echo " <option> </option> " ;
if(isset( $_GET['name']) ) {
#$name = $_GET['name'];
}
$query = "SELECT age FROM info WHERE name = '".#$name."' ";
$result = mysql_query($query);
while ($query_row = mysql_fetch_array($result)) {
echo " <option value ='".$query_row[0]."'> $query_row[0]</option> ";
}
?>
Now, with the page for the second Ajax call for the third drop menu :-
<?php
include "config.php";
if (isset( $_GET['age']) ) {
#$age=$_GET['age'];
}
$query = "SELECT country FROM info WHERE name='".#$name."' AND age='".#$age."' ";
$result= mysql_query($query);
while ($query_row = mysql_fetch_array($result)) {
echo " <option value = '".$query_row[0]."'> $query_row[0] </option> ";
}
?>
so as you see, here is the code, and of course i am connected to the database through a page called "config.php", so i want you to help me to solve this issue and retrieve the data from database into the third drop down list "country".
Thanks in Advance!
Ok, Musa here is the edit :-
function countrymatch() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('country').innerHTML = xmlhttp.responseText;
}
}
var age = encodeUriComponent(document.ajax.age.value),
var name = encodeUriComponent(document.ajax.name.value),
xmlhttp.open('GET', 'country.inc.php?age='+age+'&name'+name, true );
xmlhttp.send();
}
and also :-
<?php
include "config.php";
if (isset($_GET['age'], $_GET['name']) ) {
#$age=$_GET['age'];
#$name = $_GET['name'];
}
$query = "SELECT country from info where name='".#$name."' AND age='".#$age."' ";
$result= mysql_query($query);
while ($query_row = mysql_fetch_array($result)) {
echo " <option value = '".$query_row[0]."'> $query_row[0] </option> ";
}
?>
I don't get any error messages, i am sure your point is right but this solution didn't work unfortunately! thank you so much for helping me :)
You didn't send the name in the second ajax request but you need it for your database query, so you'll need to send the name as well as the age in the ajax request. Also you aren't sanitizing your input, you must always validate user input, I'd also suggest not using mysql_*
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
var age = encodeURIComponent(document.ajax.age.value),
var name = encodeURIComponent(document.ajax.name.value),
xmlhttp.open('GET', 'country.inc.php?age='+age+'&name'+name, true );
if (isset($_GET['age'], $_GET['name']) ) {
$age = $_GET['age'];
$name = $_GET['name'];
...
}
Basically I need to insert the value of a textarea asynchronously but when I call the function insertSQLData() it shows the source code of the page, besides that I cant find the other errors. I omitted the database code and any irrelevant code as well.
<?php
$q = $_GET["q"];
$username = $_COOKIE["user"];
?>
function insertSQLData(str){
if(str == 0){
document.getElementById("holder").innerHTML="";
return;
}
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("holder").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "index-async.php?q=+str", true);
xmlhttp.send();
}
<form action="" method="get">
<textarea onblur="insertSQLData(this.value);" id="quick-post-form" name="quick-post-form"></textarea>
<input type="button" value="Submit" name="quick-post-btn" id="quick-post-submit">
<div id="holder"></div>
if(isset($username) && !empty($q)){
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', '$username')");
} elseif(!empty($q)) {
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', 'Guest User')");
}
You have to load it before your php file starts up.
All you have to do is to write a controller, and use it anywhere instead of your index.php and in that, (after loading those things from DB) redirect user to your index.php page providing those data you need.
So you are calling same page where ajax call is..
obviously it returns the code.
write php code in another file and try to call it.
it works
You write code in conditional statement as per given below.
<?php
if(isset($_GET["q"]))
{
$q = $_GET["q"];
$username = $_COOKIE["user"];
if(isset($username) && !empty($q)){
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', '$username')");
} elseif(!empty($q)) {
mysql_query("INSERT INTO comments (comment,username) VALUES ('$q', 'Guest User')");
}
}
else
{
?>
<script>
function insertSQLData(str){
if(str == 0){
document.getElementById("holder").innerHTML="";
return;
}
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("holder").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "index-async.php?q=+str", true);
xmlhttp.send();
}
</script>
<form action="" method="get">
<textarea onblur="insertSQLData(this.value);" id="quick-post-form" name="quick-post-form"></textarea>
<input type="button" value="Submit" name="quick-post-btn" id="quick-post-submit">
<div id="holder"></div>
<?php
}
?>