Why wont this ajax script work on wamp localhost - php

I was trying out this ajax example on my local machine running windows 7 home premium, apache, php and mysql, but it wont return any results to the browser. After reading a few articles here, I downloaded firebug, and from the firebug console->All what I get is this:
GET http://localhost/dev/ajax/ajax-example.php?age=100&wpm=100&sex=m 200 OK 1.01s
Response
Query: SELECT * FROM ajax_example WHERE sex = 'm' AND age <= 100 AND wpm <= 100
<br /><table><tr><th>Name</th><th>Age</th><th>Sex</th><th>WPM</th>
</tr><tr>td>Frank</td><td>45</td><td>m</td><td>87</td></tr><tr><td>Regis</td>
<td>75</td><td>m</td><td>44</td></tr></table>
This thing above is what should be going to the broswer. The script seems to be working fine then, except the div wont refresh with new content.
Is this a broswer issue or windows/javascript issue. What do I need to do to get this working? Could you please help.
Here's the tutorial page I got all this from.
http://www.tutorialspoint.com/ajax/ajax_database.htm
This page is ajax.html
<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;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.value = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "?age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name="myForm">
Max Age: <input type="text" id="age" /> <br />
Max WPM: <input type="text" id="wpm" />
<br />
Sex: <select id="sex">
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type="button" onclick="ajaxFunction()" value="Query MySQL"/>
</form>
<div id="ajaxDiv">Your result will display here</div>
</body>
</html>
This page is ajax-example.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "norman";
$dbname = "test";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "SELECT * FROM ajax_example WHERE sex = '$sex'";
if(is_numeric($age))
$query .= " AND age <= $age";
if(is_numeric($wpm))
$query .= " AND wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

ajaxDisplay.value = ajaxRequest.responseText; here is mistake, change it for example to ajaxDisplay.innerHTML = ajaxRequest.responseText;
and mb use jquery or other framework for such trivial task?

In the callback function
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.value = ajaxRequest.responseText;
}
}
I dont think ajaxDisplay.value will work!
instead use
ajaxDisplay.innerHTML = ajaxRequest.responseText;

Related

Passing URL query string to PHP via AJAX

I am creating a site for users to look up their invoice numbers using their purchase order number and part number.
I have setup an HTML form which passes a query string to a PHP file which then queries a MySQL server, but I am getting an internal server error. The form is working correctly, it is generating the URL with the query strings attached.
Here is my code to generate the query string:
<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;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var partnumber = document.getElementById('partnumber').value;
var ponumber = document.getElementById('ponumber').value;
var queryString = "?partnumber=" + partnumber ;
queryString += "&ponumber=" + ponumber;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send();
}
//-->
</script>
<form name = 'myForm'>
Part Number: <input type = 'text' id = 'partnumber' /> <br />
PO Number: <input type = 'text' id = 'ponumber' />
<br />
<input type = 'button' onclick = 'ajaxFunction()' value = 'Find Invoice Number'/>
</form>
<div id = 'ajaxDiv'>Your result will display here</div>
</body>
</html>
And this is the ajax-example.php file
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$partnumber = $_GET['partnumber'];
$ponumber = $_GET['ponumber'];
// Escape User Input to help prevent SQL Injection
$partnumber = mysql_real_escape_string($partnumber);
$ponumber = mysql_real_escape_string($ponumber);
//build query
$query = "SELECT * FROM data WHERE partnumber = '$partnumber' and `po#` = '$ponumber'";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Part Number</th>";
$display_string .= "<th>PO Number</th>";
$display_string .= "<th>Invoice Number</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)) {
$display_string .= "<tr>";
$display_string .= "<td>$row[partnumber]</td>";
$display_string .= "<td>$row[po#]</td>";
$display_string .= "<td>$row[invoicenumber]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

Google Map + Ajax + Mysql

I want to take variables location, location1, location2 and put them to my base in mysql. I have problem edit google script.
My target is to save 3 variables, when client want to find place.
I was looking for some advices or code in internet. I am a beginner, so sorry for basic code.
Link http://mikozniak.nazwa.pl/dzis/lok.php
Here is my code:
google.maps.event.addDomListener(window, 'load', intilize);
function intilize() {
var autocomplete = new google.maps.places.Autocomplete(document.getElementById("txtautocomplete"));
google.maps.event.addListener(autocomplete, 'place_changed', function () {
var place = autocomplete.getPlace();
var location = place.formatted_address;
var location1 = place.geometry.location.lat();
var location2 = place.geometry.location.lng();
document.getElementById('lblresult').innerHTML = location
document.getElementById('lblresult1').innerHTML = location1
document.getElementById('lblresult2').innerHTML = location2
});
};
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;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function() {
if(ajaxRequest.readyState == 4) {
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var location = document.getElementById('lblresult').value;
var location1 = document.getElementById('lblresult1').value;
var location2 = document.getElementById('lblresult2').value;
queryString += "&location = " + location + "&location1 = " + location1 + "&location2 = " + location2;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
ajaxRequest.send(null);
}
</script>
<span>Miejsce:</span><input type="text" id="txtautocomplete" style="width:200px" placeholder="wpisz miejsce"/>
<label id="lblresult"></label>
<label id="lblresult1"></label>
<label id="lblresult2"></label>
<div id = 'ajaxDiv'>Your result will display here</div>
<?php
$dbhost = "mikozniak.nazwa.pl";
$dbuser ="user";
$dbpass = "password";
$dbname = "name";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($dbname) or die(mysql_error());
// Retrieve data from Query String
$loc = $_GET['location'];
$loc1 = $_GET['location1'];
$loc2 = $_GET['location2'];
// Escape User Input to help prevent SQL Injection
$loc = mysql_real_escape_string($loc);
$loc1 = mysql_real_escape_string($loc1);
$loc2 = mysql_real_escape_string($loc2);
//build query
$query = "INSERT INTO `miejsca`(`idm`, `dl`, `szr`) VALUES (NULL,$loc1,$loc2)";
//if(is_numeric($age))
// $query .= " AND age <= $age";
//if(is_numeric($wpm))
// $query .= " AND wpm <= $wpm";
//Execute query
$qry_result = mysql_query($query) or die(mysql_error());
/*
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)) {
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
*/
?>
You should use an Ajax request in your function intilize(). Link your request to your PHP script, pass your vars (location, location1 and location2) into the data parameter of the Ajax request, and handle them into your PHP script to save them in your database.
Something like that:
$.ajax({
url: '/script.php', // Your script
type: 'POST',
dataType: 'json',
data: { location: location, location1: location1, location2: location2 }
});
Then, in script.php, you will be able to access location, location1 and location2 by using $_POST["location"].

How to access current data and send data to another php file using ajax?

##ajax function in the php file i need to send id,and two input field values to my updateReq.php file ##
function updateFunction(del,inp1,inp2){
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
}catch (e){
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = "?del=" + del;
queryString += "&inp1=" +inp1;
queryString += "$inp2=" +inp2;
ajaxRequest.open("GET", "updateReq.php" + queryString, true);
ajaxRequest.send(null);
}
in my file i use this part to access ajax function
The ajax function and the bleow code on the same php file
<?php
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<td><input type='text' id='inp1' name='inp1' value='$row[cname]' /></td>";
$display_string .= "<td><input type='number' id='inp2' name='inp2' value='$row[rank]'/></td>";
$display_string .= "<td><a href='#' onclick='deleteFunction($row[id])'>Delete?</a></td>";
$display_string .= "<td><a href='#' onclick='updateFunction( $row[id], $row[cname] ,$row[rank])'>Update?</a></td>";
$display_string .= "</tr>";
}
$display_string .= "</table>";
echo $display_string;
?>
This is my updateReq.php
<?php
// Retrieve data from Query String
include 'config.php';
$id = $_GET['del'];
$inp1 = $_GET['inp1'];
$inp2 = $_GET['inp2'];
// Escape User Input to help prevent SQL Injection
$id = mysql_real_escape_string($id);
$query=mysql_query("update rcategories set cname='$inp1' rank='$inp2' where id='$id'") or die("can not update");
?>
You have a bug in your code..
queryString += "$inp2=" +inp2; change it to queryString += "&inp2=" +inp2;
HTH
Please check your queryString you are using $ instead of &

PDO error displaying query results: Object of class PDOStatement could not be converted to string

So I'm trying AJAX for the first time and I'm stoked! I have a file called ajaxtest1.html and it just has a simple text box where a mileage is entered and then passed on to another file where it receives it, plonks it into the query and sends back the result. Here's ajaxtest1...
<html>
<body>
<script language="javascript" type="text/javascript">// <![CDATA[
function ajaxFunction(){
var ajaxRequest;
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;
}
}
}
// receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.myForm.time.value = ajaxRequest.responseText;
}
}
var miles = document.getElementById('miles').value;
var queryString = "?miles=" + miles;
ajaxRequest.open("GET", "results.php" + queryString, true);
ajaxRequest.send(null);
}
// ]]></script>
<form name="myForm">Miles: <input id="miles" type="text" /> <br /> <br /> <input onclick="ajaxFunction()" value="Query MySQL" type="button" /></form>
</body>
</html>
Then, in results.php. I have
<?php
$hostname = 'host';
$username = 'user';
$password = 'password';
$miles = $_GET['miles'];
try {
$dbh = new PDO("mysql:host=$hostname;dbname=ratetable", $username, $password);
echo 'Connected to database<br />';
$stmt = $dbh->prepare('SELECT * FROM rates WHERE mileage <= :miles ORDER BY mileage DESC LIMIT 1');
$stmt->bindParam(':miles', $miles, PDO::PARAM_INT);
if ($stmt->execute()) {
// get the rowcount
$numrows = $stmt->rowCount();
if ($numrows > 0) {
// match
// Fetch rows
$rowset = $stmt->fetchAll();
}
else {
// no rows
}
}
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Mileage</th>";
$display_string .= "<th>Rate Per Mile</th>";
$display_string .= "<th>Inbound skid rate</th>";
$display_string .= "<th>Inbound truckload</th>";
$display_string .= "</tr>";
while($row_object = array($miles)){
$display_string .= "<tr>";
$display_string .= "<td>$row[mileage]</td>";
$display_string .= "<td>$row[ratepermile]</td>";
$display_string .= "<td>$row[skidinbound]</td>";
$display_string .= "<td>$row[truckinbound]</td>";
$display_string .= "</tr>";
}
echo "Query: " . $stmt . "<br />";
$display_string .= "</table>";
echo $display_string;
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
[UPDATED]
I'm pretty new to using PDO (well, PHP in general and I'm picking it up.)
I am getting the following error:
Catchable fatal error: Object of class PDOStatement could not be converted to string
and this is happening on the line that reads:
echo "Query: " . $stmt . "<br />";
It's connecting to the database fine. Can someone please tell me what could be wrong? I kind of winged it when it came to trying to form the PDO statement so it would handle my query and it's choking on the last bit.
I've updated the PHP code to show you what I've tried.
Thanks for having a look.
Try this in your results.php file:
$stmt = $dbh->prepare('SELECT * FROM rates WHERE mileage <= :miles ORDER BY mileage DESC LIMIT 1');
$stmt->bindParam(':miles', $miles, PDO::PARAM_INT);
You could remove the cast from this line:
$miles = (int) $_GET['miles'];
"Catchable fatal error: Object of class PDOStatement could not be converted to string." Means exactly what it says. The $stmt variable is a PDO object, and you are trying to echo it like it is a string. You can't echo an object, just like you can't just echo an array.
Replace this line
$stmt = $dbh->prepare('SELECT * FROM rates WHERE mileage <= ? ORDER BY mileage DESC LIMIT 1');
With this:
$query_text = 'SELECT * FROM rates WHERE mileage <= ? ORDER BY mileage DESC LIMIT 1';
$stmt = $dbh->prepare($query_text);
And then replace this line
echo "Query: " . $stmt . "<br />";
With this
echo "Query: " . $query_text . "<br />";

Inserting and retrieving data in MySQL using PHP through Ajax

I have a very simple form, containing a textbox and a submit button. When the user enters something into the form, then clicks submit, I would like to use PHP and Ajax (with jQuery) to insert the result of the form into a MySQL database. this result should be displayed on the same page in the form of a table which is updated after every insert.
Can anyone please help?
The code I have used that isn’t working:
ajax.html:
<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;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.value = ajaxRequest.responseText;
}
}
// Now get the value from user and pass it to
// server script.
var name = document.getElementById('name').value;
var age = document.getElementById('age').value;
var wpm = document.getElementById('wpm').value;
var sex = document.getElementById('sex').value;
var queryString = "&name=" +name+ "&age=" + age ;
queryString += "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" +
queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<form name='myForm'>
Name: <input type='text' id='name' /><br/>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value="m">m</option>
<option value="f">f</option>
</select>
<input type='button' onclick='ajaxFunction()'
value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>
ajax-example.php:
<?php
$dbhost = "localhost";
$dbuser = "demo";
$dbpass = "demo";
$dbname = "test_db";
//Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
//Select Database
mysql_select_db($test_db) or die(mysql_error());
// Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
// Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
//build query
$query = "INSERT INTO form2 (name,age,sex,wpm) VALUES ('$name','$age','$sex','$wpm')";;
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
//Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
// Insert a new row in the table for each person returned
$result1=mysql_query("SELECT * FROM form2 WHERE name='$name'");
while($row = mysql_fetch_array($result1))
{
$display_string .= "<tr>";
$display_string .= "<td>$row[name]</td>";
$display_string .= "<td>$row[age]</td>";
$display_string .= "<td>$row[sex]</td>";
$display_string .= "<td>$row[wpm]</td>";
$display_string .= "</tr>";
}
$display_string .= "</table>";
echo $display_string;
?>
$("button_id").click(function () {
$.ajax({
url:"where you should post the data",
type: "POST",
data: the string you should post,
success: function (result) {
//display your result in some DOM element
}
});
});
When you receive the data in the php script make query to the database and get your result
hope this would help
There are many tutorials available on internet for ajax with PHP and Jquery. You can go through any of these and get the desired result.
See an example here http://www.tutorialspoint.com/ajax/ajax_database.htm

Categories