jQuery forms.js with multiple forms per page - php

I would like to submit information to a mySql database using php and ajax.
The page that the info is being sent from (form.php) has multiple forms that are generated from a "while()" loop.
On success, I would a response to update a div above the particular form from which the data was submitted.
I am currently using jQuery and the jquery form plugin.
I have been successful in getting the data to the database, however I am having trouble with the response being sent back to the proper div. I have been successful in getting a response back to a div that is outside of the while() loop. I have not, however, been successful in getting a response back to a div within the loop. I have placed in the code below a div called:
">
Where I would like the note to be placed.
I know that this has everything to do with my javascript function:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() { $('#noteReturn').fadeIn('slow'); }
});
});
</script>
The #noteReturn function does not specify which businesses div it should be placed in.
I hope that this makes sense.
Thank you for your help.
The code is below:
<!-- the form.php page -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/forms.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() {
$('#noteReturn').fadeIn('slow'); }
});
});
</script>
<?php
$query = mysql_query("SELECT * FROM businesses");
while( $row = mysql_fetch_assoc( $query ) ):
$b_id = $row['bid'];
?>
<div class='notes'>
<?php
// query the db for notes associated with business... return notes texts and notes dates
$notesQuery = mysql_query("SELECT business_id, notes, messageDate FROM notes WHERE notes.business_id = $b_id ORDER BY messageDate");
while( $NoteRow = mysql_fetch_assoc( $notesQuery ) ) {
extract($NoteRow);
echo "$notes<br/><span class='noteDate'>$messageDate</span><br />";
} // end while$notesQuery
?>
<!-- this is where i would like jQuery to return the new note -->
<div id="noteReturn<?php echo $b_id; ?>"></div>
<!-- begin note form -->
<form name="noteForm" action="notesProcess.php" method="post">
<input type="text" name="note" />
<input type="hidden" value="<?php echo $b_id ?>" name="bid" />
<input type="submit" class="button" value="Send" />
</form>
</div> <!-- end div.notes -->
<?php
endwhile;
?>
<!-- /////////////////////////////////////////////////////
The page that the form submits to is this (notesProcess.php):
///////////////////////////////////////////////////// -->
<?php
$note = $_POST['note'];
$id = $_POST['bid'];
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if( $result ) {
echo " $note"; }
?>

Change this code:
jQuery('form').ajaxForm({
target: '#noteReturn',
success: function() {
$('#noteReturn').fadeIn('slow');
}
});
To this:
jQuery('form').ajaxForm({
target: '#noteReturn',
dataType: 'json',
success: function(data) {
$('#noteReturn' + data.id).html(data.note).fadeIn('slow');
}
});
And this code:
<?php
$note = $_POST['note'];
$id = $_POST['bid'];
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if($result) {
echo " $note";
}
?>
To this:
<?php
$note = mysql_real_escape_string($_POST['note']);
$id = mysql_real_escape_string($_POST['bid']);
$sql = "INSERT INTO notes (business_id, notes) VALUES ('$id', '$note')";
$result = mysql_query( $sql );
if($result) {
print json_encode(array("id" => $id, "note" => $note));
}
?>
What happened?
The change to the PHP code is making use of PHP's json_encode function to print out the id of the business to which the note was added as well as the actual note text. In the javascript code, I added the dataType of 'json' to tell the script what format of response to expect. Once the request is received in the success callback, the data variable is an object with the values we passed through json_encode. So data.id has the business id and data.note has the new note. Using jQuery's html() manipulation function, the inner html of the div is updated to the latest note. The div selector uses the id we passed, so we can update the corresponding div.
Also, this is slightly off topic, but make sure you always use mysql_real_escape_string when putting values into a query like you are. If you do not use this, your queries will be vulnerable and susceptible to injection attacks, and they are not pretty. If a customer decided to enter a note value of ');DROP TABLE businesses; you'd really feel the pain. Preferably, switch to PDO or MySQLi and use prepared statements, as they are the 'correct' way of doing queries nowadays.

Related

How do I implement a like counter using PHP, jQuery and AJAX?

I am working on creating a like counter for quotes. I am trying to increment the like counter when the user clicks on the like button and display the number of likes.
Problems I encountered:
Like counter gets incremented when I refresh the page (Not because I am actually hit the like button).
I tried implementing jQuery for the updation of the like counter in real time but failed :(
I referred to all the QnA related to this couldn't find the desired solution. I went through this [question]PHP/MySQL Like Button, and made the necessary changes but now there is no updation in the database when I click the button.
This is the code for one quote.
<div class="testimonial text-sm is-revealing">
<div class="testimonial-inner">
<div class="testimonial-main">
<div class="testimonial-body">
<p id="q1">
<?php
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?></p>
</div>
</div>
<div class="testimonial-footer">
<div class="testimonial-name">
<button method="POST" action='' name="like" type="submit" class="like"><b>Like</b></button>
<?php
if(isset($_POST['like'])){
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
<label>
<?php
$link = mysqli_connect("localhost","root","","success");
$sql = "SELECT likes from voted WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
?>
</label>
<button class="btn" id="clipboard" onclick="copyFunction('#q1')"></button>
</div>
</div>
</div>
How do I make the like counter implement when I click on the like button?
How do I implement jQuery and AJAX to this, so that the counter is updated without a page refresh?
Please pardon my poor code structure.
Thanks for any help.
P.S This how a single quote will look like
You need three things for an asynchronous setup like this to work:
Your back-end script to handle ajax requests
Your front-end page
Your JQuery script to send ajax requests and receive data
Your back-end PHP script would look something like this (async.php):
<?php
if(isset($_POST['get_quotes'])) {
$sql = "select quotes from voted where voted.quote_id = 1";
$result = mysqli_query($link,$sql);
$row = mysqli_fetch_array($result);
echo "$row[0]";
}
if(isset($_POST['like'])) {
$link = mysqli_connect("localhost","root","","success");
$sql = "UPDATE voted SET likes = likes+1 WHERE voted.quote_id = 1";
$result = mysqli_query($link,$sql);
}
?>
Your front-end page will include an element with an ID to hook onto with the JQuery, and a button with a class or ID to capture the click event (page.html):
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="core.js"></script>
<body>
<button id="increment-like" value="Like" type="button" />
<p id="like-count">
</p>
</body>
<html>
Finally, your JavaScript file should look something like this, for a basic ajax request using JQuery (core.js):
$(document).ready(function() {
// initially grab the database value and present it to the view
$('#like-count').text(getDatabaseValue());
$('#increment-like').on('click', function() {
incrementDatabaseValue();
});
});
function getDatabaseValue() {
$.post("async.php",
{
get_quotes: true
},
function (data, status) {
// check status here
//return value
return data;
});
}
function incrementDatabaseValue() {
$.post("async.php",
{
like: true
},
function (data, status) {
// check status here
// update view
$('#like-count').text(getDatabaseValue());
});
}
I haven't tested this code but it should be clear and detailed enough to get you on the right track.

mysqli_query() WHERE - insert data

i'm new to php and what im trying to do here is add rating +1 for specific id (1,10,30....) whenever i press arrow up button.
I need to add id value (echo $row['id'];) to mysqli_query() somehow.
Can someone help please? :)
<?php include("db.php")?>
<?php
$sql = "SELECT * FROM gifs";
$result = mysqli_query ($db,$sql);
?>
<?php
//Fetch data from database
if ($result -> num_rows >0){
while($row = mysqli_fetch_array($result)){
?>
<div><?php echo $row["name"];?></div>
<p id="<?php echo $row['id'];?>">
<?php echo $row['copygif'];?></p>
$add = $row['id']; //i know this dosnt work...
<i onClick="<?php mysqli_query($db,"UPDATE gifs SET rating = rating + 1 WHERE id= $add ");?>"></i>
How do i translate ($row['id'];) into mysqli_query( id = ?)
Thank You
Very quickly cobbled together to show how you might accomplish your goal. You cannot simply embed the sql query as you did - the PHP code runs when the page loads ( it being server side code ) so will execute before you see any content on the page. The event click is a clientside event so you need some mechanism to send the request from the client to the server - typically one might use ajax or, as here, a form submission. The code below was not tested so you might find little mistooks but the idea should help solve the issue - this though is only one method you could employ.
<?php
/* include db connection */
include('db.php');
/* Process form submission */
if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['id'] ) ){
$id=$_POST['id'];
/* sql query for prepared statement */
$sql='update gifs set rating = rating + 1 where id=?;';
/* prepare the sql query */
$stmt=$db->prepare( $sql );
if( $stmt ){
/* bind the placeholder to the id & execute */
$stmt->bind_param('i',$id);
$result=$stmt->execute();
} else {
exit( 'error: failed to prepare sql' );
}
}
/* select recordset for display */
$sql = "select * from `gifs`;";
$result = $db->query( $sql );
?>
<!doctype html>
<html>
<head>
<meta charset='utf-8' />
<title>gifs</title>
<script>
/* assign event listeners to `i` elements */
document.addEventListener('DOMContentLoaded',function(){
var form=document.forms['gifs'];
var id=form.querySelector('input[type="hidden"][name="id"]');
var col=Array.prototype.slice.call( form.querySelectorAll('i.vote') );
col.forEach(function(node){
node.onclick=function(e){
/* set the value of the hidden field to the data-id value of current `i` */
id.value=this.dataset.id;
form.submit();
}.bind( node );
});
},false );
</script>
</head>
<body>
<!-- add a basic form, using POST -->
<form name='gifs' method='post'>
<!-- hidden field for ID value -->
<input type='hidden' name='id' />
<?php
/* display recordset and create `i` elements that will register vote click */
if( $result->num_rows > 0 ){
while( $row = $result->fetch_object() ){
echo "
<div>{$row->name}</div>
<p id='{$row->id}'>{$row->copygif}</p>
<i class='vote' data-id='{$row->id}'>vote</i>";
}
}
?>
</form>
</body>
</html>
yes as #RamRaider mentioned in the comment above you may need to bind a function on up arrow button and pass the $row['id'] in i, and onclick on the button you can send this id via ajax to server and do what you to. Example may look like,
<?php while($row = mysqli_fetch_array($result)){
?>
<div><?php echo $row["name"];?></div>
<p id="<?php echo $row['id'];?>">
<?php echo $row['copygif'];?></p>
$add = $row['id'];
<i onClick="upButtonClick($row['id'])"></i>
<?php } ?>

PHP & jQuery - Create two different textfields with autocomplete having different lists of data retrieved from the database

Customer textfield with autocomplete from database
I succeeded to create one Customer textfield with autocomplete to display customers which start by the text being typed.
index.php for one textfield
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#customer" ).autocomplete({
source: "../phpfiles/search.php",
});
});
</script>
<div class="ui-widget">
<!-- action='./../customer_report_request' -->
<form id="customer_report_request" name="customer_report_request" method="post">
<table>
<tr>
<th colspan='2'>Search Customer</th>
</tr>
<tr>
<td>
<label>Customer: </label>
<input name="customer" id="customer" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_customer_request">
</td>
</tr>
</table>
</form>
</div>
<?php
//Display the list of customer details
if(isset($_POST['send_customer_request']))
{
include 'db.php'; //connection
$query = "SELECT * FROM customer WHERE Company_Name = '".$_POST['customer']."'";
$customer_result = $db->query($query);
$count_customer = $customer_result->num_rows;
if($count_customer>0)
{
echo"<div>";
echo "<table>";
echo"<tr>";
echo"<th>Company_Name</th>";
echo"<th>VAT_Registration</th>";
echo"<th>Contact_First_Name</th>";
echo"<th>Contact_Last_Name</th>";
echo"<th>Email</th>";
echo"</tr>";
while ($row = $customer_result->fetch_assoc())
{
echo"<tr>";
echo"<td>".$row['Company_Name']."</td>";
echo"<td>".$row['VAT_Registration']."</td>";
echo"<td>".$row['Contact_First_Name']."</td>";
echo"<td>".$row['Contact_Last_Name']."</td>";
echo"<td>".$row['Email']."</td>";
echo"</tr>";
}
echo "</table>";
echo"</div>";
}
$db->close();
}
?>
Search.php for one textfield
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from customer table
$query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with
while ($row = $query->fetch_assoc()) {
$data[] = $row['Company_Name'];
}
//return json data
echo json_encode($data);
?>
The problem is I want to use a single search php file to cater for other queries.
For example:
If a word is typed in the Contact textfield, the query will be
"SELECT * FROM Contact...."
If a word is typed in the Customer textfield, the query will be
"SELECT * FROM Customer...."
Both index.php and search.php were modified to achieve this.
Modified part in index.php
A jQuery variable, component_name was defined. On change from the index.php file, the customer texfield will send the variable to search.php file using a POST method so that it can be identified and used for query purposes.
The contact textfield can be either in the same form in the index.php file or in another php file.
<script>
$(function() {
$( "#customer" ).autocomplete({
var component_name= "customer";
source: "../phpfiles/search.php",
minLength: 1,
change: function(event, ui)
{
$.post("../phpfiles/search.php", data{post_data: component_name});
}
});
});
</script>
Modified search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query="";
if($_POST['post_data']=="customer")
{
$query = $db->query("SELECT * FROM customer WHERE Company_Name LIKE '".$searchTerm."%' ORDER BY Company_Name ASC"); //Starts with
while ($row = $query->fetch_assoc())
{
$data[] = $row['Company_Name'];
}
//return json data
echo json_encode($data);
}
?>
Can anyone help me to achieve this?
I used these links for the jquery-ui and jquery api parts:
api.jquery.com
jqueryui.com
This may be a little complicated ad I hope it helps. Your example does not provide any example data or schema to your DB, so I had to make a number of guesses. You'll need to adjust.
Consider if you have different input fields, you could have:
HTML
<div class="ui-widget">
<form id="customer_report_request" name="customer_report_request" method="post">
<table>
<tr>
<th colspan='2'>Search Customer</th>
</tr>
<tr>
<td>
<label>Customer: </label>
<input class="entry-field" name="customer" id="customer" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_customer_request">
</td>
</tr>
<tr>
<td>
<label>Contact: </label>
<input class="entry-field" name="contact" id="contact" value='' required>
</td>
<td>
<label>Submit: </label>
<input value="Send" name="send_customer_request" type="submit" id="send_ccontact_request">
</td>
</tr>
</table>
</form>
</div>
JavaScript
$(function() {
$(".entry-field").autocomplete({
source: function(req, resp) {
// determine which field we're working with
var type = $("this").attr("id");
// collect the entry in the field
var term = req.term;
// Prepare our response array
var responses = [];
// PErform POST Request to our Search and accept JSON results
$.ajax({
url: "../phpfiles/search.php",
data: {
t: type,
q: term
},
type: "POST",
dataType: "JSON",
success: function(results) {
$.each(results, function(key, val) {
responses.push(val);
});
}); resp(responses);
},
minLength: 1
}
});
$("#customer_report_request").submit(function(e) {
e.preventDefault();
if ($("#customer").val().length) {
// perform POST to a PHP search for that specific customer details
} else {
// performn a post to a PHP search for that specific contact details
}
// populate result DIV on page with resulting data from POST
});
});
PHP: search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'bobo';
$dbPassword = 'rodnik';
$dbName = 'training';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
// get search query
$searchTerm = $_POST['q'];
// get search type
$searchType = $_POST['t'];
//get matched data from customer table
if($searchType == "customer"){
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT * FROM customer WHERE Company_Name LIKE '?%'");
} else {
/* create a prepared statement */
$stmt = $mysqli->prepare("SELECT * FROM customer WHERE Contact_Name LIKE '?%'");
}
/* bind parameters for markers */
$stmt->bind_param("s", $searchTerm);
/* execute query */
$stmt->execute();
/* instead of bind_result: */
$result = $stmt->get_result();
while ($row = $results->fetch_assoc()) {
if($searchType == "company"){
$data[] = $row['Company_Name'];
} else {
$data[] = $row['Contact_Name']
}
}
//return json data
header('Content-Type: application/json');
echo json_encode($data);
?>
So there is a lot going on. Will start with your PHP. It was vulnerable to SQL Injection, so I made use of MySQLi Prepare to protect things. We are expecting data to be posted to this script, and we're expecting to conditions: query and type. If we do not get a type, we can set defaults. Might want to add a check for query, but it should always have 1 character.
We get this data to our Search script using the function method for the source option. See more: http://api.jqueryui.com/autocomplete/#option-source
Function: The third variation, a callback, provides the most flexibility and can be used to connect any data source to Autocomplete. The callback gets two arguments:
A request object, with a single term property, which refers to the value currently in the text input. For example, if the user enters "new yo" in a city field, the Autocomplete term will equal "new yo".
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data. It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
So with this, we can add to our $.ajax() call and make use of the error callback. Basically, we've end up sending an empty array back to response.
So we send a send a search term to PHP, we get JSON array data back, we pipe this into our own array to send back to response, and the user will get a list of results.
It's still a little clunky and that's ok if that's what you're users are used to. You can slim it down and also categorize your results. This way you can have one search field. Also once something is selected or the field is change, you can then use AJAX again to pull those details from another PHP that harvests all the data from the DB. This would result in not having to wait for the page to load again etc.
I hope this answer your question and I suspect it will raise more too. Keep searching around, there are lots of answers. Sometimes it's easier to break a big problem down into smaller single questions than to tackle the whole.

using ajax to get further mysql data using data already retrieved fro database

I'm trying to build a product catalog where clients can select a product and be presented with product specifications and price. now the first thing i do is query all the products in the database omnicon_prod. from there i build an unordered list of items like such
$query = "SELECT name, id, price, image, cost_per FROM products";
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
echo '<li class="product" style="list-style:none;margin-left:10px;margin-right:10px; width:150px;float:left;" id="'.$row['id'].'">
<img class="productImage" style="background-color:#f2f2f2;width:150px;padding:10px;float:left;" src="'.$row['image'].'main-image.jpg">
<div class="productText" style="width:100%;text-align:center;">
<div class="price" style="color:#fca204;font-weight:500;font-size:20px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['price'].' <span style="color:#959595; font-size:14px; font-weight:100;">/'.$row['cost_per'].'</span>
</div>
<div class="name" style="color:#959595;font-weight:100;font-size:14px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['name'].'
</div>
</div>
</li>';
}
What i would like to do now is attach an anchor to each list item and should the client select an item that comes from the database they would be presented with further information such as the description etc. now i know this should be done with ajax but i'm not sure how as i am relatively new to it. I would like to trigger the ajax possibly by using the onClick even on an ancho tag. this is what i have tried thus far.
the ajax
function ajaxfunction(productID)
{
$.ajax({
url: 'php-includes/products.php?productID=' + productID,
success: function(data) {
$("#productSpec").html(data);
}
});
}
the products.php page
<?php
include_once "connect.php";
$query = "SELECT name, price, image, cost_per FROM products WHERE `id` = ". mysqli_real_escape_string($_GET["ProductID"]);
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
//the content from the database that matches the id of the selected item
}
?>
please can someone help me with regards to where i'm going wrong and if it's wise to use an anchor tag to trigger this event. I basically adopted and tried to incorporate the dynamic multi-level select form option into one that uses a list to grab data...
For the ajax call you can check out these pages here and here
Basically you add the data you want to send (object or string) as a parameter.
Thanks Ruben i managed to figure it out hehe. i'd like to share the final result. if there are any errors or security risks please advise me as to how i could improve the code...
The Quote.php exerpt
<?php
include_once "php_includes/connect.php";
$query = "SELECT name, id, price, image, cost_per FROM products";
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
echo '<li class="product" style="list-style:none;margin-left:10px;margin-right:10px; width:150px;float:left;" id="'.$row['id'].'">
<img class="productImage" style="background-color:#f2f2f2;width:150px;padding:10px;float:left;" src="'.$row['image'].'main-image.jpg">
<div class="productText" style="width:100%;text-align:center;">
<div class="price" style="color:#fca204;font-weight:500;font-size:20px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['price'].' <span style="color:#959595; font-size:14px; font-weight:100;">/'.$row['cost_per'].'</span>
</div>
<div class="name" style="color:#959595;font-weight:100;font-size:14px;font-family: "Conv_Geogtq-Th", sans-serif;">'.$row['name'].'
</div>
</div>
</li>';
}
?>
THE AJAX SCRIPT
<script>
$(".product").on('click',function(){
the_id = $(this).attr('id');
$.ajax({
type: "POST",
url: "php_includes/productspec.php?id=" + the_id,
success: function(data){
$("#productSpec").html(data);
}
});
});
</script>
THE productspec.php PAGE
<?php
include_once "connect.php";
$productid = mysqli_real_escape_string($db_connect, $_GET['id']);
$query = "SELECT * FROM products WHERE `id` = " . $productid;
$result = mysqli_query($db_connect,$query);
while($row = mysqli_fetch_assoc($result)) {
echo '<p>'.$row['id'].'</p>'; //just a test result i'd like to receive
echo '<p>'.$row['name'].'</p>'; //just a test result i'd like to receive
echo '<p>'.$row['price'].'</p>'; //just a test result i'd like to receive
}
?>
thanks so much Ruben. I really appreciate the help you've given me and that you provided the tools to help me figure it out myself. I don't think i'll ever forget how to do this again hahaha. i'll mark your previous post as the answer!

Select from mysql is not working in jQuery fancybox

Fancybox script POST my form data to go.php page then open go.php in fancybox iframe
<script>
$(document).ready(function() {
$("#fancybox-manual-b").click(function() {
$.post('go.php', $(this).parent().serialize())
.done(function() {
$.fancybox.open({
href : 'go.php',
type : 'iframe',
padding : 5
});
});
});
});
</script>
<select name="country">
<option value="US">US</option>
<option value="EU">EU</option>
</select>
<input type="button" value="Calculate" id="fancybox-manual-b"/>
in go.php, I receive the POST data from the form correctly and when I try to insert this data into DB, it's been inserted correctly too!
But now I want to select * from my DB table to echo all the data in the table where column = POST data, but this query doesn't work!
<?php
$country = $_POST[country];
mysql_query("INSERT INTO calculator (country) VALUES ('$country')"); //Works Correctly
$result = mysql_query("SELECT * FROM calculator WHERE country='$country' ORDER BY ID ASC");
while($row = mysql_fetch_array($result)){
echo $row['ID']." ".$row['country'];
} //Nothing appear
?>
Please checkout this method,
$country = $_POST[country];
if(mysql_query("INSERT INTO calculator (country) VALUES ('$country')"));
{
$result = mysql_query("SELECT * FROM calculator WHERE country='$country' ORDER BY ID ASC");
while($row = mysql_fetch_array($result)){
echo $row['ID']." ".$row['country'];
}
}
I used the same code you shared. But added an additional if loop on mysql_query part. It will make sure your select works after data being inserted.
We have to use jquery ajax to send form data to the php page with POST method then receive back any printed data from the php page in the ajax instead of the console.
We will open the fancybox iframe into ajax success instead of the console.
<script type="text/javascript">
$(document).ready(function() {
$("#fancybox-manual-b").click(function() {
$.ajax({
type: 'POST',
url: 'go.php',
data: $(this).parent().serialize(),
success: function(data){
$.fancybox(data);
},
fail:function(data){console.info(data)}
});
});
});
</script>

Categories