if(isset($_GET['delete'])) {
$ID = $_GET['delete'];
echo "
<script type='text/javascript'>
var ajax = new XMLHttpRequest();
var ajax.open('POST','parser.php', true);
ajax.setRequestHeader('Content-type','application/x-www-form-urlencoded');
ajax.onreadystatechange = function () {
if(ajax.readyState ==4 && ajax.status == 200) {
alert(ajax.responseText);
}
}
ajax.send('delete=$ID')
</script>
";
}
this is my code, it is supposed to send the id to parser.php
here is parser.php
<?php
if(isset($_POST['delete'])) {
echo $_POST['delete'];
}
no response is received from parser.php, can anyone help ?
all answers are much appreciated
Related
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.
I am trying to create an AJAX based search in PHP. The code I have written so far does not seem to be working uptil now. Any suggesstions would be of great help. Thanks in advance. Here is my code.
index.php
<head>
<script src = "http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" name="text" id="text" autocomplete="off" onkeyup="showHint(this.value)"/>
<div id="inner"></div>
<script type="text/javascript">
function showHint(str) {
if(str.length == 0) {
document.getElementById('inner').innerHTML = "search";
return;
}
if(window.XMLHttpRequest) {
xmlhttp = XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttpreadystate == 4 && xmlhttp.status == 200) {
document.getElementById('inner').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("REQUEST", "search.php?text"+str, true);
xmlhttp.send();
}
</script>
</body>
</html>
search.php
<?php
$host = 'localhost';
$user = 'root';
$password= 'root';
$db = 'demo';
#$conn = mysql_connect($host, $user, $password) or die(mysql_error());
mysql_select_db($db, $conn);
/*if($result) {
echo "success";
} else { echo "fail"; }
*/
$text = $_REQUEST['text'];
$text = preg_replace('#[^a-z0-9]#i', '', $text);
$query = "SELECT * FROM users where first_name LIKE '%$text%' OR last_name LIKE '%$text%'";
$action = mysql_query($query);
$result = mysql_num_rows($action);
while($res = mysql_fetch_array($action)) {
$output .= $res['first_name']. ' '.$res['last_name'];
echo $output;
}
?>
You missed the equal sign in the script(after the text) in index.php.
xmlhttp.open("REQUEST", "search.php?text="+str, true);
Why you are doing this lengthy process, You can also try this jQuery ajax,
$.ajax({
url: 'search.php',
type: 'GET',
data: 'text='+str,
success: function(data) {
//called when successful
$('#inner').html(data);
},
error: function(e) {
//called when there is an error
console.log(e.message);
}
});
I am just getting the input in search.php. Can you try these codes:
index.html:
<html>
<head>
</head>
<body>
<input type="text" name="text" id="text" autocomplete="off" onkeyup="showHint(this.value)"/>
<div id="inner"></div>
<script type="text/javascript">
function getHttpRequest()
{
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function showHint(str)
{
var xmlhttp;
if (str=="")
{
document.getElementById('inner').innerHTML = "search";
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('inner').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "search.php?str="+str, true);
xmlhttp.send();
}
</script>
</body>
</html>
search.php:
<?php
$text=$_GET["str"];
echo $text;
?>
Use this :
$.ajax({
url: 'search.php',
type: 'GET',
data: 'text='+str,
success: function(data) {
//called when successful
$('#inner').html(data);
},
error: function(e) {
//called when there is an error
console.log(e.message);
alert(e.message); // if you dont know how to check console
}
});
I am trying to retrieve a value from a database through ajax and php.
The ajax code is as follows:
<script>
$(document).ready(function() {
$("#buyprice").change(function() {
if ($("#sname").val() == "") {
alert("Enter Stock name.");
} else {
var sn = $("#sname").val();
alert(sn);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var x = xmlhttp.responseText;
};
};
xmlhttp.open("GET", "getstockprice.php?q="+sn, true);
xmlhttp.send();
alert("here");
};
alert("here");
var bp = $("#buyprice").val();
alert(bp);
alert(x.val());
if(bp>(1.1*x)||bp<(1.1*x)){
alert("Price violating 10% constraint.");
}
alert("here");
});
});
</script>
The php page is as follows:
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','','stock_market');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT stock_price FROM live_prices WHERE stock_name = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
mysqli_close($con);
?>
Can someone please tell me where I am going wrong.
you should use echo or return to return something from php.
<script>
$(document).ready(function() {
$("#buyprice").change(function() {
if ($("#sname").val() == "") {
alert("Enter Stock name.");
} else {
var sn = $("#sname").val();
alert(sn);
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var x = xmlhttp.responseText;
};
};
xmlhttp.open("GET", "getstockprice.php?q="+sn, true);
xmlhttp.send();
alert("here");
};
alert("here");
var bp = $("#buyprice").val();
alert(bp);
alert(x);
if(bp>(1.1*x)||bp<(1.1*x)){
alert("Price violating 10% constraint.");
}
alert("here");
});
});
</script>
PHP
<?php
$q = $_GET['q'];
$con = mysqli_connect('localhost','root','','stock_market');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT stock_price FROM live_prices WHERE stock_name = '".$q."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
mysqli_close($con);
echo $row['stock_price'];
?>
The php script needs to echo the value. This does not display the value on your page, it merely makes the value avalailble to the javascript.
I would suggest using jquery and use the built in ajax functionality. This works much easier.
See the jquery ajax page, and an example straight from there:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
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>";
?>
How I can send rowNumber variable to dataSource php file in this code ?
function getData(dataSource, divID,rowNumber)
{
if(XMLHttpRequestObject)
{
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200)
{
obj.value = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
PHP File (datasource):
<?php
//mysql connection
$result = mysql_query( 'CALL view_polls(`rowNumber`);' );
$row=mysql_fetch_array($result);
echo $row['title'];
?>
in JavaScript:
XMLHttpRequestObject.open("GET", dataSource + '?rowNumber=' + rowNumber);
in PHP:
$result = mysql_query( 'CALL view_polls(`' . $_GET['rowNumber'] . '`);' );
function getData(dataSource, divID,rowNumber)
{
if(XMLHttpRequestObject)
{
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource + "?rownumber=" + rowNumber);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200)
{
obj.value = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
PHP:
<?php
if (isset($_GET['rownumber']) && is_numeric($_GET['rownumber'])) {
$rowNumber = $_GET['rownumber'];
//mysql connection
$result = mysql_query( 'CALL view_polls(`' . $rowNumber . '`);' );
$row=mysql_fetch_array($result);
echo $row['title'];
}
else {
echo "Error";
}
?>