PHP Ajax not working - javascript

I have 3 buttons on my page and depending on which one the user is clickingi want to run through ajax call a delete query in my database. When the user clicks on a button the javascript function seems to work but it doesn't run the query in php script.
The html page:
<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
<script>
function myFunction(name)
{
var r=confirm("Are you sure? This action cannot be undone!");
if (r==true)
{
alert(name); // check if is getting in if statement and confirm the parameter's value
var xmlhttp;
if (str.length==0)
{
document.getElementById("clearMessage").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)
{
document.getElementById("clearMessage").innerHTML= responseText;
}
}
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
xmlhttp.send();
}
else
alert('pff');
}
</script>
</head>
<body>
<div id="wrapper">
<div id="header"></div>
<div id="main">
<?php if (session_is_registered("username")){ ?>
<!--Εκκαθάριση παλαιών μηνυμάτων<br />
Εκκαθάριση παλαιών συνεδρίων<br />
Εκκαθάριση push notifications<br />-->
<input type="button" value="Εκκαθάριση παλαιών μηνυμάτων" onclick="myFunction('messages')" />
<input type="button" value="Εκκαθάριση παλαιών συνεδρίων" onclick="myFunction('conferences')" />
<input type="button" value="Εκκαθάριση push notifications" onclick="myFunction('notifications')" />
<div id="clearMessage"></div>
<?php } else echo "Login first."; ?>
</div>
<div id="footer"></div>
</div>
</body>
</html>
and the php script:
<?php
if (isset($_GET["q"]))
$q=$_GET["q"];
$host = "localhost";
$database = "dbname";
$user = "dbuser";
$pass = "dbpass";
$con = mysql_connect($host,$user,$pass) or die(mysql_error());
mysql_select_db($database,$con) or die(mysql_error());
if ($q=="messages")
$query = "DELETE FROM push_message WHERE time_sent IS NOT NULL";
else if ($q=="conferences")
$query = "DELETE FROM push_message WHERE time_sent IS NOT NULL";
else if ($q=="notifications") {
$query = "DELETE FROM push_friend WHERE time_sent IS NOT NULL";
}
$res = mysql_query($query,$con) or die(mysql_error());
if ($res)
echo "success";
else
echo "failed";
mysql_close($con);
?>

You have a few issues.... and this got the text from clearDatabase.php... I just had it output some generic text
<?php session_start(); ?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
<script>
function myFunction(name)
{
var r=confirm("Are you sure? This action cannot be undone!");
if (r==true)
{
// Issue #1: str is not defined anywhere
var str = "sfs";
alert("name " + name); // check if is getting in if statement and confirm the parameter's value
var xmlhttp;
if (str.length==0)
{
document.getElementById("clearMessage").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)
{
// Issue #2: responseText was not defined... it needs to belong to something
document.getElementById("clearMessage").innerHTML= xmlhttp.responseText;
}
}
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
xmlhttp.send();
}
else
alert('pff');
}
</script>
note: anyone who runs "clearDatabase.php?q="+name can delete whatever from your database. Also, make those changes but it still may not work if the code on "clearDatabase.php?q="+name doesn't work.
Also: it would have been a lot easier for us to troubleshoot this for you if you had provided the console errors.
How I solved this: I just copied and pasted this in a document myself and opened up the Chrome version of Firebug (control+shift+j) and there was red text to tell me str wasn't defined. So I defined it as var str="". Then I realized it was hitting if (str.length==0) so I give it a value. Then, I got a new error that the responseText wasn't defined. I googled how to use the response form a javascript ajax call (I only know jquery) and looked at the examples. I saw it needed to be from the request and added xmlhttp.responseText;. Then it worked.

Try;
xmlhttp.open("POST","clearDatabase.php?q="+name,true);
instead of;
xmlhttp.open("GET","clearDatabase.php?q="+name,true);

first open the xmlhttp request.
try this:
xmlhttp.open("GET","clearDatabase.php?q="+name,true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("clearMessage").innerHTML= responseText;
}
}
xmlhttp.send(null);

why dont you use jquery -> ajax() ?
And your code will look like this:
function myFunction(name)
{
var r=confirm("Are you sure? This action cannot be undone!");
if (r==true)
{
alert(name); // check if is getting in if statement and confirm the parameter's value
$.ajax({
type: "GET",
url: "clearDatabase.php?q="+name,true,
success: function (res){
$("#clearMessage").html(res );
}
});
}
else{
alert('pff');
}
}

Related

How to get <span id= var

I’m working at a web GUI for an audio mixer. Therefor I have lot of repetitive faders. All looking the same, just differing by ID. The ID is a three digit number. The first digit is provide by the main php page, the other are repetitive in each fader section. I’m trying to get the result back from the server and posting it into a span field. The problem is that the span id depends on the full id.
The span id should be “result111”.Not hardcoded as it is but dynamically generated by the provide id followed by the identifier 11.
GUI php
<script>
function transfer(value,id)
{
if (window.XMLHttpRequest)
{
// AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
xmlhttp=new XMLHttpRequest();
}
else
{
// AJAX mit IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result"+id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","backEnd.php?v="+value+"&id="+id,true);
xmlhttp.send();
return;
}
</script>
backEnd.php
<?php
$id = 10;
$value = 7;
$result = 6;
if ( isset($_GET['id']) )
{
$id = $_GET['id'];
}
if ( isset($_GET['v']) )
{
$value = $_GET['v'];
$result = $value;
}
echo ("$id + $result");
?>
GUI.php
<?php
$id = 1;
include 'fader.php';
?>
fader.php
<script>
var id = <?php echo "$id"; ?>;
function setName (id2){
var fullId =""+ id + id2;
return fullId;
}
function setNameReturn (id2){
var fullIdReturn =""+ id + id2;
return fullIdReturn;
}
</script>
<form oninput="transfer(auswertung.value,setName(11))">
<input type="range" name="auswertung" min="0" max= "63" value="30" orient="vertical">
<br>
<span id="setNameReturn (11)">n.a.</Span>
</form>
You passing value to your function in next way
transfer(auswertung.value,setName(11))
11, while expecting 111
is this your problem?
Update:
Just to be clear, everything you generated in PHP stays in PHP, you need to geenrate JS assignment to pass value to JS. You currently have hardcoded value of 11 at your transfer function, and span result111.
This might work or it might not. It is just an attempt, because you asked me for it in the comments. Have a try and see, what happens.
GUI.php
<?php
$id = 1;
function getSpanId($addedid){
$spanid = $id + $addedid;
return $spanid;
}
?>
<script>
function transfer(value,id)
{
if (window.XMLHttpRequest)
{
// AJAX nutzen mit IE7+, Chrome, Firefox, Safari, Opera
xmlhttp=new XMLHttpRequest();
}
else
{
// AJAX mit IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result"+id).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","backEnd.php?v="+value+"&id="+id,true);
xmlhttp.send();
return;
}
</script>
<?php
include 'fader.php';
?>
fader.php
<form oninput="transfer(auswertung.value,<?php getSpanId(11); ?>)">
<input type="range" name="auswertung" min="0" max= "63" value="30" orient="vertical">
<br>
<span id="<?php getSpanId(11); ?>">n.a.</Span>
</form>

How to use the response PHP variables in a XHR call?

I have two pages say, page1.php and page2.php. In page1.php I have a button, when clicked it makes XHR call to page2.php and shows the response in a defined divison i.e. "print" in page1.
Code for page1.php
<html>
<button type="button" onclick="randomFunction()">Request data</button>
<div id="print"></div>
<script type="text/javascript">
function randomFunction()
{
var xmlhttp;
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)
{
document.getElementById("print").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","page2.php",true);
xmlhttp.send();
}
</script>
</html>
Code for page2.php
<?php
$a = "apple";
$b = "banana";
echo $a;
echo $b;
?>
Output I am getting now, http://imgur.com/tyqEOgW
I want to manipulate with the response I'm getting from page2. As in I want to show "apple" in red and "banana" in blue on page1.php
How do I do that?
Send back JSON from page2.php and then add your custom HTML with that data to page1.php.
page1.php
<html>
<button type="button" onclick="randomFunction()">Request data</button>
<div id="print"></div>
<script type="text/javascript">
function randomFunction()
{
var xmlhttp;
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 data = JSON.parse(xmlhttp.responseText);
var html = '<span class="apple">'+data.a+'</span><span class="banana">'+data.b+'</span>';
document.getElementById("print").innerHTML = html;
}
}
xmlhttp.open("POST","page2.php",true);
xmlhttp.send();
}
</script>
</html>
page2.php
<?php
$a = "apple";
$b = "banana";
echo json_encode( array( 'a' => $a, 'b' => $b ) );
?>
Now you could style these spans like you want. Of course you can edit the HTML structure to your desire.
Only PHP
page1.php
<html>
Request data
<div id="print">
<?php
// Show data only, if our link was clicked
if( $_GET['showData'] == 1 ){
// Get page2.php
require_once('page2.php');
echo '<span class="apple">'.$a.'</span><span class="banana">'.$b.'</span>';
}
?>
</div>
</html>
page2.php
<?php
$a = "apple";
$b = "banana";
?>

php created select tag with ajax

Good day this is my code of index
<!DOCTYPE html>
<html>
<body>
<script>
function show_month(var) {
if (windows.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","month.php?q="+var,true);
xmlhttp.send();
}
</script>
<?php
$from = (date('Y'));
$to = 2050;
echo '<form>';
echo '<select name="year" onchange="show_month(this.value)">';
for($y = $from; $y <= $to; $y++) {
echo "<option value=$y>{$y}</option>";
}
echo '</select>';
echo '<form>';
?>
<div id="txtHint"><b>here will be info</b></div>
</body>
</html>
and here is code of my month.php
<!DOCTYPE html>
<html>
<body>
<?php
$q = $_GET['q'];
echo $q;
if ($q == 2015) {
echo "actual year";
}
else {
echo "unactual year";
}
?>
</body>
</html>
As you see I created select tag with php so I can make multiple options of year just by using loop and I want that if I select year 2015 javascript should print message actual year but it isn't working I think that problem is somewhere in select or sending value can someone more intelligent than me look into this code and tell me whats is wrong?
Your js code does not have the response code. Also you have a few other errors in your code which will cause issues for you.
show_month(var) you cannot have var as this specific to JS, change it to something else.
windows.XMLHttpRequest This is window not windows.
In order to show what you need use;
alert(xmlhttp.responseText);
in your response if.
<script>
function show_month(t) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","month.php?q="+t,true);
xmlhttp.send();
}
</script>
and finally you don't need <!DOCTYPE html> in your month.php if you are just returning text (most likely you will never need a reason for it).
Your js code is missing code to handle server response
<script>
function show_month(var) {
if (windows.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","month.php?q="+var,true);
xmlhttp.send();
}

How to display ajax in html

Following the example from http://www.w3schools.com/ajax/ajax_aspphp.asp and am using a php file to send back suggestion related to words within the array. I want to display them in html but when I put the paragraph tag round the php file the whole array is printed to screen not the selected words, please help my code for javascript and the form are below
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").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)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("GET","gethint.php",true);
xmlhttp.send();
}
</script>
My PHP file is then
<?PHP
// Fill up array with names
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
// get the q parameter from URL
$q=$_REQUEST["q"];
$hint="";
// lookup all hints from array if $q is different from ""
if ($q !== "")
{ $q=strtolower($q); $len=strlen($q);
foreach($a as $name)
{ if (stristr($q, substr($name,0,$len)))
{ if ($hint==="")
{ $hint=$name; }
else
{ $hint .= ", $name"; }
}
}
}
// Output "no suggestion" if no hint were found
// or output the correct values
echo $hint==="" ? "no suggestion" : $hint;
?>
It seems that your are not passing your q get param to the php script via ajax at all
xmlhttp.open("GET","gethint.php",true);
should be
xmlhttp.open("GET","gethint.php?q="+str,true);
Check if your copy is IDENTICALL with mine. Working copy:
http://pastebin.com/zWDtqvka
This one works for me with no problems, i tested the php and html in isolation and running both.
===============================
HTML FILE
===============================
<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length == 0)
{
document.getElementById("txtHint").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)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "hints.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<h3>Start typing a name in the input field below:</h3>
<form action="">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
=================================================================================================================
PHP hints.php
=================================================================================================================
<?php
$a[]="Anna";
$a[]="Brittany";
$a[]="Cinderella";
$a[]="Diana";
$a[]="Eva";
$a[]="Fiona";
$a[]="Gunda";
$a[]="Hege";
$a[]="Inga";
$a[]="Johanna";
$a[]="Kitty";
$a[]="Linda";
$a[]="Nina";
$a[]="Ophelia";
$a[]="Petunia";
$a[]="Amanda";
$a[]="Raquel";
$a[]="Cindy";
$a[]="Doris";
$a[]="Eve";
$a[]="Evita";
$a[]="Sunniva";
$a[]="Tove";
$a[]="Unni";
$a[]="Violet";
$a[]="Liza";
$a[]="Elizabeth";
$a[]="Ellen";
$a[]="Wenche";
$a[]="Vicky";
$q = isset($_REQUEST['q']) ? $_REQUEST['q'] : '';
$hint = '';
if ($q !== '') {
$q = strtolower($q);
$len = strlen($q);
foreach ($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === '') {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
echo ($hint === "") ? "no suggestion" : $hint;
?>
Also, if you are running it in netbeans make sure, you installed php, and check this config after clicking your project name by right mouse button in projects view

PHP & AJAX & MySQL integration

I'm trying to get the code below working so that it will call a JS function to pass a value to my PHP file which will return a number of values from a MySQL database. This is part of an assignment I thought would be quite straightforward but I think my problem is with the JavaScript event handler - how to reference the input value maybe?
The HTML:
<form>
<input type="text" name="users" onkeydown="showUser(this)"/>
</form>
<div id="txtHint">
<p id="responder"><b>Person info will be listed here.</b></p>
</div>
The showUser() function:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("responder").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)
{
document.getElementById("responder").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","php/student_query.php?q="+str,true);
xmlhttp.send();
}
</script>
The PHP:
<?php
$q=$_GET["q"];
// Step 1
$conn = mysql_connect("localhost", "root");
// Step 2
mysql_select_db("collegeData", $conn);
//Step 3
$sql="SELECT * FROM studenttable WHERE studentID = '".$q."'";
$result = mysql_query($sql);
// Step 4
while ($row = mysql_fetch_array($result))
{
// Step 5
echo "Hello $row[firstName] $row[lastName]<br/>";
echo "Your two course modules are $row[moduleNo1] and $row[moduleNo2]<br/>";
echo "<tr><td> $row[firstName]</td><td> $row[lastName] </td> <td> $row[studentID] </td> </tr>";
echo "<br/>";
}
// Step 6
mysql_close($conn);
?>
Like I said, i think my problem is in the event handler, I'm not great with JS. I'd appreciate any help.
Looks like you're sending the input element to your function, not it's value. Try
<input type="text" name="users" onkeydown="showUser(this.value);" />
Also, you should protect your database query from protection by changing your PHP to
$q = mysql_real_escape_string(trim($_GET["q"]));
if($q == "")
{
echo "";
exit;
}

Categories