display jQuery ajax variable in original page after popup window close - javascript

I am trying to display data after closing my jQuery window. I know the data is there - I can display it in an alert window after closing my jQuery window. But..., I want that same data displayed in the parent window (for lack of a better term) after the jQuery window is closed. I've been trying to solve this for 3 weeks. Please help!
Lately I've been thinking I need to refresh or reload the parent page? My apologies if "parent page" is the incorrect terminology. What I mean is; the original page from where the jQuery popup window is called.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="//whosgotbooks.com/jquery/jquery-ui-1.10.4.custom.css">
<script src="//whosgotbooks.com/jquery/jquery-1.10.2.js"></script>
<script src="//whosgotbooks.com/jquery/jquery-ui-1.10.4.custom.js"></script>
</head>
<body>
<div id="dialog" title="Google Books Search Results" style="display:none;">
<script>
var book_title;
$(function() {
$( "#dialog" ).dialog({
height: 550, width: 450});
$( ".btn" ).click(function(){
//var book_title = $item['volumeInfo']['title'];
$.ajax({
type: "POST",
url: 'book-meta.php',
//dataType: 'json',
//data: { book_title : 'Success!' },
data: { book_title : $("#returnvalues").val() },
success: function(data)
{
$.post("/wp-content/plugins/book-search-google/book-search-google.php", data);
//$(".btn").load("/wp-content/plugins/book-search-google/book-meta.php", data);
alert(data);
//console.log(data);
//$("#dialog").html(data);
},
error: function(errorThrown){
alert('error');
}
});
$( "#dialog" ).dialog( "close" );
});
});
</script>
<strong><p style="font-size: 16px; text-align: center";>Top 10 Results for "<?php echo #$_POST['q']; ?>"</p></strong>
<strong><p style="font-size: 14px; text-align: center";>choose a book to select as your topic</p></strong>
<table style="width:400px">
<col width="325">
<col width="75">
<?php foreach ($data['items'] as $item) { ?>
<?php for($i =1; $i <11; $i++) { ?>
<tr>
<td>
<strong><u><div style="font-size: 14px";><?php printf($item['volumeInfo']['title'])?></u></div></strong>
<strong>Author: </strong><?php printf( $item['volumeInfo']['authors'][0])?><br />
<strong>Published: </strong><?php printf( $item['volumeInfo']['publishedDate']); ?><br />
<strong>Page(s): </strong><?php printf( $item['volumeInfo']['pageCount']); ?><br />
<strong>Publisher: </strong><?php printf( $item['volumeInfo']['publisher']); ?><br />
<strong>Category: </strong><?php printf( strtolower($item['volumeInfo']['printType']).', '.strtolower($item['volumeInfo']['categories'][0])); ?>
<strong>ISBN: </strong><?php printf( $item['volumeInfo']['industryIdentifiers'][0]['identifier']); ?></td>
<td><p><input type="submit" method="post" name="selectbook" value="Select" class="btn" id="returnvalues"/></p>
<img src="<?php printf( rawurldecode($item['volumeInfo']['imageLinks']['smallThumbnail'])); ?>" />
</td>
<tr><td style="width:420px"><p><strong>Description: </strong><?php printf( $item['volumeInfo']['description']); ?><br /></p></td>
</tr>
</tr>
<?php } } }
else {
?>
<p><strong>Sorry, there were no results</strong></p>
<?php }
/* for testing purposes show actual request to API - REMOVE when finished
$apiRequest = $url;
echo '<p>API request: '.$apiRequest.'</p>'; */ ?>
</table>
</div>
</body>
</html>
<?php
else: //show form and allow the user to check for Google Book search results
?>
<p><form id="searchForm" name="searchForm" method="post">
<fieldset id="searchBox">
<label>Search for a Book:</label>
<input class="text" id="q" name="q" type="text" value="Powered by Google" onfocus="this.value=''; this.onfocus=null;" />
<select id="type" name="type" size="1">
<option selected value="all">Book Title</option>
<option value="isbn">Books by ISBN</option>
<option value="lccn">Books by LCCN #</option>
<option value="oclc">Books by OCLC #</option>
</select>
<input class="submit" id="searchForm" name="submit" type="submit" value="Search" />
</fieldset>
</form></p>
<?php
//end submit isset if statement on line 73
endif;
}
Here is my book-meta.php code (most of it is commented out - from trying different things):
if ( isset( $_POST['book_title'] )) {
// session_start();
// header('Location: '.$_SERVER['REQUEST_URI']);
// header('Location: '.$_SERVER['PHP_SELF']);
// $book_title = $_POST['book_title'];
// $_SESSION['book_title'] = $book_title;
// echo $_SESSION['book_title'];
$book_title = $_REQUEST['book_title'];
// $book_title = (isset($_POST['book_title']))?$_POST['book_title'] : 'not yet';
echo $book_title;
echo "Test within IF statement <br>";
}
//$_SESSION['$book_title'] = (isset($_POST['book_title']) ? $_POST['book_title'] : "");
echo "Test outside IF statement <br>";
Here is how I call book-meta.php:
include 'book-meta.php';
//$_SESSION['$book_title'] = (isset($_POST['book_title']) ? $_POST['book_title'] : "");
echo $book_title;//
I can add additional source code if needed. Please help!

If you want to display your data in your html page I suggest you place a div element with the id you want (let's say "displayTest") in this page. Then, when you get your data in the ajax callback function use the following code:
$( "#displayTest" ).append(data);
instead of:
alert(data);
Hope it helps.

Related

submit form not working/ not reload

i create a form(form1) to search mysql data into table without reload the page using ajax, it's working fine, but when i want to insert data from the second form(formorder) the submit button not refresh or reload.
this my code
index.php
<html>
<head>
<title>Search Data Without Page Refresh</title>
<script type='text/javascript' src='js/jquery-1.4.2.min.js'></script>
</head>
<body>
<center>
<br>
<?php include("koneksi1.php");
$sql="select * from supplier";
$query=mysqli_query($koneksi,$sql);
?>
<form action="" name = "form1">
<select name="namea" style="width:300px; padding:8px;">
<?php
while($data=mysqli_fetch_assoc($query)){
echo "<option value='".$data['id_supplier']."'>".$data['id_supplier']."</option>";
}
?>
</select>
<input type="submit" value="Search" id="search-btn" style="padding:8px;"/>
</form>
<br>
<div id = "s-results">
<!-- Search results here! -->
</div>
<script type = "text/javascript">
$(document).ready(function(){
$('#s-results').load('search.php').show();
$('#search-btn').click(function(){
showValues();
});
$(function() {
$('form').bind('submit',function(){
showValues();
return false;
});
});
function showValues() {
$.post('search.php', { namea: form1.namea.value },
function(result){
$('#s-results').html(result).show();
});
}
});
</script>
</center>
</body>
</html>
search.php
<?php
include("koneksi1.php");
isset( $_REQUEST['namea'] ) ? $name=$_REQUEST['namea'] : $name='';
$name = mysqli_real_escape_string($koneksi,$name);
if( empty( $name )){
echo '<script> alert("Please search something!")</script>';
}else{
$sql = "select * from barang where id_supplier like '%$name%'";
$rs = mysqli_query($koneksi,$sql ) or die('Database Error: ' . mysql_error());
$num = mysqli_num_rows($rs);
if($num >= 1 ){
echo "<div style='margin:10px; color:green; font-weight: bold;'>$num records found!</div>";
echo "<table width='365' border ='0' cellspacing='5' cellpadding='5'>";
echo"<tr><th>RESULTS</th></tr>";
echo "<div class='table-responsive'>";
echo "<table class='table table-hover'>";
while($data = mysqli_fetch_array( $rs )){
?>
<tbody>
<?php
$kuantitas=0;
$kuantitas++;
?>
<form action="aksi.php" method="post" id="formorder">
<tr>
<td><?php echo $data['nama_barang']?></td>
<td><?php echo $data['stok']?></td>
<td><input type="text" name="kuantitas" size="4"></td>
<td><input type="text" name="harga_satuan" id="harga_satuan" size="10"></td>
<td><input type="text" name="ppn" id="ppn" size="3"> %</td>
<td><button type="submit" class="btn btn-success btn-sm" id="add" name="add">ADD</button></td>
</tr>
</form>
<?php }?>
</tbody>
</table>
</div>
<?php
}else{
echo "<tr><th>NO RESULTS</th></tr>";
}
}
?>
the button submit in formorder not working, what wrong with my code???

Display select query results by using jQuery

I'm pretty new to jQuery and I'm practicing with it. I've this html simple page:
<html>
<head>
<title> Testing jQuery
</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="script.js" type="text/javascript"></script>
<link href="mycss.css" rel="stylesheet" type="text/css">
</head>
<body>
<h2 id="myH"> This is a title.</h2>
<br>
<br>
<fieldset>
<legend>Data</legend>
<form name="myForm">
<input type="text" id="firstData" placeholder="Write something in here" \>
<br>
<br>
<input type="text" id="secondData" placeholder="Write something else in here" \>
<br>
</form>
<button id="formButton" value="Confirm">Confirm</button>
</fieldset>
<br><br><br>
<div id="myDiv"></div>
</body>
</html>
This PHP script:
<?php
/* Connection to DB*/
.... CONNECTIONS STUFF.........
$query = " SELECT * FROM table1;";
$results = mysql_query($query);
echo " <table border=\"2\"><tr> <th>ID</th><th>First</th><th>Second</th></tr>";
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td>
<?php echo $row['ID']?>
</td>
<td>
<?php echo $row[ 'First']?>
</td>
<td>
<?php echo $row[ 'Second']?>
</td>
</tr>
<?php
} echo "</table>"; ?>
And finally this js code:
$(function () {
$('#formButton').on('click', function (e) {
var firstData = $('#firstData').val();
var secondData = $('#secondData').val();
var query = 'first=' + firstData + '&second=' + secondData;
// Here I use another php script.
$.get('myData.php', query, function (data) {
$('#myDiv').html(data);
});
});
$('#formButton').on('click', function (e) {
$.ajax({
url: "myquery.php",
type: "POST",
success: function (data) {
$("#myDiv").empty().html(data);
}
});
});
});
Ok , now that I've inserted all the code , the problem is that I can add elements to my database by using myData.php script but I'd like to create a page where in the top you can add elements and when you click on the confirmation button in the bottom (with a query) all the contents of the table are displayed. So I can add elements but I'm not able to display them. I'm new to jQuery and I'm trying to make it work , I've made different researches on the Web but I couldn't find anything that solved my problem. Could please someone help me? Thanks!
You can do both operation by single file myData.php
Put below code right after record inserted in myData.php
$query = " SELECT * FROM table1;";
$results = mysql_query($query);
echo " <table border=\"2\"><tr> <th>ID</th><th>First</th><th>Second</th></tr>";
while($row = mysql_fetch_array($results)) {
?>
<tr>
<td>
<?php echo $row['ID']?>
</td>
<td>
<?php echo $row[ 'First']?>
</td>
<td>
<?php echo $row[ 'Second']?>
</td>
</tr>
<?php
} echo "</table>"; ?>
No need of two ajax call. Remove the second button click jquery code.
On first button click event myData.php file will be called. First record will be inserted in your DB table with your existing code. After it place your code to fetch records from DB. your HTML will be sent in the response and place that HTML in the DIV with your existing jquery code.
you can use jquery load function for it, its very easy for you
http://www.w3schools.com/jquery/jquery_ajax_load.asp
just load a div from there to a div in current page
follow this url for the video tutorial, its very simple, use a div here then enter the id and in the page you are loading, please use another id and load that id into this page div
https://www.youtube.com/watch?v=mtz8MdQXhno
it works in wordpress and will simply work in php
same code

Ajax response not updating in php while loop

I am having a slight problem figuring out why this ajax response isn't updating properly. I have a php while loop which lists gallerys in text format, i am using . It is getting details from the php page but only for one result so essentially when you hover over the name a qtip tooltip box pops up so you can edit the name of the gallery. The problem is it only lists one result for all results in the loop.
PHP & HTML
<?php
$MemberGalleriesQuery = $bapcity->query("SELECT * FROM CroMemberRetailGalleries WHERE UserID='".$_SESSION['user_id']."' ORDER BY GalleryID DESC");
$MemberGalleriesCount = $MemberGalleriesQuery->num_rows;
if ( $MemberGalleriesCount )
{
$BaseHeight = 150;
$GalleriesBoxHeight = $BaseHeight + ( 20 * $MemberGalleriesCount );
echo '
<div id="ManageGalleries" style="height: '.$GalleriesBoxHeight.'px" align="center">
<div id="ManageGalleriesHeader">Manage Galleries</font></div><br><br>
<font color="#000000"><b>Click Gallery To Edit</b></font><br><br>
';
while($GalleryData = $MemberGalleriesQuery->fetch_assoc())
{
echo '>> <b><a class="EditGallery" href="Crowork.Backend/Crowork.EditGallery.php?action=EditGallery&gallerykey='.$GalleryData['GalleryID'].'">'.$GalleryData['GalleryName'].'</a></b> <<<br>';
}
echo '<br><br></div>';
}
$MemberGalleriesQuery->free();
?>
JAVASCRIPT:
//Edit Form When Hovering Over Gallery Name
$('.EditGallery').each(function() {
var link = $('.EditGallery').attr('href'); //Gets link url
$.ajax({ //Make the ajax request
url: link,
cache: false
}).done(function( html ) { //On complete run tooltip code
//Display tooltip code goes here, returned text is variable html
$('.EditGallery').qtip({
content: {
text: html
},
hide: {
fixed: true,
delay: 300
},
style: 'wiki'
});
$('.EditGallery').qtip('click', true);
$(".EditGallery").page();
});
});
CONTENTS OF Crowork.Backend/Crowork.EditGallery.php
if ( isset( $cleanGet['action'] ) && $cleanGet['action'] == 'EditGallery' ){
$MemberGalleriesQuery = $bapcity->query("SELECT * FROM CroMemberRetailGalleries WHERE GalleryID='".$cleanGet['gallerykey']."' AND UserID='".$SessionUserID."' ORDER BY GalleryID DESC");
$MemberGalleriesCount = $MemberGalleriesQuery->num_rows;
if ( $MemberGalleriesCount )
{
$GalleryData = $MemberGalleriesQuery->fetch_assoc();
}?>
<form action="Crowork.Backend/Crowork.EditGallery.php?action=DoEditGallery&gallerykey=<?php echo $GalleryData['GalleryID']?>" method="post">
<input type="hidden" name="GalleryName" value="<?php echo $GalleryData['GalleryName']?>">
<input type="hidden" name="GalleryID" value="<?php echo $GalleryData['GalleryID']?>">
<input type="submit" name="DeleteGallery" value="Delete Gallery">
</form>
<form action="Crowork.Backend/Crowork.EditGallery.php?action=DoEditGallery&gallerykey=<?php echo $GalleryData['GalleryID']?>" method="post">
<table border="0" width="100%">
<tr>
<td colspan="2" align="center"><font size="-1"><b>NOTE:</b> Letters & Numbers Only</font></td>
</tr>
<tr>
<td>Name:</td>
<td><input type="text" name="GalleryName" size="30" value="<?php echo $GalleryData['GalleryName']?>"></td>
</tr>
<tr>
<td align="right" colspan="2">
<input type="hidden" name="OriginalGalleryName" value="<?php echo $GalleryData['GalleryName']?>">
<input type="hidden" name="GalleryID" value="<?php echo $GalleryData['GalleryID'] ?>">
<input type="submit" name="EditGallery" value="Edit Gallery">
</td>
</tr>
</table>
</form>
<?php }?>
PREVIEW:
http://www.bigjohn863.com/mini-upload-form/uploads/ajaxproblem.png
See how all three are the same results.
Try:
$('.EditGallery').each(function()
{
$(this).qtip({
content: {
text: "Loading...",
ajax: {
url:$(this).attr('href'),
type: "GET",
success: function(data, status) {
this.set('content.text', data);
}
}
},
hide: {
fixed: true,
delay: 300
},
style: 'wiki'
});
$(this).qtip('click', true);
});
http://jsfiddle.net/st0j8nLy/
//Edit Form When Hovering Over Gallery Name
$('.EditGallery').each(function() {
var link = $('.EditGallery').attr('href'); //Gets link url
....
everytime you are calling $('.EditGallery'). $('.EditGallery'). is an array, you need to change all references to $('.EditGallery') that is within the loop to $(this):
var link = $(this).attr('href'); //Gets link url
You Might be need to create dynamic id so you can call proper ajax.
please modify your ajax call as below
$gid=$GalleryData['GalleryID'];
echo '>> <b><a onclick="editgalary($gid)" id="EditGallery_$gid" href="Crowork.Backend/Crowork.EditGallery.php?action=EditGallery&gallerykey='.$GalleryData['GalleryID'].'">'.$GalleryData['GalleryName'].'</a></b> <<<br>';
replace this code in while loop.
function editgalary(galaryid){
var link = $('#EditGallery_'+galaryid).attr('href');
//ajax code as it is.
}
try and let me konw

Ajax- fill multiple textboxes for php

I have a html page with a drop down menu, The menu works and onchange calls a function popBox() that too works. Within the function i am using ajax to post the value of the drop down menu into php where it selects form the db. I wish to fill the textboxes in the form "DetailsForm" with the information selected. I currently fill no text boxes and the alert (msg) displays the whole html side of the page in and alert box. Could somebody please help me with my problem. I have tried multiple different variation of ajax and jquery to perform this and after 15hrs on the same function i am starting to get slight frustrated to say the least. Thanks in advance for any help, i do appreciate it.
Here is my code:
HTML
<head>
<link href="../UserTemplate.css" rel="stylesheet" type="text/css"/>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- TemplateBeginEditable name="doctitle" -->
<title>Tours</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"> </script>
<script type="text/javascript">
function popBox(str)
{
$.ajax({
type: "PopulateBoxes.php",
data: { dat: str}
}).done(function( msg ) { //you can also use success
alert( "Data Saved: " + msg );
});
//document.getElementById("txt_Duration").value = <?php Print($Duration); ?>;
//document.getElementById("txt_Vessel_Name").value = <?php Print($Vessel); ?>;
//document.getElementById("txt_Location").value = <?php Print($Location); ?>;
//document.getElementById("txt_Available").value = <?php Print($Available); ?>;
//document.getElementById("txt_Price").value = <?php Print($Price); ?>;
}
</script>
</head>
<body>
<div id="MainDiv">
<div id="Header">
<div id="Logo"><img src="../Scotia Sea Life Logo.png" width="150px" height="110px" alt="Company Logo"/></div>
<div id="NavBar"><ul>
Home Tours About Donate Account
</ul>
</div>
<div id="Title">Tours</div>
</div>
<div id="Content">
<div id="Search">
<div id="SearchDiv">
<form id="SelectTourForm" style="margin:5px;">
<table border="0" align="center" width="100%">
<tr>
<td>
<label style="color:#FFF; font:Georgia, 'Times New Roman', Times, serif; font-size:20px; margin-left:10px; margin-top:25px">Select Tours Details</label></td>
</tr>
<tr>
<td><select name="lst_MonthDrop" style="background-color:#FF9933; color:#FFF; border:none; margin-top:10px; margin- left:10px;" onchange="popBox(this.value);">
<option>Please Select</option>
<?php
include 'populatedrodown.php';
foreach ( $results as $option ) : ?>
<option value="<?php echo $option- >Date; ?>"><?php echo $option->Date; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" name="btn_TourSearch" id="btn_TourSearch" value="Search" style="background:#009300; border-radius:5px; border-color:#009300; color:#FFF;margin-left:5px;" /></td>
</tr>
<tr>
<td></td>
</tr>
</table>
<p> </p>
</form>
</div>
</div>
<div id="DetailsDiv">
<div id="DetailsContent">
<form id="DetailsForm" >
<table border="0" align="center" width="100%">
<tr><td><label style="color:#FFF; font-size:14px;">Tour ID</label> <input type="text" id="Tour_ID" /> </td></tr>
<tr><td><label>Duration</label> <input type="text" id="txt_Duration" /> </td></tr>
<tr><td><label>Vessel Name</label> <input type="text" id="txt_Vessel_Name"/> </td></tr>
<tr><td><label>Location</label> <input type="text" id="txt_Location" /> </td></tr>
<tr><td><label>Date</label> <input type="text" id="txt_Date" /> </td></tr>
<tr><td><label>Available</label> <input type="text" id="txt_Available" /> </td></tr>
<tr><td><label>Price</label> <input type="text" id="txt_Price" /> </td></tr>
</table>
</form>
</div>
</div>
</div>
<div id="Footer">
<div id="FooterLinks"></div>
</div>
</div>
</body>
</html>
PHP
<?php
$q = $_POST['dat'];
$mysql_db_hostname = "localhost";
$mysql_db_user = "root";
$mysql_db_password = "pwd";
$mysql_db_database = "db";
$con = mysql_connect($mysql_db_hostname, $mysql_db_user, $mysql_db_password) or die("Could not connect database");
mysql_select_db($mysql_db_database, $con) or die("Could not select database");
$sql="SELECT * FROM Tour WHERE Date = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
$Duration = $row['Duration'] ;
$Vessel = $row['Vessel_Name'] ;
$Location = $row['Location'] ;
$Available = $row['Available'];
$Price = $row['Price'];
}
mysqli_close($con);
?>
Try to modify you JS code similar to this:
function popBox(selectValue) {
$.ajax({
type: 'POST',
url: "PopulateBoxes.php",
data: { dat: selectedValue },
success: function(serverResponse) {
// after success request server should return response with data
// that will be passed to this callback function as parameter
// and you can use it to fill text boxes:
$('#txt_Duration').val(serverResponse.duration);
}
});
}
Also you should modify your PHP code to return data in JSON:
// At the end you should return selected array. For example:
echo json_encode($dataArray); exit;
As you are using $_POST in your PHP code, you would need to edit the ajax call script.
Type is either GET or POST and page address comes in to the url attribute.
$.ajax({
type: 'POST',
url: "PopulateBoxes.php",
data: { dat: str}
}).done(function( msg ) { //you can also use success
alert( "Data Saved: " + msg );
});
}

How to populate a database list without refreshing webpage

I'm interested in having a search form on the left side of a webpage, and the main content being the rows returned from the database.
Example : www.kijiji.ca
What I want to avoid, is reloading the whole page. Kijiji is not a good example of this, updating the query or changing the results page, updates the entire browser window. Ideally when search parameters are changed, the container with the search results will update, and nothing else. This way the outside information is preserved, and page loading time is reduced.
Would an Iframe be ideal for this? Or perhaps Jquery/ajax can handle this somehow ??
Thanks for the advice.
AJAX is your answer. It stands for Asynchronous Javascript and XML...depending on your development framework, requirements, skill/knowledge and a variety of other factors you'll be implementing it in a variety of fashions.
AJAX is not a language, it is a concept. The idea is to allow asynchronous updates to portions of (or whole) pages on a website/web application. Here's a few resources to start you off:
http://learn.jquery.com/ajax/
http://www.w3schools.com/ajax/
http://www.tutorialspoint.com/ajax/
With a bit more information on your choice of IDE and/or requirements (are you building an ASP/PHP application or a CMS-based website?) we can offer some more pointed help.
You can achieve this easily with AJAX and without any (deprecated) frames.
Look at JQuery for example. It provides all you need to refresh/populate certain areas of your page, without the need to reload the whole page.
Try searching for jquery and ajax.
Further to what has been mentioned here about using AJAX, you'll need to have a server-side back-end that gets the required data from your db and uses a HTTP response to send data back to the client. This could be stored as JSON for instance and you can use that response to populate your search field.
I have python and wsgi set up on an apache server right now for a back-end for instance, but this sort of thing could be implemented through something like php as well.
Ajax is the best bet. try going through http://api.jquery.com/jQuery.ajax/ to learn more.
This is the basic template code:
$.ajax({
type: "GET",
url: "",//type your url
data: {
searchdata: searchdata
},
success: function (response) {
$('#Content').html(response);
}
});
as you see if your content page has a div with id as Content. it would just update that div alone.
You don't even need Ajax for this.
Here is some (admittedly sloppy) code from a recent project. Should get you started. You can add the Ajax later for neat stuff like a reset button, or chained select boxes. Good luck.
This code assumes your page is named index.php (the data is submitted to the same page) Also, the commented out echos are for testing your database connection and that the form data made it to your query. And you probably don't need this query, but there it is anyway. Make a fast test database and give it a try.
HTML:
<div id="formarea">
<form method="post" action="index.php">
Note: All fields are not required for searching<br>
First Name:
<input type="text" name="first"><br>
Last Name:
<input type="text" name="last"><br>
School:
<input type="text" name="edu"><br>
City:
<input type="text" name="cit"><br>
State:
<input type="text" name="st"><br>
<input class="submit" name="submit" type="submit" value="Find">
</form>
</div>
<div id="listarea">
<?php
mysql_connect('database', 'username', 'password') or die(mysql_error());
//echo "Connected to MySQL <br>";
mysql_select_db("hair1") or die(mysql_error());
//echo "Connected to Database <br>";
$first = mysql_real_escape_string($_POST['first']);
$last = mysql_real_escape_string($_POST['last']);
$edu = mysql_real_escape_string($_POST['edu']);
$cit = mysql_real_escape_string($_POST['cit']);
$st = mysql_real_escape_string($_POST['st']);
//echo $first; echo "<br>";
//echo $last; echo "<br>";
//echo $edu; echo "<br>";
//echo $cit; echo "<br>";
//echo $st; echo "<br>";
?>
<?php
if(isset($_POST['submit'])){
$query = "SELECT * FROM hair1 WHERE 1=1 ";
if($first) $query .= "AND fname=\"$first\" ";
if($last) $query .= "AND lname=\"$last\" ";
if($edu) $query .= "AND school=\"$edu\" ";
if($cit) $query .= "AND city=\"$cit\" ";
if($st) $query .= "AND state=\"$st\" ";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<div class='resultbox'><div class='infobox'>";
echo $row['fname'];
echo "</div><div class='infobox'>";
echo $row['lname'];
echo "</div><div class='infobox'>";
echo $row['school'];
echo "</div><div class='infobox'>";
echo $row['city'];
echo "</div><div class='infobox'>";
echo $row['state'];
echo "</div><div class='infobox'>";
echo $row['phone'];
echo "</div><div class='infobox'>";
echo $row['email'];
echo "</div></div>";
}
if ( mysql_num_rows( $result ) > 0 ){
}
else{ echo "<p>Sorry, that search didn't turn up anything. Please check your spelling and try again.</p>";
}}
else{
echo "<p>No Results Found</p>";
}
?>
</div>
CSS:
#formarea {
height: 235px;
width: 280px;
float: left;
clear: left;
text-align: right;
margin-right: 10px;
}
#listarea {
height: 235px;
width: 650px;
overflow-x: hidden;
overflow-y: auto;
float: left;
}
.resultbox {
height: 18px;
width: 100%;
padding-top: 3px;
}
.infobox {
float: left;
padding-right: 5px;
padding-left: 5px;
}
As others have mentioned, AJAX is the best solution for what you requested.
Here is a full example that does what you want. Values in a database will be updated via AJAX, with a response appearing on the page without the page refreshing.
jsFiddle (all working except AJAX)
While jsFiddle cannot demonstrate the AJAX, you can see that in action if you copy/paste the following into two files (three if you break out the javascript into its own file), and edit it to match your own database structure.
Two files are required:
One: index.php (or whatever you wish to call it)
Two: my_php_processor_file.php (if change this name, must also change in the AJAX code block in the javascript
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<style>
</style>
<script type="text/javascript">
//Global var goes here:
editRow = 0;
$(document).ready(function() {
$('#msgbox').dialog({
autoOpen:false,
width:400,
modal:true,
buttons: {
Submit: function() {
var mfn = $('#mfn').val();
var mln = $('#mln').val();
var mem = $('#mem').val();
$('table').find('tr').eq(editRow).find('.fname').val(mfn);
$('table').find('tr').eq(editRow).find('.lname').val(mln);
$('table').find('tr').eq(editRow).find('.email').val(mem);
/*
//Now do the ajax transfer to the server
$.ajax({
type: 'POST',
url: 'my_php_processor_file.php',
data: 'user_id=' +editRow+ '&first_name=' +mfn+ '&last_name=' +mln+ '&email_addy=' +mem,
success:function(recd){
$('#alert').html(recd);
$('#alert').dialog('open');
}
}); //END ajax code block
*/ //Now, close the dialog -- doesn't happen automatically!
$(this).dialog('close');
}, //END Submit button
Cancel: function() {
$(this).dialog('close');
} //END Cancel button
} //END all buttons
}); //END msgbox div (dialog)
$('.editbutt').click(function() {
editRow = $(this).parents('tr').index();
//alert(editRow);
var fn = $(this).parents('tr').find('td').eq(0).find('.fname').val();
var ln = $(this).parents('tr').find('td').eq(1).find('.lname').val();
var em = $(this).parents('tr').find('td').eq(2).find('.email').val();
$('#mfn').val(fn);
$('#mln').val(ln);
$('#mem').val(em);
$('#msgbox').dialog('open');
}); //END editbutt
$('#alert').dialog({
autoOpen:false,
modal:true
});
}); //END document.ready
</script>
</head>
<body>
<table id="tbl">
<tr>
<td>
First Name
</td>
<td>
Last Name
</td>
<td>
Email
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" id="fn1">
</td>
<td>
<input type="text" class="lname" id="ln1">
</td>
<td>
<input type="text" class="email" id="em1">
</td>
<td>
<input class="editbutt" type="button" value="Edit Row">
</td>
</tr>
<tr id="tr2">
<td id="td2a">
<input type="text" class="fname" id="fn2">
</td>
<td id="td2b">
<input type="text" class="lname" id="ln2">
</td>
<td id="td2c">
<input type="text" class="email" id="em2">
</td>
<td id="td2d">
<input class="editbutt" type="button" value="Edit Row">
</td>
</tr>
</table>
<div id="msgbox">
<h2>Edit User</h2>
First Name: <input id="mfn" type="text"><br/>
Last Name : <input id="mln" type="text"><br/>
Email Addy: <input id="mem" type="text"><br/>
</div>
<div id="alert"></div>
</body>
</html>
PHP Processor File: my_php_processor_file.php
<?php
$fn = $_POST['first_name'];
$ln = $_POST['last_name'];
$em = $_POST['email_addy'];
$uid = $_POST['user_id'];
/*
//This is where you use the security features of PHP to strip_slashes, and
//protect html_entities, etc. to guard your database against SQL injection
//attacks, etc. SEE THESE POSTS:
https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php
http://www.tizag.com/mysqlTutorial/mysql-php-sql-injection.php
http://blogs.msdn.com/b/brian_swan/archive/2010/03/04/what_2700_s-the-right-way-to-avoid-sql-injection-in-php-scripts_3f00_.aspx
*/
//Now, update the database:
$success = mysql_query("UPDATE `users` SET `email`='$em', `first`='$fn', `last`='$ln' WHERE `user_id` = '$uid'");
//Now, return a message or something
if (mysql_affected_rows() == -1) {
$output = '<h2>Sorry, database update failed</h2>';
}else{
$output = '<h2>Update successful</h2>';
}
echo $output;
Here are some other simple examples of how AJAX works:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
I think you should go with JQuery ajax
It's as simple as:
var request = $.ajax({
url: //here goes url,
type: "GET",
data: { param : value}, //pass your parameters here
dataType: "html"
});
request.done(function( data ) {
//here you update your main container
$( "#main_container" ).html( data);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});

Categories

Resources