I have written a simple application that displays a list of candidates for a job, then, upon clicking a hire button, should alter a database to reflect the newly hired candidate and display the rest as unhired. However, the function is not working properly. The problem I am having is the AJAX function never seems to provide a response, and I cannot figure out why. The database is also not getting updated. My files are below.
The line document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>"; is updating a div at the bottom of my html page, showing that the the readyState is 4 and the status is 200, which should mean that the AJAX function returned properly, but the echo'd response is not being displayed. Even when I remove all code from the new_hire.php file and simply make the file echo "hello";, nothing is returned in the responseText.
resumes.php:
<html>
<head>
<script type="text/javascript">
function new_hire(name){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>";
//this line, when removed, does not change anything. I left it in for debugging purposes.
document.getElementById("errors").innerHTML+=xmlhttp.responseText;
if (xmlhttp.readyState=4 && xmlhttp.status=200){
var others = xmlhttp.responseText.split("|");
for (i=0;i<others.length;i++){
tag = others[i].replace(" ","_");
document.getElementById(tag).innerHTML="";
}
}
}
xmlhttp.open("POST","new_hire.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("hiree="+name.replace(" ","%20")+"&position=Salespeople");
var name_tag = name.replace(" ","_");
document.getElementById(name_tag).innerHTML="(Current Employee)<br>";
}
</script>
</head>
...
</html>
new_hire.php (AJAX response file):
<?php
$hiree = $_POST['hiree'];
$pos = $_POST['position'];
$con = mysql_connect("host.name","user","pass") or die('Could not connect: ' . mysql_error());
mysql_select_db("dbname",$con);
$clear = mysql_query("UPDATE $pos SET employed=false WHERE 1=1;");
mysql_fetch_array($clear);
$reset = mysql_query("UPDATE $pos SET employed=true WHERE Name='$hiree';");
mysql_fetch_array($reset);
$people = mysql_query("SELECT Name FROM $pos WHERE employed=false;");
$array = array();
while ($row = mysql_fetch_array($people)){
array_push($array,$row['Name']);
}
mysql_close($con);
$response = join("|",$array);
echo $response;
?>
Please note that your if statement is not using the comparison operator == but rather the assignment operator = so you are using: if (xmlhttp.readyState=4 && xmlhttp.status=200) instead of if (xmlhttp.readyState==4 && xmlhttp.status==200)
Related
I am using jQuery to send a part number from one php file to another.
The part number is received correctly in the destination php file, but when when I try to use it, it does not work.
Here is the strange thing: To test,when I use $mpn=STA-12 (or any other value that exists in table2), in destination php file, the connection is established and the relevant data is extracted, BUT when THE SAME DATA is fetched, it does not work
Here is the destination PHP file:
<?php
$row['mpn'] = $_GET['q'];
include("order/connection.php");
echo "mpn is here : ".$row['mpn']; // It displays STA-12 but doesn't data get fetched!
$mpn=$row['mpn'];
//$mpn="STA-12"; // *** When I actually put this line in, it all works ***
$stmt = $pd->prepare("SELECT * FROM table2 WHERE part_number = :part_number " );
//$stmt->execute(array());
$stmt->execute(array(':part_number' => $mpn));
$row = $stmt->fetch(PDO::FETCH_BOTH);
//... rest of the code
?>
This jQuery script copied from W3:
<script>
function showUser(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","serv.reply3.3.php?q="+str,true);
xmlhttp.send();
}
}
And this is where it is called from:
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Choose</option>
<option value=" <?php echo $row["mpn"]; ?> ">items</option>
</select>
</form>
The problem is finally solved.
Since the code was copied from another example, the jQuery variable sent over, contained some EXTRA information that when ECHO'ed didn't show.
echo "mpn is here : ".$row['mpn']; that displayed STA-12, actually contained ' string(6) " STA-12" ', which was discovered by doing:
var_dump( $row['mpn']).
This had my head scratching for days.
I am trying to pass a variable from a javascript function to my php file. All I do is extract the user_name from a cookie in javascript and then use AJAX to $_POST the variable to my php file for processing. I do not use a form to submit the POST variable which I have done in the past.
The problem is my $_POST array is not getting passed to the php file. I've looked here and looked at several other suggestions but none work. Do you have to submit the $_POST variable via an html form? I dont think so but maybe I'm wrong. Here is the code:
Javascript -
function clearDoneItems() {
var user_name = getNameFromCookie();
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert(user_name);
xmlhttp.open("POST","todolist/clear_done_items.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(user_name);
displayHomeInformation(user_name);
}
PHP -
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Clear Done Items</title>
</head>
<body>
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
print_r($_POST);
$xml_name=$_POST['user_name'];
$xml_file = $xml_name . ".xml";
echo $xml_file;
/* Here we will use the The DOMDocument class functions to delete
the text nodes.
Format XML to save indented tree rather than one line */
$domxml = new DOMDocument('1.0');
if ($domxml->load('$xml_file') === TRUE) {
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
// Start Delete process of node
echo "<br>";
$xpath = new DOMXPath($domxml);
// Here we use the The DOMXPath class function evaluate to do the heavy lifting.
foreach ($xpath->evaluate('//doneitems/item') as $node) {
$node->parentNode->removeChild($node);
}
//Save XML to file - remove this and following line if save not desired
$domxml->save('alan.xml');
echo "<strong>XML Document updated.</strong>";
}
else {
echo " <strong>Error in loading XML file:</strong>";
echo "<br>";
print_r(error_get_last());
}
?>
</body>
</html>
Errors on php page:
Notice: Undefined index: user_name in /var/www/bb/todolist/clear_done_items.php on line 16
0
Warning: DOMDocument::load(): I/O warning : failed to load external entity "/var/www/bb/todolist/$xml_file" in /var/www/bb/todolist/clear_done_items.php on line 24
Sorry for the delay in responding. I just wanted to post how I solved issue. I will have to revisit using the $_POST array with AJAX cause I was never able to pass a variable thru it.
Javascript:
// Clear Done Items Function
function clear_done_items()
{
var xmlhttp;
var temp = document.getElementById("list_section");
var temp_list_name = temp.innerHTML;
var str_len = temp_list_name.length;
var list_name = temp_list_name.slice(17,str_len);
var user_name = getNameFromCookie();
if (user_name == list_name) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","todolist/clear_done_items.php",true);
xmlhttp.send();
} else {
alert("Warning: You Must be Logged in as this User, " + list_name + ", to Delete the Completed Items List");
}
}
and php:
<?php
$xml_cookie = $_COOKIE['user'];
$xml_file_name = $xml_cookie . ".xml";
/* Here we will use the The DOMDocument class functions to delete
the text nodes.*/
//Format XML to save indented tree rather than one line
$domxml = new DOMDocument('1.0');
if ($domxml->load($xml_file_name) === TRUE) {
$domxml->preserveWhiteSpace = false;
$domxml->formatOutput = true;
// Start Delete process of node
echo "<br>";
$xpath = new DOMXPath($domxml);
// Here we use the The DOMXPath class function evaluate to do the heavy lifting.
foreach ($xpath->evaluate('//doneitems/item') as $node) {
$node->parentNode->removeChild($node);
}
//Save XML to file - remove this and following line if save not desired
$domxml->save($xml_file_name);
echo "<strong>XML Document updated.</strong>";
}
else {
echo " <strong>Error in loading XML file:</strong>";
echo "<br>";
print_r(error_get_last());
}
?>
so basically I'm using a cookie to get the user_name variable to php to process from the main page.
Haven't found this exact situation on here, so I figured I'd ask. I have some JavaScript that, using AJAX, is attempting to call a PHP file, execute the PHP script, and return a concatenated PHP variable through xmlhttp.responseText, then alert that response.
JS
function queryDB() {
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)
{
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET","php/location.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
PHP
<?php
$con = mysql_connect("<THIS DATA HIDDEN FOR SECURITY PURPOSES, IT IS CORRECT");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("gpstracks", $con);
$bus = $_GET['bus'];
$query = "SELECT lat, lon from tracksarchive where runnerid = '$bus' ORDER BY time DESC LIMIT 1;";
$latlon = mysql_query($query);
while ($row = mysql_fetch_array($latlon, MYSQL_ASSOC)) {
$lat = $row['lat'];
$lon = $row['lon'];
}
$result = $lat . ", " . $lon;
echo $result;
mysql_close($con);
?>
Yes, I know that mysql_ has been replaced by mysqli_, I'll deal with that later. When I execute the PHP on its own (using a form submit) - it displays the correct values from the table, but when I alert the xmlhttp.responseText - I only get the comma and space - no passed variables. Any idea what I'm doing wrong? Help is much appreciated.
Sidenote: I know the preferred method for AJAX calls these days is jQuery - but a component of the page this JavaScript is on doesn't function when I use jQuery.
when I alert the xmlhttp.responseText - I only get the comma and space - no passed variables
You're not performing your GET properly; in your JavaScript you have
xmlhttp.open("GET","php/location.php",true);
i.e. you performed a GET request without a URI query string.
In your PHP you have
$bus = $_GET['bus'];
i.e. you're GETting this data from the URI query string, except none was passed, so this will be empty, so
$query = "SELECT lat, lon from tracksarchive where runnerid = '$bus' ORDER BY time DESC LIMIT 1;";
doesn't work as expected.
You really wanted to do something like
xmlhttp.open(
"GET",
"php/location.php?bus="+window.encodeURIComponent(foobar),
true
); // foobar your value for `bus`
Further, you'll need to do some server-side sanitisation of $bus, as it stands you're open to SQL injection.
As you send request by GET method, you need to manually add the parameter bus to the URL. So, rewrite
xmlhttp.open("GET","php/location.php",true);
to
xmlhttp.open("GET","php/location.php?bus=value",true);
You should pass "bus" in on the PHP file URL.
I have an anchor tag which i want to use to go to a certain page but at the same time i want to use the onclick function to insert into a databse.
here's what i got so far:
html:
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
alert("txtHint");
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","submit.php?click="+str,true);
xmlhttp.send();
}
</script>
<a onclick="showUser('test')" href="http:www.google.com">click here</a>
and here's the php file:
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("db_name") or die(mysql_error());
// Retrieve all the data from the "example" table
$result = mysql_query("
SELECT `clicked` FROM `links`
WHERE open = ".$_GET['link'])
or die(mysql_error());
$row = mysql_fetch_array( $result )
$x = $row['clicked'];
$y = $x++;
$result2 = mysql_query("
UPDATE `db_name`.`links`
SET `clicked` = $y
WHERE `links`.`open` = '".$_GET['link']."'
")
or die(mysql_error());
mysql_fetch_array($result2);
It's going to google as it should, but it isn't inserting into the database.
Any ideas?
thanks in advance,
Reece
edit- i have fixed all the errors in the php file thanks everyone, it now inserts properly when just visiting the php page with a click in the url.
BUT it still does not insert using the ajax. clearly there is something i have done wrong with the code.
any ideas?
thanks
edit2 solved-
for anyone thats interested, the problem with the ajax code was this line:
xmlhttp.open("GET","submit.php?click="+str,true);
it needed to be like this
xmlhttp.open("GET","/submit.php?click="+str,true);
It's going to google as it should, but it isn't inserting into the database.
Yes, but make sure that the call to the php script actually works and that the script itself is free of errors, then look at the database.
your using mysql_fetch_array($result2); for update use mysql_query($result2)
and its nor $_GET['link'] its $_GET['click']
the first error I found is:
you want $_GET['link']) in your php code, but only send a click parameter in JS. So you should change your JS code:
xmlhttp.open("GET","submit.php?link="+str,true);
try to run the php script without ajax to eventually find more errors.
i suggest use jquery & .post() method.
Syntax of this will be more readable by humans :)
// submit here ...
$.post(
"answer.php",
{
start: $("#ancor_id" ) . attr( "title" )
},
function(ret) {
if (!ret.success )
{
alert(1);
}
else
{
alert( "Update Ok" );
}
},
'json'
);
where answer.php
<?
header( "Content-Type: application/json" );
$arr_json = array();
$arr_json[ "success" ] = "true";
echo json_encode( $arr_json );
exit;
?>
Seems you forgot the ; mark here: $row = mysql_fetch_array( $result )
i've tried using this code and this to make a random quote generator, but it doesn't display anything. my questions are:
what is wrong with my code?
in the above tut, the quote is generated on a button click, i'd like
a random quote to be displayed every
30 mins automatically. how do i do
this?
////////////////////////
quote.html:
<!DOCTYPE html>
<script src="ajax.js" type="text/javascript"></script>
<body>
<!–create the div for the quotes land–>
<div id="quote"><strong>this</strong></div>
<div><a style="cursor:pointer" onclick="run_query();">Next quote …</a></div>
</body>
</html>
/////////////////////
quote.php:
<?php
include 'config.php';
// 'text' is the name of your table that contains
// the information you want to pull from
$rowcount = mysql_query("select count(*) as rows from quotes");
// Gets the total number of items pulled from database.
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
}
// Selects an item's index at random
$rand = rand(1,$max)-1;
$result = mysql_query("select * from quotes limit $rand, 1");
$row = mysql_fetch_array($result);
$randomOutput = $row['storedText'];
echo '<p>' . $randomOutput . '</p>';
////////////
ajax.js:
var xmlHttp
function run_query() {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("This browser does not support HTTP Request");
return;
} // end if
var url="quote.php";
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
} //end function
function stateChanged(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("quote").innerHTML=xmlHttp.responseText;
} //end if
} //end function
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// For these browsers: Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
//For Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
} //end function
Try to print the values for $max,$rand and $result. You can use print_r to get more info from the php page.
Run the quote.php on browser to see if you get an output.
Then get to ajax to debug.
You can use a timer in ajax to automate your requests for every 30 mins or so. use javascript's settimeout function for this.
HTH