I need the jquery script for the following
while typing inside the text field, the 'Load' text need to be displayed near the text field.
If i stop typing the 'Load' text need to change as 'Del'
If click this 'Del' Text the text field should be cleared.
In the mean time i need to display the search result for the entered text.
For this i used the following script
$("#lets_search").keyup(function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
Here is the html part of the file
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
Search:
<div> </div>
<div style="float:left; width:250px;">
<div style="background-color:#fff; padding:3px; width:200px; float:left; border-left:1px solid #eee; border-top:1px solid #eee; border-bottom:1px solid #eee;">
<input name="str" id="str" type="text" style="border:0px; width:150px;">
<div style="float:right; padding-top:3px;" id="loader">Load</div>
</div>
</div>
</form>
<div id="search_results"></div>
In this <div style="float:right; padding-top:3px;" id="loader">Load</div>
I have to display the text (del, Loading etc...)
Please do the needful. Thanks
I think the best way to do this is with a setTimeout, like so:
var pTimeout = null;
$("#lets_search").keyup(function()
{
var value = $('#str').val();
$('#loader').text('Loading...').unbind('click');
if(pTimeout) clearTimeout(pTimeout);
pTimeout = setTimeout(function () { GetResult(value); }, 50);
});
function GetResult(value)
{
$.post('db_query.php',{value:value}, function(data){
pTimeout = null;
$('#loader').text('del').click(function () {
$("#search_results").empty();
$('#str').val('');
});
$("#search_results").html(data);
});
}
There is always a better way of doing it, but must give you the idea.
PS I did not test the code :)
var searchTimeout = null;
$("#str").keyup(function() {
// Clear any existing timeout
if (searchTimeout) {
clearTimeout(searchTimeout);
}
// Put "Load" text in
$('#loader').html('Load');
// Set a timeout for end of typing detection
searchTimeout = setTimeout(function() {
$('#loader').html('Del');
}, 500);
// Get the value from the text field and send it to the server
var value = $(this).val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
});
// Clears the search box value
function clearSearch() {
$("#str").val('');
};
Related
I was trying to parse data to my controller so I can insert it into the database using JQuery and it was returning null. It's for a review star system so doesn't use conventional form fields however the network tab in inspect elements shows that data is actually posted to the controller just, not able to read it for some weird reason.
Update: The data is being inserted fine on desktop however the confirmation (flashdata) message is shown correctly not sure why. Additionally on mobile view no data or message is shown. Does anyone know why? I have updated the code below..
Here's the code from my view:
<?php if($this->session->flashdata('review_submitted')){ ?>
<div class="alert alert-success alert-dismissible container show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<strong>Thank you!</strong> Your review has been submitted.
</div>
<?php } ?>
<form id="myForm" name="myForm">
<br>
<div class="form-group text-left div-style">
<h3 style="font-family: MontserratLight;letter-spacing: 2px; line-height: 32px;">Full Name <b>*</b></h3>
<input name="name" class="form-control" style="background: #f7f7f7; border: 1px solid #801424;" required />
</div>
<div class="rate">
<div id="1" class="btn-1 rate-btn"></div>
<div id="2" class="btn-2 rate-btn"></div>
<div id="3" class="btn-3 rate-btn"></div>
<div id="4" class="btn-4 rate-btn"></div>
<div id="5" class="btn-5 rate-btn"></div>
</div>
<script>
$(function(){
$('.rate-btn').hover(function(){
$('.rate-btn').removeClass('rate-btn-hover');
var therate = $(this).attr('id');
for (var i = therate; i >= 0; i--) {
$('.btn-'+i).addClass('rate-btn-hover');
};
});
$('.rate-btn').click(function(){
var therate = $(this).attr('id');
var dataRate = 'rate='+therate; //
$('.rate-btn').removeClass('rate-btn-active');
for (var i = therate; i >= 0; i--) {
$('.btn-'+i).addClass('rate-btn-active');
};
$('#myForm').on('submit', function(e){
var url = "<?php echo base_url(); ?>index.php/reviews/add_review";
// $('#myForm').append(therate);
var dataPost = $('#myForm').serialize() + "&rate=" + therate;
$.ajax({
type : "POST",
url : url,
data: dataPost,
success:function(){
}
});
});
});
});
</script>
and using the controller I simply use the following to get the data and add it to the database:
public function add_review(){
$name = $this->input->post('name');
$rating = $this->input->post('rate');
$dataDB = array(
'full_name' => $name,
'rating' => $rating
);
if($this->functions->submit($dataDB)){
$this->session->set_flashdata('review_submitted', true);
redirect(base_url() . 'reviews/index', 'refresh');
}
}
Here's some CSS that I used, perhaps the problem is to do with the mobile browser not having a cursor?
.rate{
width:245px; height: 40px;
margin-bottom:0px;
}
.rate .rate-btn{
width: 45px; height:40px;
float: left;
background: url(rate-btn.png) no-repeat;
cursor: pointer;
cursor:hand;
pointer-events: auto;
}
.rate .rate-btn:hover, .rate .rate-btn-hover, .rate .rate-btn-active{
background: url(rate-btn-hover.png) no-repeat;
}
When passing data through ajax, I think it is better to use JSON dataType. Reform the data type (string -> data object). Besides, I don't think it is really necessary to concat the 'to-be-sent' data into a string.
If you want dynamic data to be sent, you can push elements by condition
$.ajax({
type : "POST",
dataType: 'text' //it is not necessary if you are not returning any data (if you return json, put 'JSON'),
url : "<?php echo base_url(); ?>index.php/reviews/add_review",
data: dataRate, //change to {key:value,key:value}
success:function(data){
}
});
This is just to address your issue with your AJAX Posted Values not appearing where you are expecting them ONLY.
There are a zillion ways you can code this but here is just one which I have changed about to perform debugging. Even I learned a new trick doing this.
Just Nit Picking but what stuck out when reading your code is your use of therate when everywhere else in your JS you use camel case so it should be theRate.It's a good idea to choose a standard and stick to it.
Plus you had what appeared to be nested events in your JS. Some attempt at getting theRate to work correctly? Anyway...
First things. Get back to something basic and work your way back up. (Although in this case I didn't strip your view back to bare bones, but I did with your controller.
Your View.
I had to change this up a bit and hopefully the comments explain things.
I called it rating_view.php
<form name="my-form" id="my-form">
<div class="rate">
<div id="1" class="btn-1 rate-btn">1</div>
<div id="2" class="btn-2 rate-btn">2</div>
<div id="3" class="btn-3 rate-btn">3</div>
<div id="4" class="btn-4 rate-btn">4</div>
<div id="5" class="btn-5 rate-btn">5</div>
</div>
<input type="submit">
</form>
<!-- Added for viewing debug response -->
<div id="json-debug-output"></div>
<!-- Some styles added as non were provided -->
<style>
.rate-btn-hover {
background: blue;
}
.rate-btn-active {
background: yellow;
}
</style>
<script src= <?= base_url('assets/js/jquery_v3.4.1.js'); ?>></script>
<script>
$(document).ready(function () {
// Define your Dom Elements ONCE for efficiency etc
let domRateButton = $('.rate-btn');
let domMyForm = $('#my-form');
let theRate = 0; // Declares this as a Global Var.
let domJsonDebugOutput = $('#json-debug-output');
// Hover
domRateButton.hover(function () {
domRateButton.removeClass('rate-btn-hover');
let theRate = $(this).attr('id');
for (let i = theRate; i >= 0; i--) {
$('.btn-' + i).addClass('rate-btn-hover');
}
});
// Click
domRateButton.click(function () {
console.log('Rating Button Clicked');
theRate = $(this).attr('id');
domRateButton.removeClass('rate-btn-active');
for (let i = theRate; i >= 0; i--) {
$('.btn-' + i).addClass('rate-btn-active');
}
});
// Submit
domMyForm.on('submit', function (e) {
e.preventDefault(); // This was missing
console.log('Posting Rate = ' + theRate);
$.ajax({
type: "POST",
// dataType: 'text',
dataType: "json",
url: "<?php echo base_url(); ?>reviews/add_review",
data: {'act': 'rate', 'post_id':<?= $post_id; ?>, 'rate': theRate},
success: function (data) {
let debugData = JSON.stringify(data);
domJsonDebugOutput.text(debugData); // Display in our Debug Div
},
error: function (data) {
let debugData = JSON.stringify(data);
domJsonDebugOutput.text(debugData); // Display in our Debug Div
}
});
});
});
</script>
Note in the AJAX the changes to dataType from text to json. Also note that data is an array.
I also changed the scope of theRate from local to a global so it was "findable" amongst the functions.
NOT SURE how your form was setup but I added e.preventDefault(); to prevent the form submitting for testing.
Personally I cringe at having PHP vars embedded in any JS code and I usually have my JS as external files and pass in the values from PHP by reading them using JS but that's got it's Pros and Cons as well. So I left that alone for the sake of not going too far with this.
For your Controller - Called Reviews.php
public function show() {
$data['post_id'] = 1; // This comes from somewhere
$content = $this->load->view('rating_view', $data, TRUE);
echo $content;
}
/**
* Called by AJAX
* Do we need to test this is only called by AJAX?
*/
public function add_review() {
// Return everything that was sent for debugging
echo json_encode($this->input->post());
// var_dump($this->input->post());
exit();
}
So here I just had a method show() show the form and the add_review to simply bounce back what was sent. You can do all sorts of things with this. One nice aspect in this case is you do not need to use console.log) as you can view it all on the page (BUT ONLY FOR DEBUGGING). It's another option.
So have a play with that and start making changes to your code and see what works. Remember - get back to basics and pick on the bit that isn't working.
Next you will find you might be getting tripped up on your redirect. But that's for another post.
hai iam trying to place hover in an dynamic image have to show a dynamic div, if remove mouse div has to be hidden, if i over to the div after hover on image div needs to remain visible if i move out from the div it has to be hidden i tried something like this, but not working as expected, If i over to image div appears if i place mouseout tag there it hides the div once i remove the mouse couldn't use the options in the div, if i place the mouse out in div once i remove the mouse from image the div not closing, sorry for bad english as solutions for this case?
<img onmouseover="GoView_respond(<?php echo $print->Friend_id;?>);" onmouseout="ExitView_respond_one(<?php echo $print->Friend_id;?>);">
<div class="respond_request" style="display:none;" id="pending_req_<?php echo $print->Friend_id;?>" >
<p class="user_details" onmouseout="ExitView_respond(<?php echo $print->Friend_id;?>);">
</div>
<script>
function GoView_respond(id){
console.log('hovering');
document.getElementById("pending_req_"+id).style.display="block";
}
var cl=0;
function ExitView_respond(id){
console.log('not hovering');
if(cl!=1){
document.getElementById("pending_req_"+id).style.display="none";
}
}
</script>
Well, there are various ways to achieve this.
You could for example trick by setting a little timeout that will allow the mouse to reach the user details html node and vice-versa.
Let me be more explicit, according to your case
<?php
class Friend
{
public $Friend_id;
public $Friend_details;
public $Friend_image;
public function __construct($id, $details, $image){
$this->Friend_id = $id;
$this->Friend_details = $details;
$this->Friend_image = $image;
}
}
$print = new Friend(1, 'The very first user', 'http://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
?>
<img class="user_image" id="user_image_<?php echo $print->Friend_id; ?>" src="<?php echo $print->Friend_image; ?>" alt="some image" />
<div class="user_details" id="user_details_<?php echo $print->Friend_id; ?>">
<h5>User details</h5>
<?php echo $print->Friend_details; ?>
</div>
<style>
.user_details {
display: none;
background-color: lightgray;
width: 250px;
padding: 15px;
}
</style>
<script>
var userImages = document.getElementsByClassName('user_image');
for(var i = 0; i < userImages.length; i++){
var
userImage = userImages[i],
userId = userImage.id.replace('user_image_', ''),
thisUserDetails = document.getElementById('user_details_' + userId),
mouseOutTimeout = 100, // Here is the trick
mouseTimer = null; // Needed in order to hide the details after that little timeout
userImage.addEventListener('mouseout', function(){
mouseTimer = setTimeout(function(){
thisUserDetails.style.display = 'none';
}, mouseOutTimeout);
});
userImage.addEventListener('mouseover', function(){
clearTimeout(mouseTimer);
thisUserDetails.style.display = 'block';
});
thisUserDetails.addEventListener('mouseout', function(){
var _this = this;
mouseTimer = setTimeout(function(){
_this.style.display = 'none';
}, mouseOutTimeout);
});
thisUserDetails.addEventListener('mouseover', function(){
clearTimeout(mouseTimer);
});
}
</script>
Note: I've used getElementsByClassName and addEventListener here, that are not compatible with IE8 and earlier. Check this link for getElementsByClassName compatibility and this one for addEventListener.
Hope it help.
I'm creating a 5 star rating system with html php and jquery i dont know how to stop the stars rating when user has clicked on rating.
In my code when user click on 4 stars the alert box shows 4 stars but when the user move his mouse from stars the stars shows 0 rating.
here is my code, i'm not posting the css here
HTML :
<div class="rating">
<div class="ratings_stars" data-rating="1"></div>
<div class="ratings_stars" data-rating="2"></div>
<div class="ratings_stars" data-rating="3"></div>
<div class="ratings_stars" data-rating="4"></div>
<div class="ratings_stars" data-rating="5"></div>
</div>
JQUERY :
$('.ratings_stars').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
}
);
$('.ratings_stars').click(function() {
$('.ratings_stars').removeClass('selected'); // Removes the selected class from all of them
$(this).addClass('selected'); // Adds the selected class to just the one you clicked
var rating = $(this).data('rating');
alert(rating);
// Get the rating from the selected star
$('#rating').val(rating); // Set the value of the hidden rating form element
});
Guessing because you haven't said what you expect to happen. It could be that you want the selected rating, and the stars before it, to be highlighted.
So instead of this
$(this).addClass('selected');
you use this, similar to how you have previously.
$(this).prevAll().andSelf().addClass('selected');
But I would also remove the hover class so that it's obvious to the user on click
$(this).prevAll().andSelf().addClass('selected').removeClass('ratings_over');
Demo
<!--SAVE AS WHATEVAUWANNA.HTML AND TEST-->
<html>
<head>
<title>Rating System jQuery Plug by Aldanis Vigo</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js'></script>
<style type='text/css' language='css'>
.record{
opacity: .50;
}
#value-display{
position: relative;
top: -5px;
margin-left: 10px;
color: orange;
font-weight: bold;
}
</style>
</head>
<body>
<span value='0' id='ratingbar'>
<img class='record' number='1'/>
<img class='record' number='2'/>
<img class='record' number='3'/>
<img class='record' number='4'/>
<img class='record' number='5'/>
<span id='value-display'>0 / 5</span>
</span>
</body>
<script>
//Change these variables to your liking!!
var iconsrc = 'https://upload.wikimedia.org/wikipedia/commons/a/ae/Record2.png';
var iconwidth = '20px';
var iconheight = '20px';
var value = $('#ratingbar').attr('value');
$('#ratingbar img').each(function(){
//Set the icon for each
$(this).attr('src', iconsrc);
$(this).attr('width', iconwidth);
$(this).attr('height', iconheight);
$(this).hover( function(){
$(this).css('opacity','1');
$(this).prevAll().css('opacity','1');
});
$(this).click( function(){
//Clear all of them
$(this).parent().attr('value',$(this).attr('number'));
$(this).parent().children('#value-display').html($(this).attr('number') + ' / 5');
//Color up to the selected ones.
$('#ratingbar img').each( function(){
if($(this).attr('number') <= $(this).parent().attr('value')){
$(this).css('opacity','1');
}else{
$(this).css('opacity','.50');
}
});
});
$(this).mouseout( function(){
$(this).css('opacity','.50');
$(this).prevAll().css('opacity','.50');
//Color up to the selected ones.
$('#ratingbar img').each( function(){
if($(this).attr('number') <= $(this).parent().attr('value')){
$(this).css('opacity','1');
}
});
});
});
</script>
</html>
I have a listing of products each with differnt ID. Now on frontend I want to get prodouct data(say, name,price and a addtocart button) on mousover.
Here is my code:
This is in loop to get all products:
HTML:
<div class="prod">
<a class="product-image pi_470" title="Cushion Tsavorites" href="/tsavorite/cushion-tsavorites-1328.html"><img height="135" width="135" alt="Cushion Tsavorites" src="/small_image.jpg"></a>
<div style="display: none; margin: -65px 0px 0px 5px; position: absolute; z-index: 30;" class="mouse_hover_470">
<input type="hidden" id="prod_id" value="470">
<h2 class="product-name"><a title="Cushion Tsavorites" href="/tsavorite/cushion-tsavorites-1328.html">Cushion Tsavorites</a></h2>
<div class="price-box">
<span id="product-price-470" class="regular-price">
<span class="price">$387.15</span>
</span>
</div>
<div class="actions">
<button onclick="setLocation('http://dev614.trigma.us/chocolate/index.php/checkout/cart/add/uenc/aHR0cDovL2RldjYxNC50cmlnbWEudXMvY2hvY29sYXRlL2luZGV4LnBocC90c2F2b3JpdGUuaHRtbA,,/product/470/form_key/4BR7w0TqeeO9AC0g/')" class="button btn-cart" title="Add to Cart" type="button"><span><span>Add to Cart</span></span></button>
</div>
</div>
</div>
jQuery:
jQuery(document).ready(function() {
var bla = jQuery('#prod_id').val();
jQuery(".pi_" + bla).mouseover(function() {
//alert("hello");
jQuery(".mouse_hover_" + bla).css("display", "block");
});
jQuery(".pi_" + bla).mouseout(function() {
jQuery(".mouse_hover_" + bla).css("display", "none");
});
});
But Iam getting only data of first product on mouseover. Its not working for rest of products
Looks like you are executing the above block of code in a loop, once per each product. In that case the problem is jQuery('#prod_id').val(); it will always return the value of first element with id prod_id.
In your case you don't have to do that, you can
jQuery(function ($) {
$('.prod .product-image').hover(function () {
$(this).next().show();
}, function () {
$(this).next().hide();
})
});
There is a much, much easier way to do this:
jQuery(document).ready(function() {
jQuery(".product-image").hover(function() {
$(this).next().show();
}, function() {
$(this).next().hide();
});
});
Demo: JSBin
You can use each() function in jQuery
NOTE: Instead of using id="prod_id", use class, i.e class="prod_id". Since you told that the div is dynamically created it is using the same id attribute
Now loop the product div on ready function
jQuery(document).ready(function() {
jQuery('.prod').each(function(){
var bla = jQuery('.prod_id').val();
jQuery(".pi_" + bla).on('mouseover',function() {
//alert("hello");
jQuery(".mouse_hover_" + bla).css("display", "block");
});
jQuery(".pi_" + bla).on('mouseout',function() {
jQuery(".mouse_hover_" + bla).css("display", "none");
});
});
});
You can checkout this jQuery each()
Ashi,
try using
var bla = jQuery(input[id*='prod_id']).val();
instead of
var bla = jQuery('#prod_id').val();
This will give you all the hidden inputs so loop all of them and bind the mouseover event.
For example:
jQuery(input[id*='prod_id']).each(function(){
var bla = jQuery(this).val();
//carry out your logic..
// you can use jquery().live('mouseover'function(){}) for dynamically created html
});
Hope this will work!!
Cheers!!
function handler(ev) {
var target = $(ev.target);
var elId = target.attr('id');
if( target.is(".el") ) {
alert('The mouse was over'+ elId );
}
}
$(".el").mouseleave(handler);
http://jsfiddle.net/roXon/dJgf4/
I have an HTML form that is split into three major components. The top portion is essentially a header for displaying a magazine name. This information does not change.
The middle portion is a table developed through a MySQL query for displaying the story information as a table of contents after it is entered in the bottom portion, which is a data entry screen.
The bottom portion, is a data entry screen for entering the information concerning each story contained in the magazine issue.
After entering the data and pressing the submit button in the bottom portion, the middle portion should be updated through the MySQL query to reflect the newly entered story. That was not happening.
Note: The code previously associated with this question has been removed for purposes of clarity. The solution was associated with how the various forms were called. My thanks to Sulthan Allaudeen for providing potential solutions. Currently, I am not familiar with utilizing jquery-ajax. Eventually I will need to learn.
As the OP wanted to know how do the jquery and ajax call
Step 1 :
Recognize the Input
Have a button with a class trigger
$(".trigger").click(function()
{
//your ajax call here
}
Step 2 :
Trigger your ajax call
$.ajax({
type: "POST",
url: "yourpage.php",
data: dataString,
cache: false,
success: function(html)
{
//your action
}
});
Step 3 :
Inside your success function show the result
$("#YourResultDiv").html(data);
For that you should create a div named as YourResultDiv
Note :
Inside your yourpage.php You should just print the table and it will be displayed as the output
Here's a brief example of displaying the results of submitting a form without leaving the current page. Form submission is done with the help of Ajax.
Each form has it's own button for submission, hence the loop over matching elements in onDocLoaded.
1. blank.php form is submitted to this script
<?php
echo "-------------------------------<br>";
echo " G E T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_GET ); echo "<br>";
echo "-------------------------------<br>";
echo " P O S T - V A R S<br>";
echo "-------------------------------<br>";
var_dump( $_POST ); echo "<br>";
echo "<hr>";
if (count($_FILES) > 0)
{
var_dump($_FILES);
echo "<hr>";
}
?>
2. blank.html Contains 2 forms, shows the result of submitting either of them to the above script.
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
function allByClass(className,parent){return (parent == undefined ? document : parent).getElementsByClassName(className);}
function allByTag(tagName,parent){return (parent == undefined ? document : parent).getElementsByTagName(tagName);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
function toggleClass(elem, className){elem.classList.toggle(className);}
function toggleClassById(targetElemId, className){byId(targetElemId).classList.toggle(className)}
function hasClass(elem, className){return elem.classList.contains(className);}
function addClass(elem, className){return elem.classList.add(className);}
function removeClass(elem, className){return elem.classList.remove(className);}
function forEachNode(nodeList, func){for (var i=0, n=nodeList.length; i<n; i++) func(nodeList[i], i, nodeList); }
// callback gets data via the .target.result field of the param passed to it.
function loadFileObject(fileObj, loadedCallback){var reader = new FileReader();reader.onload = loadedCallback;reader.readAsDataURL( fileObj );}
function myAjaxGet(url, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("GET", url, true);
ajax.send();
}
function myAjaxPost(url, phpPostVarName, data, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajax.send(phpPostVarName+"=" + encodeURI(data) );
}
function myAjaxPostForm(url, formElem, successCallback, errorCallback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
successCallback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
errorCallback(this);
}
ajax.open("POST", url, true);
var formData = new FormData(formElem);
ajax.send( formData );
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded()
{
forEachNode( allByClass('goBtn'), function(elem){elem.addEventListener('click', onGoBtnClicked, false);} );
}
function onGoBtnClicked(evt)
{
evt.preventDefault();
var thisElem = this;
var thisForm = thisElem.parentNode;
myAjaxPostForm('blank.php', thisForm, onPostSuccess, onPostFailed);
function onPostSuccess(ajax)
{
byId('tgt').innerHTML = ajax.responseText;
}
function onPostFailed(ajax)
{
//byId('tgt').innerHTML = ajax.responseText;
alert("POST FAILED!!!!");
}
return false;
}
</script>
<style>
#page
{
display: inline-block;
border: solid 1px gray;
background-color: rgba(0,0,0,0.2);
border-radius: 6px;
}
.controls, .tabDiv
{
margin: 8px;
border: solid 1px gray;
border-radius: 6px;
}
.tabDiv
{
overflow-y: hidden;
min-width: 250px;
background-color: white;
border-radius: 6px;
}
.tabDiv > div
{
padding: 8px;
}
</style>
</head>
<body>
<div id='page'>
<div class='tabDiv' id='tabDiv1'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Name: </label><input name='nameInput'/><br>
<label>Age: </label><input type='number' name='ageInput'/><br>
<input type='file' name='fileInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<div class='tabDiv' id='tabDiv2'>
<!-- <div style='padding: 8px'> -->
<div>
<form id='mForm' enctype="multipart/form-data" >
<label>Email: </label><input type='email' name='emailInput'/><br>
<label>Eye colour: </label><input name='eyeColourInput'/><br>
<label>Read and agreed to conditions and terms: </label><input type='checkbox' name='termsAcceptedInput'/><br>
<button class='goBtn'>GO</button>
</form>
</div>
</div>
<!-- <hr> -->
<div class='tabDiv'>
<div id='tgt'></div>
</div>
</div>
</body>
</html>
The solution to refreshing the form to display the addition of new data was to re-call it through the following line: "include("new_stories.inc.php");". This line is imediately executed just after the MySQL insert code in the data entry section of the form.
The middle section of the form "new_stories.inc.php" (the table of contents) queries the MySQL data base to retrieve the story information related to the current magazine issue. Re-calling the form is equivalent to a re-query.