ajax load data from php page and mysqli - php

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();
}

Related

ajax php always returning null

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.

fetching data from mysql using Ajax

I am trying to calculate the sum of prices sold between two specific dates. My query is okay but it isn't returning anything when i use in PHP. It works when i directly execute in database.
Here is my code,
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var startdate = document.getElementById('startdate').value;
var enddate = document.getElementById('enddate').value;
var queryString = "?startdate=" + startdate ;
queryString += "&enddate=" + enddate;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Start Date: <input type='date' id='startdate' /> <br />
End Date: <input type='date' id='enddate' /> <br />
<input type='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
Here is my PHP Code
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "temp";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$startdate = $_GET['startdate'];
$enddate = $_GET['enddate'];
//build query
$query = "SELECT SUM(price) FROM ajax_example WHERE daterec >= '$startdate'";
$query .= " AND daterec <= '$enddate'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
echo "Query: " . $query . "<br />";
?>
What am i doing wrong? Thank you in advance
Satisj Rajak! you are right!
check mysql_query
first, this function will be deprecated after PHP 5.5.0, try to dont use it.
second, to get the results you have "transform" the variable in an associative array using this example code:
while ($row = mysql_fetch_assoc($result)) {
echo $row['field_name'];
}
and if you use ajax, try to send a json format response.
hope my answer help you.
In your button click handler, try returning false. My first instinct would be that your form is being submitted by that button and your AJAX request is never being completed.
<input type='button' onclick='ajaxFunction(); return false;' value='Query MySQL'/>
If that doesn't solve it, open up google chrome and the network debugging tools. When you execute the AJAX request, check the request and response data.
In addition, you should optimize your JavaScript to be more effective.
Here is a snippet of JS which could be used in your situation:
var get = function(path) {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.open('GET', path);
request.onload = function() {
if (request.status == 200)
resolve(request.response);
else
reject(Error(request.statusText));
};
request.onerror = function() {
reject(Error(request.statusText));
};
request.send();
});
}
function fetchQueryResults() {
get('/test.php').then(function(response) {
var el = document.getElementById('results');
el.innerHTML = response;
}).catch(function(error) {
// Something went wrong, handle the error here
});
return false;
}

sending multiple parameters to mysql database

this code is to autosave form in mysql database
i am unable to send multiple parameters
the main issue is here
var saved_text = document.getElementById("saved_text").value;
var content = document.getElementByID("test").value;
var params = "saved_text="+saved_text+"content="+content;
php code
<?php
$user_id = 1;
if($_SERVER["REQUEST_METHOD"]=="POST")
{
$saved_text = mysql_real_escape_string($_POST["saved_text"]);
$sql = "UPDATE asave SET saved_text = '".$saved_text."' ";
$sql.= "WHERE user_id = $user_id";
mysql_query($sql) or die(mysql_error().$sql);
echo "Your data has been saved ".date("h:m:s A");
exit;
}
$sql = "SELECT saved_text FROM asave WHERE user_id = $user_id";
$rs = mysql_query($sql) or die(mysql_error().$sql);
$arr = mysql_fetch_array($rs);
$saved_text = $arr["saved_text"];
?>
html code
<html>
<head>
<script type="text/javascript">
function init(){
window.setInterval(autoSave,10000); // 10 seconds
}
function autoSave(){
var saved_text = document.getElementById("saved_text").value;
var content = document.getElementByID("test").value;
var params = "saved_text="+saved_text+"content="+content;
var http = getHTTPObject();
http.onreadystatechange = function(){
if(http.readyState==4 && http.status==200){
msg = document.getElementById("msg");
msg.innerHTML = "<span onclick='this.style.display=\"none\";'>"+http.responseText+" (<u>close</u>)</span>";
}
};
http.open("POST", window.location.href, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
}
//cross-browser xmlHTTP getter
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
</script>
</head>
<body onload="init();">
<span id="msg" style="cursor:pointer;"></span>
<form method="POST">
<textarea id="saved_text" name="saved_text" rows="10" cols="100"><?PHP echo $saved_text;?></textarea>
<br/>
<input id="test" type="text" value="<?php echo $content;?>">
<input type="submit" value="save now" />
</form>
</body>
You're not posting saved_text in your javascript. You're posting params (that is missing a delimiter).
To post multiple parameters check this post: Posting parameters to a url using the POST method without using a form

unable to send complete data into database using ajax

i m using the following javascript to send the data into database
var x=document.getElementById("sortable").innerHTML;
alert(x);
var http=new XMLHttpRequest();
http.open("POST", "5.php?field="+x, true);
http.onreadystatechange = function()
{
if(http.readyState == 4 && http.status == 200)
{
alert(http.responseText);
}
}
http.send();
on php side i m using the following functions:
$l=$_GET['field'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("formdem", $con);
$sql="INSERT INTO rohit(content)VALUES('$l')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "<br/>&nbsp&nbsp&nbsp Your Form is now ready to be filled.....";
$rs= mysql_query("Select * from rohit where content='$l'");
if(mysql_num_rows($rs)!=0)
{
while($row = mysql_fetch_array($rs)) {
echo "<br/>Your unique id is ".$row['formid'];
}
}
but this code is not sending the complete data into database. what may be the reasons. in database i have taken field as longtext.
thnx
As your innerHTML is some HTML, it can't be simply added to make an URL. You can't do this :
http.open("POST", "5.php?field="+x, true);
You have to urlEncode x before :
http.open("POST", "5.php?field="+encodeURIComponent(x), true);

Javascript PHP synchronisation problem

I want to call a javascript function with parametars that are stored in MySQL. All this is happening on an onClick event.
Here is the javascript code:
function getFile() {
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("POST", "gmap.php", false);
AJAX.send("searchField=" + searchField.value);
return load(AJAX.responseText);
} else {
return false;
}
}
So, the gmap.php is echoing the parameters for the javascript load function. But it doesn't load the parameter because the function is called before the MySQL query in gmap.php is executed. I've tried sync and async AJAX.
If I try to call the javascript function from PHP, it doesn't get executed, because it is called on a onClick event, and this is inside a div.
Please help me, I'm doing this over a week now. I've tried everything.
Here is the php code with the MySQL query:
<?php
header( 'Content-Type: text/html; charset=UTF-8' );
mb_internal_encoding( 'UTF-8' );
$a = $_POST['searchField'];
$dbhost = "localhost";
$dbuser = "*******";
$dbpass = "*******";
$dbname = "citydb";
//connect sql
mysql_connect($dbhost, $dbuser, $dbpass);
//select db
mysql_select_db($dbname) or die(mysql_error());
//retrieve data
//$city=$_GET['city'];
//escape user input to help prevent SQL injection
//$city=mysql_real_escape_string($city);
//query
mysql_query('SET CHARACTER SET utf8');
$result=mysql_query("SELECT citystart, cityend FROM cityids WHERE city='$a' ");
if(!result) {
die("Database query failed: " . myql_error());
}
while($row=mysql_fetch_array($result)) {
$lat=$row['citystart'];
$lng=$row['cityend'];
}
echo $lat;
echo ", ";
echo $lng;
?>
pass the php url together with the variable to search.
if (AJAX) {
var url = "gmap.php?searchField="+ searchField.value;
AJAX.open("POST", "url", false);
AJAX.send(true);
return load(AJAX.responseText);
}
I think searchField.value does not contain anything.
Replace
searchField.value
With this
document.getElementById('searchField').value
assign the searchField as an id to the search box.
add this code after AJAX.open and before AJAX.send.
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", searchField.value.length);
AJAX.setRequestHeader("Connection", "close");
I have succesfully tested this
<html>
<head>
<script>
function load(response) {
alert(response);
}
function getFile() {
if (window.XMLHttpRequest) AJAX=new XMLHttpRequest();
else AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX) {
var params = "foo=" + searchField.value;
AJAX.open("POST", "http://localhost/test.php", true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", params.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.onreadystatechange = function() {
var ok;
try { ok=AJAX.readyState; } catch(e) { }
if(ok==4) load(AJAX.responseText);
}
AJAX.send(params);
}
}
</script>
</head>
<body>
<input type="text" id="searchField"/>
<input type="button" onclick="getFile()"/>
<script>
searchField = document.getElementById("searchField");
</script>
</body>
</html>

Categories