I have the following table that uses Javascript to calculate the sum of cells. When the inputs are entered Javascript the sums up the total of quantity and displays it in TD id="totalSum".
Ultimately I need to have it where when the totalSum equals 100, then execute php code.
How do I get PHP to read the data in the totalSum and then execute PHP when it equals 100?
HTML-
<table id="mytable" width="394">
<colgroup>
<col style="width: 50px;">
<col>
<col style="width: 60px;">
<col style="width: 110px;">
</colgroup>
<tbody>
<tr>
<th width="130" height="43"></th>
<th width="52">Weight Select</th>
<th width="181">New P</th>
</tr>
<tr>
<td align="center" width="130"> </td>
<td align="center">
<input type="text" size="2" value="1" id="qty_item_1" name="sum" >
</td>
<td align="center" id="total_item_1"></td>
</tr>
<tr>
<td align="center" width="130"></td>
<td align="center" >
<input type="text" size="2" value="1" id="qty_item_2" name="sum" >
</td>
<td align="center" id="total_item_2"></td>
</tr>
<tr class="tr">
<td align="left" colspan="1"><strong>Grand Total:</strong></td>
<td width="11" align="left" id="totalSum"></td>
</tr>
</tbody>
</table>
Javascript-
<script type="text/javascript">
var bIsFirebugReady = (!!window.console && !!window.console.log);
$(document).ready(function (){
// update the plug-in version
$("#idPluginVersion").text($.Calculation.version);
/*
$.Calculation.setDefaults({
onParseError: function(){
this.css("backgroundColor", "#cc0000")
}
, onParseClear: function (){
this.css("backgroundColor", "");
}
});
*/
// bind the recalc function to the quantity fields
$("input[id^=qty_item_]").bind("keyup", recalc);
// run the calculation function now
recalc();
// automatically update the "#totalSum" field every time
// the values are changes via the keyup event
$("input[name^=sum]").sum("keyup", "#totalSum");
// automatically update the "#totalAvg" field every time
// the values are changes via the keyup event
$("input[name^=avg]").avg({
bind:"keyup"
, selector: "#totalAvg"
// if an invalid character is found, change the background color
, onParseError: function(){
this.css("backgroundColor", "#cc0000")
}
// if the error has been cleared, reset the bgcolor
, onParseClear: function (){
this.css("backgroundColor", "");
}
});
// automatically update the "#minNumber" field every time
// the values are changes via the keyup event
$("input[name^=min]").min("keyup", "#numberMin");
// automatically update the "#minNumber" field every time
// the values are changes via the keyup event
$("input[name^=max]").max("keyup", {
selector: "#numberMax"
, oncalc: function (value, options){
// you can use this to format the value
$(options.selector).val(value);
}
});
// this calculates the sum for some text nodes
$("#idTotalTextSum").click(function() {
// get the sum of the elements
var sum = $(".textSum").sum();
// update the total
$("#totalTextSum").text("$" + sum.toString());
});
// this calculates the average for some text nodes
$("#idTotalTextAvg").click(function() {
// get the average of the elements
var avg = $(".textAvg").avg();
// update the total
$("#totalTextAvg").text(avg.toString());
});
});
function recalc(){
$("[id^=total_item]").calc(
// the equation to use for the calculation
"qty * price / 100",
// define the variables used in the equation, these can be a jQuery object
{
qty: $("input[id^=qty_item_]"),
price: $("[id^=price_item_]")
},
// define the formatting callback, the results of the calculation are passed to this function
function (s){
// return the number as a dollar amount
return "" + s.toFixed(2);
},
// define the finish callback, this runs after the calculation has been complete
function ($this){
// sum the total of the $("[id^=total_item]") selector
var sum = $this.sum();
$("#grandTotal").text(
// round the results to 2 digits
"" + sum.toFixed(2)
);
}
);
}
</script>
Your question does not show how you trigger summing up the values, or checking the value of cell id="totalSum", so in my solution I added a button id="mybutt" to do that.
Working jsFiddle here
All you need to know is in the above jsFiddle, and in the section below discussing the some_php_file.php. What follows now is a description of how the code works, if you need that.
First, we get the collection of all table cells where the id starts with qty_item:
$('[id^=qty_item_]')
Next, we iterate through this collection using the .each method:
var ttl = 0;
$('[id^=qty_item_]').each(function() {
str = $(this).val();
ttl += Number(str);
});
Then, inject the total into the cell with id="totalSum"
$('#totalSum').text(ttl).trigger('change');
Note that we trigger a change event on that same element (table cell). That immediately fires this code:
$('#totalSum').change(function() {
var sum = $(this).text();
alert('Value: ' + sum);
if (Number(sum) > 99) {
alert('Value > 100. AJAX will begin, but cannot finish because jsFiddle cannot do ajax. Just look at syntax.').
$.ajax({
type: "POST",
url: "some_php_file.php",
data: 'myTotalSum='+sum,
success:function(somedata){
alert(somedata);
}
});
}
});
In the AJAX code block, notice the URL that is specified. A PHP file with the same name must exist on the server (in same folder as your HTML code, for this example). It will receive the info sent via AJAX in a POST variable called myTotalSum.
Once you have that number, your PHP file can stick it into the database. If you want, you can even have the PHP file send information back to the webpage (it arrives in the success function of the AJAX code block). Note that the javascript on the webpage continues processing without waiting for the PHP page to finish. If you need the javascript to wait, then you would insert async: false, somewhere near the top of that code block.
To see this actually work, create a text file with this name and these contents:
some_php_file.php
<?php
$theSum = $_POST['myTotalSum'];
$r = '<h2>Mr. PHP received this number:</h2><h1>' .$theSum. '</h1>';
echo $r;
The echo in the PHP file sends the contents of variable $r back to the AJAX code block, where it is received in the success function. Important: this incoming data must be dealt with here, and no where else. It will not exist outside the success function.
To access received data outside the success function, stick the received data into an element, such as a hidden input element, like this:
success:function(mydata){
$('#a_hidden_input_element').val(mydata);
}
Here is an SO post with some additional AJAX code examples.
Related
I have angularjs table added with check boxes to each row and a common remove button outside the table, so that multiple rows can be selected and deleted at a time. When rows are selected and remove is clicked, that particular rows will be deleted. This is fine and till here its working in the below plunker too. Now what I need is when a particular row is selected, its rowid has to be sent as a parameter to another URL. when this URL(URL formed by selected rowIds) with ids is called, automatically the rows will be deleted from first URL data, and now the table has to be updated from first URL. null will be returned from second url with ids as parameters and at the same time that rows will be deleted from JSON data of first URL.
Here is a demo:http://plnkr.co/edit/UzKdIGSubEfHoF7FHoCd?p=preview
Below is the code for the table:
<div ng-controller="SampleController">
<form class="form-horizontal">
<a class="btn btn-info" ng-click="subt_click()">Submit</a>
</form>
<div class="table-responsive" ng-show="tableData.length > 0">
<table class="table table-striped table-bordered table-hover dataTables-example">
<thead>
<tr>
<th><input name="all" type="checkbox" ng-click="selectAllFriends()" /></th>
<th>ID</th>
<th>Body</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="x in tableData">
<td><input name="all" type="checkbox" ng-model="x.checked" /></td>
<td>{{x.id}}</td>
<td>{{x.body}}</td>
</tr>
</tbody>
</table>
</div>
<input ng-hide="!tableData.length" type="button" class="btn btn-danger pull-left" ng-click="remove()" value="Remove">
app.js:
$scope.remove = function () {
var newDataList = [];
$scope.selectedAll = false;
angular.forEach($scope.tableData, function (checked) {
if (!checked.checked) {
newDataList.push(checked);
}
});
$scope.tableData = newDataList;
};
$scope.isAll = false;
$scope.selectAllFriends = function () {
if ($scope.isAll === false) {
angular.forEach($scope.tableData, function (x) {
x.checked = true;
});
$scope.isAll = true;
} else {
angular.forEach($scope.tableData, function (x) {
x.checked = false;
});
$scope.isAll = false;
}
};
In brief what i need is:
I get table data from first url. (pls check the plunk and the url i used is jsonplaceholder.typicode.com/posts)
When a checkbox is selected from a row in table and remove button is clicked, that rowid has to be sent to second URL(need to call another url, need not post) and this url when called along with selected rowids deletes that particular row details from first url and returns a null.
Finally, the first url data(which will be modified by just calling second url with rowids) has to be updated in the table present already.
How can I change this code to send rowid to second url and call that url to update the table. Thanks in advance!!
$scope.xListNo is never affected in your statements.
May be you wanted to use xListNo which is your function parameter (without $scope) ?
So does index in your second statement, which should be idx.
Double check your variables spelling and it should work !
#Deborah : Went through your Plunker and could not find any code for Posting ids to an URL. Assuming that you are doing that somewhere, Still there can be two cases, whether to remove data as soon as call is made or removing it after response from API call. The better way would be removing after the success of API.
So, what you should do probably is to keep your entire table data in a variable (as you have already done, after your GET call).
//Table Data
$http.get("http://jsonplaceholder.typicode.com/posts")
.success( function(response) {
$scope.tableData = response;
});
Now In remove function you can create an array of rows which are checked and send them to URL..Like:
$scope.remove = function(){
$scope.deletedIds = [];
$scope.tableData.forEach(function(x){
if(x.checked){
$scope.deletedIds.push(x)
}
}
makePostCallFOrDeletion()
}
//use this if POST call
function makePostCallFOrDeletion(){
$http.post("deleteurl", angular.toJson($scope.deleteIds)).then(function(response){
$scope.tableData = response //assuming you get the updated JSON back.
//if you don't get JSON back, delete yourself from JSON, like
$scope.tableData.forEach(function(x,i){
if ($scope.deleteIds.indexOf(x.id) !== -1)
$scope.tableData.splice(i, 1);
}
}
As per my understanding of your question, this should get you going..
EDIT: OP wanted GET call for deleting (which as per my opinion is not a good idea, since number of IDs can be too large)
//use this if GET call
function makePostCallFOrDeletion(){
$http.get("deleteurl" + append IDs here,).then(function(response){
//$scope.tableData = response //assuming you get the updated JSON back.
//if you don't get JSON back, delete yourself from JSON, like
$scope.tableData.forEach(function(x,i){
if ($scope.deleteIds.indexOf(x.id) !== -1)
$scope.tableData.splice(i, 1);
}
}
I am trying to use the split function in classic ASP using JavaScript. I need to have a big text box where I can keep group of bar-code numbers of products. Once submit button is clicked These bar-code numbers needed to be split by each and every character term for all bar-code numbers (in a loop). For instance, if i have 5 bar-code numbers, I have to split first bar-code number by each and every character/number, keep into array and continue same process to all 5 bar-code numbers. I wanted to display the result of split-ted numbers into a paragraph for myself just to check if its working. Below is the code I was working on. It doesn't show me anything when i click the button. I am not being able to figure out my logical error or what am I missing. How do I fix it? I didn't find any helpful solution when i was doing research.
<p id="demo"></p>
<form name="submitticket" action="<%=Request("script_name")%>" method="post">
<input type="hidden" name="action" value="sendform">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td align="center" colspan="2">
<br /><textarea name="noskews" id="skewsip" rows="50" cols="100" wrap="soft" maxlength="5000"><%=Request("noskews")%></textarea>
</td>
</tr>
<tr>
<td align="center" colspan="2" style="padding-top:20px;">
<input type="submit" name="clearNoskew" value="Submit" class="a-t-button-mini">
</td>
</tr>
</table>
</form>
<script>
$("form").on("click", ".a-t-button-mini", function(event){
//var clickedId = $(this).attr('value')+','; // give me first numbers,
var locationBtn = $('#skewsip'); // Select the input
var locationBtnValue = $('#skewsip').val(); // Take the select value
var ids = locationBtnValue.split(',');
document.getElementById("demo").innerHTML = ids; //want to display in a paragraph for myself
});
</script>
I was able to split one barcode (out of total 5 barcodes entered inside textarea) by every characters and display it into div. for example: I entered 5465 8989 7586 5236 5486 (These barcodes are entered using "enter or new line" after every 4 numbers; space in above example means the next barcode is in next line). I get split output of (5,4,6,5) which I need but it didn't give me for rest of my barcodes. In other words, I couldn't do same for all 5 total bar codes entered into the textarea/textbox. I know its only "for loop" When I kept for loop in my code, it executes for first barcode out of 5 barcodes.
<script>
$("#form").on("click",".a-t-button-mini", function(event){
var locationBtnValue = $('#skewsip').val();
var skews_array = locationBtnValue.split("",12);
// for (i = 0; i < locationBtnValue.length; i++) {
// text += skews_array[i] + "<br>";
document.getElementById("test").innerHTML = skews_array;
// }
});
</script>
I think you're saying each barcode on a new line of the textarea. If so, this should work for you (\n is the newline character), at least to capture and re-output to the demo element:
<script>
$("form").on("click", ".a-t-button-mini", function(event){
var ids = $("#noskews").val().split('\n');
$.each( ids, function( index, value ) {
$("#demo").append(index + ' - ' + value + '<br/>');
});
});
</script>
Added working code to codepen:
http://codepen.io/anon/pen/NxENYW
I want to pass all datas stored in the table in my template. The table is growing by user's choices. My project is about a food ordering system and what i'm trying to do is, when user adds menus to its basket, and make an order, how can i pass the values to my view to save them to my db. I know about forms but my table is not static.. I can't imagine how it will be big.
My add row func:
$(document).ready(function(){
var sum = 0;
$(document).on('click', '.myaddButton', function() {
var $foodname = $(this).closest("tr") // Finds the closest row <tr>
.find(".nr") // Gets a descendent with class="nr"
.text();
var $foodprice = $(this).closest("tr") // Finds the closest row <tr>
.find(".rn") // Gets a descendent with class="nr"
.text();
$('#carttable').prepend("<tr class='danger' id ='myTableRow'><td>"+$foodname+"</td><td class='price'>"+$foodprice+"</td> <td> <button class='deletebutton btn btn-danger' type='button'> <span class='glyphicon glyphicon-trash'></span> </button> </td></tr>");
});
$(document).on('click', '.deletebutton', function() {
$('#myTableRow').remove();
//$('.price').each(function() {
// var $price = $(this);
//console.log($price);
//sum += parseInt($price.context.innerHTML);
//});
//$('#total').html(sum);
//sum = 0;
});
});
</script>
My Table
<table border="1" class="table" id="menutable" name="menutable">
<tr class="danger">
<tbody>
{%for a in list%}
<tr class= {% DoRandom %}>
<td><b> {{a.name}}</b> </td>
<td class="nr">{{a.description}}</td>
<td class="rn"><p>{{a.price}}</p></td>
<td id="addbutton" > <button class="myaddButton btn btn-success" type="button">
<span class="glyphicon glyphicon-plus"></span> </button> </td>
</tr>
{%endfor%}
</tbody>
</table>
If you want to use little bit higher technique of form processing, then you should look at question Making a Django form class with a dynamic number of fields...
Second "simple" solution is to add hidden input values (which will contain food_id and quantity) together with name and price (during prepend), and wrap your table in form. E.g
var $food_id = ... // some how get food id
var $quantity = 1; //1 for now, but you can add increase and decrease functionality
...
// in prepend text
... + "<input type='hidden' name='food-" + $food_id + "' value='" + $quantity + "' >" + ...
And in your template you should add <form> before <table> (and </form> after </table> tags), or use serialize if you are using ajax.
Third solution is to use JS object as cart, and encode it to Json before form submittion. E.g.
//in your javascript global scope
var js_food_cart = {};
....
// then on click
$food_id = ... ;// yes, again you need food id
$quantity = 1; // or something elese
js_food_cart[$food_id] = $quantity;
....
// then somwhere in before submit, code assumes that you have form with my_cart hidden input
$('input[name=my_cart]') = JSON.stringify(js_food_cart);
Then in view you should parse your json value of my_cart input. In template you should add form with hidden field to pass cart value.
This approach more convenient if you will implement ability to increase/decrease quantity of food.
Thanks, i resolved the issue by casting my food objects to json and post by AJAX post.
First time using ajax. Have successfully progressed through a number of teething problems, so far with happy results. However now is a more confusing one specific to one particular input field nested within a table - there is a good reason for that.
First the html:
<table id="speakersName" style="width: 100%; height: auto;">
<tbody><tr class="activity_row">
<td class="right" style="width: 190px;">Name of Speaker:</td>
<td><input type="text" id="input_3_1" name="input_3_1" id="input_3_1" placeholder="Name of Speaker" value="<?=$input_3_1?>" required></td>
<td><input type="button" name="button2" id="button2" value=" +1 " class="button" style="width: auto !important; margin: 5px;"></td>
</tr>
<tr>
<td class="center" colspan="3"><input type="hidden" name="MAX_FILE_SIZE" value="5632000">
<label for="file">Filename:</label> <input type="file" name="file" id="file">
<input class="button" style="width: 70px; margin-top: 12px;" type="submit" name="submit" value="Upload"></td>
</tr></tbody>
</table>
We can fairly much ignore the section containing the file upload. I just wanted to be clear about the entire table structure.
The .js file that is included in the head contains this relevant code:
function doSend_3_1() {
$.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_3_1', $('#input_3_1').serialize());
}
$("document").ready(function() {
$("#input_3_1").blur(doSend_3_1);
})
Which ajax's the data entered into the text input field over to this bit of php:
// include the funcky stuff
include './conf/Funcs.php';
include './conf/DBconfig.php';
// GET the constants
$appID = $_GET['appID'];
$ident = $_GET['ident'];
if(($ident) == "input_3_1") {
$userInput = $_POST['input_3_1'];
if(($userInput == "") || ($userInput == " ") || ($userInput == NULL)) { $userInput = NULL; }
try {
$stmt = $conn->prepare("UPDATE $database.app_ConSupAp SET `nameOfSpeakers` = :userinput, `lastModified` = :time WHERE `appID` = :appid");
$stmt->bindParam(':userinput', $userInput, PDO::PARAM_STR, 128);
$stmt->bindParam(':time', time(), PDO::PARAM_INT, 11);
$stmt->bindParam(':appid', $appID, PDO::PARAM_INT, 11);
$stmt->execute();
} catch(PDOException $e) { catchMySQLerror($e->getMessage()); }
}
Which happily drops in the text that the user typed into the initial text input field, soon as they click out of it. This technique is being used across the form successfully.
True I don't yet have a success or error message coming back to the user facing page, but I'll get onto that after I've sorted this query out. One thing at a time, right? :)
Ok so now I'll show what makes the particular table input (the one above the file upload ) a little more complicated. In the head of the html facing page, I have also got the following code, within a tag:
$(window).load(function() {
// trigger event when button is clicked
$("#button2").click(function() {
// add new row to table using addTableRow function
addTableRow($(this),$("#speakersName"));
// prevent button redirecting to new page
return false;
});
// function to add a new row to a table by cloning the last row and incrementing the name and id values by 1 to make them unique
function addTableRow(btn,table) {
// clone the last row in the table
var $tr = btn.closest($("tr")).clone(true);
var num; // Current unique field number
// Clear the input fields (that are not the button)
$tr.find(":not(:button)").val("");
// get the name attribute for the input field
$tr.find("input").attr("name", function() {
// break the field name and its number into two parts
var parts = this.id.match(/(\D+)(\d+)$/);
num = parts[2]; //Get the number for later
// create a unique name for the new field by incrementing the number for the previous field by 1
return parts[1] + ++parts[2];
// repeat for id attributes
}).attr("id", function() {
var parts = this.id.match(/(\D+)(\d+)$/);
return parts[1] + ++parts[2];
});
btn.remove();
num++;
// append the new row to the table
$(table).find(".activity_row:last").after($tr);
};
});
And this function works wonderfully on it's own, it pops up new table rows for other input, in a nice unlimited manner. I've used a variation on this once before (for which it was originally written for) but that was not utilising ajax. This version works as expected for the initial input value, but I believe I need some sort of JS foreach function to arrange each of the additional new input text fields into one value, separated by a delimiter such as ^ so that I can break them up in the php and count them there with an explode and foreach.
jQuery is being used.
This is where I'm lost as I do not know how to achieve this. Help warmly received. :)
I carefully study your job at http://jsfiddle.net/k3dj214k/2/
Now, I will try explain all the steps to fix errors:
The form page html:
<form id="ConSupAp_section_3" name="ConSupAp" action="./post.4.ConSupAp.php" method="post" enctype="multipart/form-data"><!-- edited by kazumov#gmail.com -->
<input type="hidden" name="token" value="3e57334833283e22579f77e3a1ade083edf637bd3f4ab8009bbf1f4d7f517fde">
<input type="hidden" name="uID" value="1">
<input type="hidden" name="uaID" value="1">
<input type="hidden" name="appID" value="1">
<input type="hidden" name="ident" value="input_3_1"><!-- edited by kazumov#gmail.com -->
<h2 style="margin: 0 auto 20px;">Conference Support Application - Section 3</h2>
<table id="speakersName" style="width: 100%; height: auto;">
<tbody>
<tr>
<td colspan="3" style="padding: 30px;"><span class="h3">3.1</span>Please list names of guest speaker(s). Use the <strong>+1</strong> button to add addtional speakers.</td>
</tr>
<tr class="activity_row">
<td class="right" style="width: 190px;vertical-align:top">Name of Speaker:</td>
<td id="speakers_list"><!-- edited by kazumov#gmail.com -->
<!--<input type="text" name="s" placeholder="Name of Speaker" value="" required>--><!-- edited by kazumov#gmail.com -->
</td>
<td>
<input type="button" id="btnAddSpeaker" value=" +1 " class="button" style="width: auto !important; margin: 5px; vertical-align:bottom"><!-- edited by kazumov#gmail.com -->
</td>
</tr>
</tbody>
</table>
</form>
I added one hidden input and delete text input. The form tag id should be renamed to ConSupAp_section_3.
The app_ConSupAp.js editions:
Kill doSend_3_1() function
// edited by kazumov#gmail.com
//function doSend_3_1() {
// $.post('./post.4.ConSupAp.php?appID=' + (appID) + '&ident=input_3_1', $('#input_3_1').serialize(), function(data) {
// $("#errorText_3_1").html(data.errorText_3_1);
// $("#resultImg_3_1").html(data.resultImg_3_1);
// }, 'json');
//}
Kill whole module for names manipulation:
// edited by kazumov#gmail.com
// // trigger event when button is clicked
// $("#button2").click(function() {
// // add new row to table using addTableRow function
// addTableRow($(this), $("#speakersName"));
// // prevent button redirecting to new page
// return false;
// });
//
// // function to add a new row to a table by cloning the last row and incrementing the name and id values by 1 to make them unique
// function addTableRow(btn, table) {
// // clone the last row in the table
// var $tr = btn.closest($("tr")).clone(true);
// var num; // Current unique field number
// // Clear the input fields (that are not the button)
// $tr.find(":not(:button)").val("");
// // get the name attribute for the input field
// $tr.find("input").attr("name", function() {
// // break the field name and its number into two parts
// var parts = this.id.match(/(\D+)(\d+)$/);
// num = parts[2]; //Get the number for later
// // create a unique name for the new field by incrementing the number for the previous field by 1
// return parts[1] + ++parts[2];
// // repeat for id attributes
// }).attr("id", function() {
// var parts = this.id.match(/(\D+)(\d+)$/);
// return parts[1] + ++parts[2];
// });
// btn.remove();
// num++;
// // append the new row to the table
// $(table).find(".activity_row:last").after($tr);
// };
append the script page with:
// ---------------------------------------------------
// code addition for phase (3) "Speakers" of "Guests"
// edited by kazumov#gmail.com
// ---------------------------------------------------
$(document).ready(function() {
function addSpeakerNameField() {
var $txtInput = $("<input type=\"text\" name=\"speakers[]\" placeholder=\"Name of Speaker\" value=\"\" required />");// extended notation to create input element, 'id' is not nesessary
$("#speakers_list").append($txtInput);
$txtInput.blur(function(){// change value event
$.post(
"post.4.ConSupAp.php", // your address of page is different, i made temporary php page to debug
$("#ConSupAp_section_3").serialize(),// get all form values
function(data) {
// actually, your html have no tags with id "errorText_3_1" and "resultImg_3_1"
$("#errorText_3_1").html(data.errorText_3_1);// not working
$("#resultImg_3_1").html(data.resultImg_3_1);// not working
},
'json');
});// end of blur()
}
addSpeakerNameField();// the first field
$("#btnAddSpeaker").click(function() { // add one more field
addSpeakerNameField();
});
});
// end of edition by kazumov#gmail.com
As you can see, the important editions are:
a) you should generate all the input text fields from code, because it will create the whole sending routine for all the fields in one place;
b) you should naming the text fields in html like name="speaker[]", because it will create array after serialization;
c) you should adding hidden inputs inside the form, if you want to send static values;
d) i recommend you delete all over-navigation:
and rename the tabs:
Finally, in post.4.ConSupAp.php you will reach the names:
$speakers = $_POST["speakers"];// returns array
And you should to add the header to the post.4.ConSupAp.php
header("Content-type: application/json");
if you expecting the data.errorText_3_1 and data.resultImg_3_1 output to the form.
This looks like a situation where you have a jquery event you would like to bind to a number of elements, but not all of those elements have been created when the event - blur() - is bound.
You can bind events to higher DOM element and use the following syntax to bind events to new elements as they are created:
$("body").on("blur", "input.some_class_name", do_send);
When do_send() is called, "this" will be defined as the element where the event was generated, so you can identify which element needs to be posted:
function do_send(e) {
// "this" is the dom element
var the_id = $(this).attr('id');
var value = $(this).val();
// post away!
}
I have a table as below;
<table>
<tr>
<td id="prev">prev</td>
<td class="content"></td>
<td class="content"></td>
<td class="content"></td>
<td class="content"></td>
<td class="content"></td>
<td id="next">next</td>
</tr>
</table>
and a PHP file, ajax.php for AJAX calls as;
<?php
$array = array(1,2,3,4,5,6,7,8,9,10);
$page = $_POST["page"];
$quantity = 5;
$offset = ($page-1)*$quantity;
$selectedFiles = array_slice($array, $offset, $quantity);
echo $selectedFiles;
?>
The PHP function is suppose to return an array with a limited number of elements with respect to $_POST["page"] like in pagination. The script will return first 5 elements for $page = 1, second 5 elements for $page = 2, etc..etc.. When page loads, the <td>s having id content may display 1,2,3,4 and 5 respectively.
When user click next, it may display next results and may return to previous result if user click prev. How can I do this using JavaScript using jQuery?
It will be more helpful if some effect is given when user clicks and data changes, like sliding (transition), so that it will look like sliding some bar.
Save yourself a TON of time. Use a pre-done grid solution like DataTables that does all this work for you. It allows you to sort, filter, paginate, order, and limit your table results that can be fed via the dom, JSON, or true server-side AJAX.
Since DataTables is such a mature project, it has already overcome all the random issues with cross-browser quirks, etc.
It also includes a pre-done PHP example with the query done for you. Just change to match your table, and voila!
This should help you get started:
<table id="pageLinks">
<tr>
<td id="prev">prev</td>
<td class="content">1</td>
<td class="content">2</td>
...
<td id="next">next</td>
</tr>
</table>
var currPage = 1;
$("#pageLinks tr td").click(function() {
if($(this).hasClass("content")) {
var currPage = $(this).text();
} else {
if(this.id == "next") {
currPage++;
} else {
if(currPage > 1)
currPage--;
}
}
$.post("script.php", {currPage: currPage}, function(html) {
$("#someDiv").hide().html(html).slideUp();
});
});
Notes:
IDs should not be duplicated in a document, so I've given those cells the class 'content' instead.
I don't fully understand your question, so I've assumed that the table is for paginated links, and you're loading in the content elsewhere.