I am trying to make images change on click to a value (a file name) collected from a text file with PHP. This is done by collecting the file as an array (data) and echoing the right item in the array with the help of a counter (counter). This counter is incremented on each click with Javascript, but I want to return this incremented variable to PHP, to be able to change the images. Is there a way to do this? This is my attempt so far, trying my hand at posting the variable (see full code further down):
<script>
var variableToSend = JSON.parse(localStorage.getItem('counter'));
$.post('lan7_old.php', {variable: variableToSend});
</script>
<?php $counter = $_POST['variable'];
echo $counter; ?
I thought that it ought to work to post as the page is refreshed on image click, but maybe I am mistaken here. Or is anything else wrong with my code? The images shown are still the first ones from the text file, but this is only because I add integers to counter in the PHP echo - there is no value set to the PHP counter variable.
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel="stylesheet" href="styles.css">
<script src="jquery-3.1.1.min.js"></script>
</head>
<body>
<script>
// Saves counter variable although the page is refreshed
$(document).ready(function(){
if (localStorage.getItem('counter') === null) {
localStorage.setItem('counter', JSON.stringify(0));
}
// Incrementing counter until next page is needed
$("img").click(function(){
var counter = JSON.parse(localStorage.getItem('counter'));
if(counter < 60) {
counter += 4;
localStorage.setItem('counter', JSON.stringify(counter));
}
else {
localStorage.setItem('counter', JSON.stringify(0));
window.location.href = '8.php';
return false;
}
$("#test").text(localStorage.getItem('counter')); //for testing
// sending js variable to be obtained by PHP
var variableToSend = JSON.parse(localStorage.getItem('counter'));
$.post('lan7_old.php', {variable: variableToSend});
});
$("#test").text(localStorage.getItem('counter'));
});
</script>
<div class="main">
<h1>Heading</h1>
<p>Heading 2</p>
<div id="test">hello</div>
<?php $data = getData($subtest_nr);
// retrieving counter variable
$counter = $_POST['variable'];
echo $counter; //for testing ?>
<form id="myform" method="post">
<div class="four_images">
<div class="flex-item">
<input type="radio" name="image" value="7.11" id="alt1" class="hidden">
<label for="alt1"><img src="images/<?php echo $data[$counter+0]; ?>"></label>
</div>
<div class="flex-item">
<input type="radio" name="image" value="7.12" id="alt2" class="hidden">
<label for="alt2"><img src="images/<?php echo $data[$counter + 1]; ?>"></label>
</div>
<div class="flex-item">
<input type="radio" name="image" value="7.13" id="alt3" class="hidden">
<label for="alt3"><img src="images/<?php echo $data[$counter+2]; ?>"></label>
</div>
<div class="flex-item">
<input type="radio" name="image" value="7.14" id="alt4" class="hidden">
<label for="alt4"><img src="images/<?php echo $data[$counter+3]; ?>"></label>
</div>
<div>
<input type="submit" name="save" value="Save Image Selection">
</div>
</div>
</form>
</div>
</body>
</html>
Your page is only refreshed if counter reaches 60 or above (window.location.href = '8.php¨).
Php only renders server side, now you are doing a javascript post request but ignoring the response, so this doesn't do anything.
Either you need to make your php return a response which you by javascript use to update the page (the DOM tree), or you should reload the whole page with for example window.location.href = "index.php?counter=" + counter.
Related
I am writing a simple online message board where people can post messages. I hope people can see new messages without refreshing the page so I'm using jquery to do $.ajax() on a text file containing messages. What's very weird is, sometimes the ajax doesn't work. Even though the message.txt has been updated, the data read from it in ajax is still old.
I observed that after I make a modification of my code on the server, it would stop working correctly. And clearing all browser history also makes it stop working correctly for a while. I have no idea what's causing the problem.
This is the code in my php file
#!/usr/local/bin/php
<?php
ob_start();
session_name('message_board');
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<?php
if (!isset($_SESSION['loggedin']) or !$_SESSION['loggedin']) {
header('Location: index.php');
}
else {
?>
<?php
if (isset($_POST['message'])) {
$file = fopen('message.txt', 'a') or die('Can not open file');
date_default_timezone_set('America/Los_Angeles');
$date_time = new DateTime();
fwrite($file, $_POST['message'].'#~,'.$_SESSION['username'].'#~,'.$date_time->format('Y-m-d H:i:s').'#~;');
fclose($file);
}
?>
<head>
<meta charset="UTF-8">
<title>Message Board</title>
<link rel="stylesheet" type="text/css" href="msg_board.css">
<script src="https://code.jquery.com/jquery-latest.min.js" defer></script>
<script src="msg_board.js" defer></script>
</head>
<body>
<h1 id="msg_board_title">
Awesome Message board
</h1>
<form action="logout.php">
<p id="welcome_message">
Welcome to the Message Board! Your email address is <?php echo $_SESSION['username'] ?>
<input type="submit" value="log out">
</p>
</form>
<section id="all_messages">
</section>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<p>
<textarea rows="8" name="message" id="posting_area" required></textarea>
</p>
</fieldset>
<fieldset>
<input type="submit" value="Post">
</fieldset>
</form>
</body>
<?php } ?>
</html>
This is the javascript
$.ajax({
url: "message.txt",
dataType: "text",
success: function(data) {
let large_text = "";
if (data !== "") {
let msg_blocks = data.split("#~;");
for (let i = 0; i < msg_blocks.length - 1; ++i) {
temp = "<p>";
temp += msg_blocks[i].split("#~,")[0];
temp += "<br>";
temp += msg_blocks[i].split("#~,")[1];
temp += "<br>";
temp += msg_blocks[i].split("#~,")[2];
temp += "</p>";
large_text = temp + large_text;
}
}
else {
large_text = "<p>Post something! There hasn't been any messages yet!</p>";
}
$("#all_messages").html(large_text);
}
});
A sample from message.txt
Hi#~,hello#test.com#~,2019-06-04 17:58:35#~;
Not only would it stop working right after I clear browser history or change any file related to these on my server, it also doesn't fulfill the one reason I use AJAX. I'm hoping it would show new messages other users post on their computers without me having to refresh, but that doesn't happen either. I think my usage of php POST and javascript AJAX are very standard. I've spent an entire afternoon already and feeling nauseous literally. Please help!
Just to clarify: By AJAX not working properly, I mean it doesn't update the change to the webpage, even though I've checked the text file indeed has been updated by php. No errors reported anywhere.
I have a insert query through ajax. It is working correctly. But when I reload browser then result disappears from div section and if I insert form through ajax again then result is showing.
I have a file first.php (in which, form is present), a AJAX code and a firstcall.php where query will be execute.
My first.php (html form) is:
<form class="reservation-form mb-0" action="" method="post" autocomplete="off">
<input name="name1" id="name1" class="form-control" type="text" placeholder="Enter Name" required aria-required="true">
<input name="age" id="age" class="form-control" required type="number" placeholder="Enter Age" aria-required="true">
<input type="checkbox" id="checkbox" class="checkbox1" name="namec[]" value="<?php echo $value['id']; ?>" >
<input type="button" class="pull-right btn btn-warning" value="Submit" id="submit">
</form>
Here data should be display:
<div class="col-md-5">
<div class="panel panel-primary" id="showdata">
<!-- Here is the results, but when reload browser then result disapper-->
</div>
</div>
AJAX is:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name1 = $("#name1").val();
var age = $("#age").val();
var chkArray=[];
$('.checkbox1:checked').each( function() {
chkArray.push($(this).val());
} );
var selected;
selected = chkArray.join(',') ;
if(selected.length > 1){
$.ajax( {
url:'firstcall.php',
type:'POST',
data:{name1: name1,age: age,namec: chkArray},
}).done(function(data){
$("#showdata").html(data);
});
}
else{
alert("Please at least one of the checkbox");
}
});
});
</script>
firstcall.php is:
<div class="panel panel-primary" id="showdata">
<?php
foreach($_POST['namec'] as $selected){
echo $selected;
$_SESSION['name1']=$_POST["name1"];
$_SESSION['age']=$_POST["age"];
echo $name1=$_SESSION['name1'];
echo $age=$_SESSION['age'];
$query=mysql_query("insert into patient_details (p_name,p_age,g_number) values ('$name1','$age','$selected')") or die(mysql_error());
}
?>
First of all fix your query to use MySQLi, instead of MySQL, check this or the PHP manual
Also don't ever add direct $_POST or $_GET variables into your mysql query, filter them first using mysqli_real_escape.
$name1 = mysqli_real_escape($link, $_POST["name1"]);
$age = mysqli_real_escape($link, $_POST["age"]);
After that, to show the data when the page reloads, you need to load the data with the page, easiest way to do that is just add in your HTML PHP tags with an echo command inside, adding your variables.
If I understand your question correctly, you want the Ajax result to also show on page load?
Right now you only execute the JS after a click (so on page load/relaod you will just see the html), you might want to execute it after page load aswell (so execute the script without the .click)
You could create a function once, and call it when the page is ready and on click.
well I searched on every web site but I didn't find what I want so :
I will be easier for you, to see what I have :
my page ;)
So for each radio buttons, I want to set the display of my table.
Ex : if I pick "Alphabétique", the values sorted in alphabetical order.
I knew I needed to use Ajax, but I'm absolutely not comfortable with that. In addition to that, I am programming my project in MVC.
I made some research on Google, Stack, OpenClassroom, etc..
And I don't understand exactly what I need to do in Ajax or where I need to add the instructions.
So here is my code :
controllerBoutique.php (Controller):
<?php
require('../Views/codes/boutique.php');
require('../Models/vehicule.php');
$query = getVehiculesByAlpha();
require('../Views/codes/tabAffich.php');
?>
boutique.php : (View)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Rentcar - Boutique</title>
<link rel="stylesheet" href="../Views/styles/style2.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
</head>
<body>
<?php require("menu.php");?>
<section id="section" class="main-section cleanbg">
<div class="container">
<label>Trier par :</label>
<div class="single-col">
<div class="styled-input-container">
<div class="styled-input-single">
<input type="radio" name="fieldset-1" id="radioAlpha" value="Alpha" checked="checked"/>
<label for="radioAlpha">Alphabétique</label>
</div>
<div class="styled-input-single">
<input type="radio" name="fieldset-1" id="radioModel" value ="Model"/>
<label for="radioModel">Modèle</label>
</div>
<div class="styled-input-single">
<input type="radio" name="fieldset-1" id="radioKm" value ="Km"/>
<label for="radioKm">Kilométrage</label>
</div>
<div class="styled-input-single">
<input type="radio" name="fieldset-1" id="radioDispo" value ="Dispo"/>
<label for ="radioDispo"> Disponible </label>
</div>
</div>
</div>
</div>
<div class="search">
<label class="lblSearch"> Rechercher :</label>
<input type="text" id="search-box" class="search-box">
<button class="btnSearch">Chercher</button>
</div>
</section>
<section id="section" class="main-section cleanbg">
<div class="container">
<hr>
tabAffich.php : (view table)
<div class="wrapper">
<div class="table">
<div class="row header">
<div class = "cell">Marque</div>
<div class = "cell">Modèle</div>
<div class= "cell">Kilométrage</div>
</div>
<?php
while($res = $query->fetch()){
?>
<div class="row">
<div class ="cell">
<?php echo $res['nom'];?>
</div>
<div class="cell">
<?php echo $res['modele'];?>
</div>
<div class="cell">
<?php echo $res['km'];?>
</div>
</div>
<?php
}
$query->closeCursor();
?>
</div>
</div>
</div>
</section>
</body>
</html>
vehicule.php (Model):
<?php
function getVehiculesByAlpha(){
try{
$db = new PDO('mysql:host=localhost;dbname=ProjectRentcar;charset=utf8','root','root');
}catch(Exception $e){
die('Erreur : '.$e->getMessage());
}
$query = $db->query('
SELECT nom, modele, km
FROM Vehicule V, Marque Ma
WHERE V.numMarque = Ma.numMarque
ORDER BY nom, modele');
return $query;
}
function getVehiculesByModel(){
//Same code with order differently
}
function getVehiculesByKm(){
//Same here
}
So I would know how can I change the display of table when I click on a specific radio button, and some help in Ajax 😉
Thanks you in advance ❤️
you can achive this using only PHP but sure it would be better for UX to achive this with Ajax (for you too, you will learn more).
1) So first you need a javascript function that will trigger when you click on input[type=radio] and for example if you click on radio button with id == radioAlpha it will run a function using Ajax request to your vehicule.php?sort=alphabetique. If you click on radio button with id == radioModel it should run a function using Ajax request to your vehicule.php?sort=model - you can send data using POST or GET request with Ajax, how do you like.
2) You should then change your vehicule.php file, it should also contain something like this:
if ($_GET['sort'] == 'alphabetique') {
// run function with sort for alphabetique
// echo data with json format for example or even with html
}
if ($_GET['sort'] == 'models') {
// run function with sort for model
// echo data with json format for example or even with html
}
...
...
3) Yor file tabAffich.php
<?php
while($res = $query->fetch()){
?>
<div id="sorttable"> // Add this line
<div class="row">
<div class ="cell">
<?php echo $res['nom'];?>
</div>
<div class="cell">
<?php echo $res['modele'];?>
</div>
<div class="cell">
<?php echo $res['km'];?>
</div>
</div>
<?php
}
$query->closeCursor();
?>
</div>
Back to Ajax request, when it would be a successfull call with response you can generate new data in <div id="sorttable"> container. You need some knowledge of javascript how to clear data and generate a new from ajax response but its not very hard to learn.
I hope that will help you a little bit in understanding how you can use ajax in this situation.
There are really many ways to get the effect you want to achieve, and the one I've presented is quite simple, I think.
I would like to create an upload form. In the form, member can upload multiple pictures to his/her own folder, which is named by the member's ID. For example, if the member's ID is 0001, then he/she can upload his pictures to image/0001/ folder.
In the uploading form, I use Javascript to let users upload multiple pictures in the same page. After user select the first picture, it generates the second <input type="file"> ; after selecting the 2nd picture, it generates the third <input type="file">.... and so on.
Now, I want to add constraint that each member can have at most 5 pictures in their folder. Therefore, I use a PHP variable $pic_in_folder to to count how many picture the member has already had in the his/her folder.
// test.js
$(document).ready(function(){
var pic_in_folder //To receive PHP variable $pic_in_folder
var blockCount = 1; //To count how many #upload_block.
$("body").on("change", "#picture", function(){
//if( pic_in_folder + blockCount < 5 ){
$("#upload_block" + blockCount ).after($("<div/>", {
id: "upload_block"+ (blockCount + 1),
class: "upload_block",
style: "margin: 1rem;"
}).fadeIn("slow").append($("<input/>", {
name: "picture[]",
type: "file",
id: "picture"
})));
blockCount += 1;
//}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Upload Picture</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/test.js"></script>
</head>
<body>
<?php
$member_Id = $_GET["member"];
$pic_in_folder = 0; //Count how many pictures this member currently have
foreach(glob("picture/".$member_Id."/*") as $file){
if(file_exists($file)){
$pic_in_folder += 1;
}
}
?>
<h3>You currently have <?php echo $pic_in_folder; ?> pictures.</h3>
<hr/>
<form name="upload_form">
<div id="upload_block1" class="upload_block" style="margin: 1rem;">
<input type="file" name="picture[]" id="picture" />
</div>
<input type="submit" />
</form>
</body>
</html>
For the Javascript codes, in order to avoid member having more than 5 pictures after they uploading pictures, I use variable pic_in_folder to get values from PHP variable $pic_in_folder ; blockCount to count how many input block is showing in the form. And the Javascript only generates input block when (pic_in_folder + blockCount) < 5
However, My HTML & PHP codes are in one document and the Javascript is in the other one. How can I pass the $pic_in_folder to the Javascript document variables ?
Thank you very much !!
You can declare the Variable for JS in your PHP-File:
echo '<script>var pic_in_folder = ' . $pic_in_folder . '</script>';
This will make it available globally. Then you can just use pic_in_folder in your other JS file. But be sure to include your external JS AFTER you did the script-tag above, so the external file actually knows about the variable.
Regarding best practices, I'm not sure if this is a good approach but it worked for me in one of my projects. Hope it helps :)
You can create a hidden field to store the $pic_in_folder value.
<input type="hidden" id="pic_in_folder" name="pic_in_folder" value="<?php echo $pic_in_folder;?>" />
Then read this value in JavaScript as follows:
var pic_in_folder = $("#pic_in_folder").val();
How about this?
<?php
$member_Id = $_GET["member"];
$pic_in_folder = 0; //Count how many pictures this member currently have
foreach(glob("picture/".$member_Id."/*") as $file){
if(file_exists($file)){
$pic_in_folder += 1;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload Picture</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function picsInFolder() { return <?= $pic_in_folder;?>; }
</script>
<script src="/test.js"></script>
</head>
<body>
<h3>You currently have <?php echo $pic_in_folder; ?> pictures.</h3>
<hr/>
<form name="upload_form">
<div id="upload_block1" class="upload_block" style="margin: 1rem;">
<input type="file" name="picture[]" id="picture" />
</div>
<input type="submit" />
</form>
</body>
</html>
Then in your JS file you can call picsInFolder();
var pic_in_folder = picsInFolder();
I have several tabs and each time I select a tab, the form is submitted sending a variable a different value (hidden from the user). If I go say from TAB1 to TAB2, variable99 will get a value of 2, TAB3 a value of 3 and so on.... Problem I am having is that when I select TAB2, I don't want the page to revert back to TAB1. Here is my code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit a Form on Tab Click</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style type="text/css">
</style>
<script>
$(function() {
$("#Main").tabs();
$('[id^=ui-id-]').click(function(){
var tabId = $(this).attr('id');
var tabNum = tabId.split('-')[2];
$('#form-' + tabNum).submit();
});
});
</script>
</head>
<body>
<div id="Main">
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
<li>Tab4</li>
<li>Tab5</li>
<li>Tab6</li>
</ul>
<form id="form-1" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="1">
</form>
<form id="form-2" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="2">
</form>
<form id="form-3" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="3">
</form>
<form id="form-4" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="4">
</form>
<form id="form-5" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="5">
</form>
<form id="form-6" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="6">
</form>
<div id="Tab1">
<p>Tab1</p>
</div>
<div id="Tab2">
<p>Tab2</p>
</div>
<div id="Tab3">
<p>Tab3</p>
</div>
<div id="Tab4">
<p>Tab4</p>
</div>
<div id="Tab5">
<p>Tab5</p>
</div>
<div id="Tab6">
<p>Tab6</p>
</div>
</div>
</body>
</html>
Here is my code now, I removed some things, that didn't make since:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit a Form on Tab Click</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style type="text/css">
</style>
<script>
$(function() {//Open function
$("#Main").tabs();
$('[id^=ui-id-]').click(function(){ //Open [id^=ui-id-]
if (tabId == 'ui-id-1')
{
doAjax('1');
}
else if (tabId == 'ui-id-2')
{
doAjax('2');
}
else if (tabId == 'ui-id-3')
{
doAjax('3');
}
function doAjaxSubmit(formID) { //Open doAjaxSubmin
$.ajax({
type: "POST",
url: "Tab_Click_v00.html",
data: "Nb_var99=" + formID,
})
} //Close doAjaxSubmin
}); //Close [id^=ui-id-]
});//Close function
</script>
</head>
<body>
<div id="Main">
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
<li>Tab4</li>
<li>Tab5</li>
<li>Tab6</li>
</ul>
<div id="Tab1">
<p>Tab1</p>
</div>
<div id="Tab2">
<p>Tab2</p>
</div>
<div id="Tab3">
<p>Tab3</p>
</div>
<div id="Tab4">
<p>Tab4</p>
</div>
<div id="Tab5">
<p>Tab5</p>
</div>
<div id="Tab6">
<p>Tab6</p>
</div>
</div>
</body>
</html>
This is not working. It also killed the css style?? I'll keep on trying.
For what you want to do, there is no need to use <form>s and <input>s at all.
Just based on the tab that is clicked, you can send a 1 or a 2 or a 3 over to the desired HTML page, via AJAX.
The <form> construction is great when you have several fields and you wish to POST their data over to another server page for processing. However, in your case, it appears that you only wish to send a value to another page, and then return.
Here is one way to do it, using AJAX:
$(document).ready(function() {
$( "#Main" ).tabs();
$('[id^=ui-id-]').click(function() {
if (tabId == 'ui-id-1') {
doAjax('1');
}else if (tabId == 'ui-id-2') {
doAjax('2');
}else if (tabId == 'ui-id-3') {
doAjax('3');
}
}); //END ui-id-#.click fn
}); //END document.ready
function doAjaxSubmit(formID) {
$.ajax({
type: "POST",
url: "myphpprocessor.php",
data: "Nb_var99=" + formID,
})
.done(function( recd_from_PHP ) {
//No need to put ANYTHING in here, but for eg, you can do:
//AS AN EXAMPLE ONLY, display message sent from server side
alert("PHP side said: " + recd_from_PHP);
//AS AN EXAMPLE ONLY, click the third tab...
$('[id^=ui-id-3]').click();
});
}
Another way to send form data (using a <form> as it was intended) is to create a hidden <iframe> on your page, containing the Tab_Click_v00.html page inside it -- and then POST to that page.
Because the form's target is already on the page in an <iframe>, the current page should not refesh. And because the <iframe> is hidden, the user should not see anything unusual.
This answer also uses AJAX. I will post another example, addressing your request for more information regarding the hidden iframe idea.
Notice that as you click from Tab to Tab, the user remains on the tab.
Just copy/paste into two files:
index.php (or whatever you wish to name it), and
myphpprocessor.php (if change name of this file, must also change its name in AJAX code block)
index.php (or mytest.html, or whatever)
<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>
#msg{width:30%;height:80px;padding:10px;margin-top:20px;background-color:wheat;}
.hidden{display:none;}
</style>
<script type="text/javascript">
$(document).ready(function() {
$( "#Main" ).tabs();
$('[id^=ui-id-]').click(function() {
var tabId = $(this).attr('id');
if (tabId == 'ui-id-1') {
doAjax('1');
}else if (tabId == 'ui-id-2') {
doAjax('2');
}else if (tabId == 'ui-id-3') {
doAjax('3');
}else if (tabId == 'ui-id-4') {
doAjax('4');
}else if (tabId == 'ui-id-5') {
doAjax('5');
}
}); //END ui-id-#.click fn
}); //END document.ready
function doAjax(formID) {
$.ajax({
type: "POST",
url: "myphpprocessor.php",
data: "Nb_var99=" + formID,
})
.done(function( recd_from_PHP ) {
//No need to put ANYTHING in here, but for eg, you can do:
//alert('In done fn...');
//AS AN EXAMPLE ONLY, display message sent from server side
//alert("PHP side said: " + recd_from_PHP);
$('#msg').html('<h2>Here is what the PHP side sent:</h2>' + recd_from_PHP);
//AS AN EXAMPLE ONLY, click the third tab...
//$('[id^=ui-id-3]').click(); //Warning, this will cause endless loop -- but just demonstrating
});
}
</script>
</head>
<body>
<div id="Main">
<ul>
<li>Tab1</li>
<li>Tab2</li>
<li>Tab3</li>
<li>Tab4</li>
<li>Tab5</li>
<li>Tab6</li>
</ul>
<form id="form-1" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="1">
</form>
<form id="form-2" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="2">
</form>
<form id="form-3" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="3">
</form>
<form id="form-4" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="4">
</form>
<form id="form-5" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="5">
</form>
<form id="form-6" action="Tab_Click_v00.html" method="post">
<input type="hidden" name="Nb_var99" value="6">
</form>
<div id="Tab1">
<p>Tab1</p>
</div>
<div id="Tab2">
<p>Tab2</p>
</div>
<div id="Tab3">
<p>Tab3</p>
</div>
<div id="Tab4">
<p>Tab4</p>
</div>
<div id="Tab5">
<p>Tab5</p>
</div>
<div id="Tab6">
<p>Tab6</p>
</div>
</div>
<div id="msg"></div>
</body>
</html>
Server Side: myphpprocessor.php (MUST end in .php)
<?php
$id = $_POST['Nb_var99'];
if ($id == 4) {
$msg = "Return of the Tab Four";
}else{
$msg = 'PHP side receieved: ' .$id;
}
echo $msg;
Posting to a hidden <iframe>
I've never done this myself, and can see its a bit tricky. Here are some posts that discuss how to do it:
How do you post to an iframe?
Hidden iframe submit
Remember to specify the name= attr
Post form in an iframe
You will notice that this is considerably more complicated than simply doing a basic AJAX form submission, as suggested in my previous two answers.
I am not sure why the AJAX solution is not appealing in your situation, but I remember when AJAX and PHP were unknown commodities to me, and perhaps that is what you are struggling with.
If so, struggle no more. Both are much simpler than you realize.
For basic, FREE, from-the-ground-up 10-min tutorials in PHP:
phpAcademy.org
thenewboston.com
Next, here are some good posts for getting the basics of AJAX:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
My recommendation is to use the AJAX solution, but I do not understand what you are trying to achieve in the end. What is the file Tab_Click_v00.html going to do with the data it receives?
Perhaps if you provide more information (as a comment below this post) about the desired end result on the Tab_Click side, I can be of more help.
Given you're using the jQuery Tabs control, you can use the window.location.hash and bind to the load event (and show the appropriate tab using the active option):
$(window).load(function(){
if(window.location.hash){
$('#main').tabs('option','active',window.location.hash.substring(1));
}
});
Then redirect the user back using somepage.html#tabindex