Using ajax to insert into database - php

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 )

Related

Beginner PHP / SQL / AJAX - Query not working when parameter passed to server side script

I am beginning to learn PHP + AJAX + SQL. I cannot seem to crack the syntax issue I am running into. I am running the latest WAMP version on a server in my network as the test environment.
I have the following script in my INDEX.PHP (from W3Schools.com):
<script>
$(document).ready(function() {
$('#submit').click(function() {
str = document.getElementById("cn").value;
if (str=="")
{
document.getElementById("txtHint").innerHTML="No name typed, returning all rows ";
str="all";
};
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","getcustomer.php?q="+str,true);
xmlhttp.send();
});
});
</script>
I then have a server side script called GETCUSTOMER.PHP which contains (in part) the following:
<?php
$q = $_GET['q'];
echo "The variable contains = ".$q; **<--- this shows me on the browser the correct variable value is passed to the server side script**
$con = mysqli_connect('localhost','phpuser','abc123','learnphp');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
};
mysqli_select_db($con,"PHP_AJAX_Demo");
if ($q == "all") {
$sql="SELECT * FROM customers";
} else {
$sql="SELECT * FROM customers WHERE 'Company' = '" . $q . "'";
};
$result = mysqli_query($con,$sql);
When my main form submits with a "blank" value for COMPANY it works fine as the "str=all" is executed and returns to the browser all rows in the CUSTOMERS table. When I submit it with a value (that exists in the table) I get no rows back. I also get no errors back.
The syntax came from W3 and it works on their demo. What am I missing? Thanks in advance!
You're putting single quotes around your column name when single quotes are used to indicate the beginning and end of a string value. Use backticks instead. Change:
$sql="SELECT * FROM customers WHERE 'Company' = '" . $q . "'";
to
$sql="SELECT * FROM `customers` WHERE `Company` = '" . $q . "'";
Note that this script is open to SQL injection and that you should be using prepared statements.

Passing php variable to xmlhttp.responseText

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.

Why is this AJAX function not working properly?

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)

random quote generator with php, ajax and mysql

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

Get MYSQL Data Into AJAX

I'm an AJAX novice and I'm having major trouble trying to get data out of mySQL and into my javascript function.
What I want to do is loop through my data in php and somehow send that data into various named divs on the page.
Here's the code from my javascript page:
function loadPageContent(){
var projectID = getQuerystring('pid');
var templateID = getQuerystring('t');
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null){
alert ("Browser does not support HTTP Request")
return
}
var url="getImages.php"
url=url+"?projectID="+projectID
url=url+"&templateID="+templateID
xmlHttp.open("GET",url,true);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("statusdebug1").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.send(null);
}
Here's the code for my php page:
<?php
$projectID = $_GET["projectID"];
$templateID = $_GET["templateID"];
include_once('includes/php/conn.php');
$sql ="select * FROM imageSel WHERE projectID='$projectID' AND templateName = '$templateID'";
$results=mysql_query($sql, $link);
if(!($mysql_rs = mysql_query($sql, $link)))
die("Error in executing query");
echo "<script language='JavaScript'>";
while($row =mysql_fetch_assoc($results) ){
$imageSelID = $row['imageSelID'];
$templateName = $row['templateName'];
$tNode = $row['box'];
$image = $row['image'];
$sql2 ="select * FROM products WHERE productid='$image'";
if(!($mysql_rs = mysql_query($sql2, $link)))
die("Error in executing query");
//Retrieve values
$row2 = mysql_fetch_array($mysql_rs);
$productname = $row2['productname'];
$subcategoryid = $row2['subcategoryid'];
$sql3 ="select * FROM subcategory WHERE subcategoryid='$subcategoryid'";
if(!($mysql_rs = mysql_query($sql3, $link)))
die("Error in executing query");
//Retrieve values
$row3 = mysql_fetch_array($mysql_rs);
$foldername = $row3['foldername'];
$foldername = strtolower($foldername);
$theImage = '<img src="images/lowres/' . $foldername . '/' . $productname .'" />';
echo "document.getElementById(".$tNode.").innerHTML=".$theImage.";";
}
echo "</script>";
?>
That's typically not how I would implement AJAX.
AJAX, when done correctly, should send data to the browser, then let the browser decide what to do with it.
Try using json_encode to put the data you want to send to the browser in JSON format, then on the Javascript end use a JSON library to decode the data then handle it appropriately.
Good luck!
please use this code :
xmlHttp.open("GET",url,false);
because if you are keeping its true then it will call asynchronize ajax.
Please correct if i am wrong.
You are setting the Ajax response to the innerHTML of the div. But you output javascript in your PHP (which becomes your Ajax response). Try outputting just the img tag without the javascript wrapper. Or, even just outputting "Hello world";
EDITED TO ADD: You're using javascript getElementById and innerHtml on the client side and the server side. It's redundant. You probably want to keep it on the client side, ie, your html and javascript

Categories