Inserting and retrieving data in MySQL using PHP through Ajax - php

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

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 &

Why wont this ajax script work on wamp localhost

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;

passing checkbox ID to another php file

let's say i'm generating some sort of html table (from mysql queried data) with a checkbox at each row with something like
$display_string = "<form action=\"delete.php\" method=\"post\">";
$display_string .= "<div><input type=\"button\" VALUE=\"Button1\"></div>";
$display_string .= "<div><input type=\"button\" VALUE=\"Button2\"></div>";
while($row = mysql_fetch_array($qry_result)){
$display_string .= "<tr onmouseover=\"this.className = 'hlt';\" onmouseout=\"this.className = '';\">";
$display_string .= "<td class='blank'><input type=\"checkbox\" /></td>";
$display_string .= "<td class='data'>" . $row['first_name'] . "</td>";
$display_string .= "<td class='data'>" . $row['last_name'] . "</td>";
$display_string .= "<td class='data'><a href='" . $row['email'] . "'>" . $row['email'] . "</a></td>";
etc...
etc...
$display_string .= "</form>";
what i'd like to happen now, after various checkboxes are selected are two things:
1) for example, call delete.php when Button1 is clicked to delete the selected rows.
2) some other php file called when Button2 is clicked
I have access to $row['ID'] which I can use to name each checkbox, i'm just not sure how to incorporate it since i'm new to php
UPDATE
The following seems to work for my purposes
I've got the following html-
<form name='myForm' method=\"post\" >
<input type=\"submit\" onClick=\"deleterow(document.myForm)\" VALUE=\"Delete ROWs\">
while($row = mysql_fetch_array($qry_result)){
<input type=\"checkbox\" name='rows' value=" .$row['ID']. "/>
Javascript is as follows-
<script language=\"javascript\" type=\"text/javascript\">
function deleterow(form){
if (!confirm(\"Are you sure you want to delete?\")) return false;
var queryString = \"?ID=\";
for (var i = 0; i < document.myForm.rows.length; i++) {
if (document.myForm.rows[i].checked) {
ID = document.myForm.rows[i].value;
ID = ID.slice(0, -1);
queryString += ID;
queryString += \"-\";
}
}
queryString = queryString.slice(0, -1);
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;
}
}
}
var ajaxRequest; // The variable that makes Ajax possible!
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open(\"GET\", \"delete_row.php\" + queryString, true);
ajaxRequest.send(null);
confirm('Delete successful!');
}
then with delete_row.php you can do all you need to with a mysql query, and new data can be sent back and displayed with
<div id='ajaxDiv'></div>
To get a clear code I suggest you to avoid two buttons firing two several actions. Instead use a simple javascript method to append a parameter to the submitted form to get rid of what button has been pushed.
<script type="text/javascript">
function submitForm( act ){
$('#act').val(act);
$('#myForm').submit();
}
</script>
<form id="myForm" ... >
<input type="hidden" id="act" value="" />
<button onClick="submitForm(1)">1</button>
<button onClick="submitForm(2)">2</button>
</form>
this is just an example (using jquery).
About your second answer (checkboxes):
<input type="checkbox" name="selectedboxes[]" value="someIdHere" />
when the form is submitted you'll receive an array "selectedboxes" as a param in which you get checked checkboxes.
You can do it changing the Form action, for example if you click BUTTON 1 it will change the action to DELETE.PHP, take a look to this post:
Changing the action of a form with javascript/jquery
They use JQuery and they have multiples answer how to do it

Categories