passing Javascript variable to PHP on form submission - php

This question follows from my previous question counting the rows in html table using php.
Since I got no working solution, I want to try a new way but dont know how to implement it.
I assign unique ID to each dynamic row added using Javascript. So the count variable in Javascript stores the number of rows present in HTML table. When i submit the form, it is processed by savedata.php. Is it possible to automatically pass the Javascript variable count to savedata.php each time the form is submitted.
Following is a short version of my Javascript file that is used to create unique IDs for elements of dynamically created rows.
var count=2;
function addRow()
{
var table=document.getElementById("studenttable");
var row=table.insertRow(-1);
var cell15=row.insertCell(14);
var ipt8 = document.createElement('input');
ipt8.setAttribute("type", "hidden");
ipt8.id = "text" + count;
ipt8.name = "htmlrow[]";
ipt8.value = count;
cell15.appendChild(ipt8);
count++;
}
Each time a new row is added, count increments, so just passing it to the PHP file will allow to get the number of rows in HTML table. I want to do it automatically each time the form is submitted.

Add this inside your form..
<input name="NumRows" id="NumRows" type="hidden" value="0"/>
And then modify your JS to update the value...
document.getElementById("NumRows").value = count;
Then, in your PHP you can do...
$NumRows = $_REQUEST['NumRows'];
Note that if for some reason NumRows isn't passed with the form (unlikely here but possible elsewhere) then you should do this in PHP...
$NumRows = isset($_REQUEST['NumRows'])?$_REQUEST['NumRows']:0;
Which means "If $_REQUEST['NumRows'] is set, use it, otherwise set $NumRows to 0"

I would suggest never use $_REQUEST, use $_POST for post method forms. If you use $_REQUEST you have no guarantee that the data came from the post data, which leads to security holes in your script. So better use
$NumRows = $_POST['NumRows'];
to access the count value in PHP

Go for Ajax call. Each time when submit button is clicked make an ajax call and send the required data to the any php page.
here go through these links and they will definitely gonna help u
http://www.w3schools.com/jquery/ajax_post.asp
http://api.jquery.com/jQuery.post/

Related

Implementing Filtering content using jquery ajax and php

I had implemented multiple checkbox filtering for a job portal using jQuery where in I was calling a function every time a checkbox is checked and that function contained an ajax call which would send the request with the checked values and I would do the querying of database and return the result.
But one of the developers I meet told me you should not hit the database continuously for filtering, it should be done client-side.
He also suggested to use AngularJS or Knockout(js) for the purpose, as they work on content, whereas jQuery works on DOM elements.
But if it has to be done client-side, all of the data must be loaded at once during the first visit to the page, which in turn would slow down the page.
And I cannot use class on each element and show/hide them based on the checkbox ID or value something like that, because there are a lot of checkboxes, which I think will be hectic to handle.
How to achieve the desirable result with good performance?
I'm a Newbie to jQuery, so if I have gone wrong anywhere bear with me.
Below is the sample way in which I have actually done:
HTML:
<input type="checkbox" name="location[]" value="Bangalore" onclick="loadresult()">Bangalore
JS:
function loadresult() {
location array value accessed and passed to ajaxcall
//ajax call to processresult.php
Displaying the DB returned Data
}
PHP (processresult.php):
<?php
//dbconnection + querying db and returning result
?>
There is significant difference. Angular is a framework and jQuery is a library.
With jQuery it much simpler to modify DOM elements deal with events and do some more cool stuff. But you define how you deal with data on your own. You can easily move your data to Js object or array of objects and render this data to your DOM tree.
For example:
//let's presume that you are searching something
var someUsers = [{id: 1,name:'User 1'},{id: 2,name:'User 2'},{id: 1,name:'User 3'}];
var usersTemplate = _.template("<h1>User name: <%= user.name %></h1>");
var $container = $('#someRenderContainer');
someInputFeild.on('keypress', function(){
var searchText = someInputFeild.text();
var foundUsers = someUsers.filter(function(item, index){
item.name.indexOf(searchText) !== -1
});
render($container,foundUsers);
})
function render($container,users){
users.forEach(function(item){
$container.append(usersTemplate(item));
})
}
Here is simple example where you can see that your manipulate with data in the memory but not in DOM. Similar things you can do with your checkboxes.
I would just make one ajax request in the beginning, fill the page with data, marking every row with class name
jQuery.each(d, function(i,data) {
$("table.content").append("<tr class=\""+data.city+"\"><td>" + data.tag + "</td><td>" + data.city + "</td><td>" + data.num + "</td><td>" + data.state + "</td></tr>");
});
and use checkboxes to hide and show marked rows using jQuery hide(), show() methods.
Rows can have multiple classes meaning filtered by multiple columns, but logic will get more complicated.
see example http://jsfiddle.net/elshnkhll/czdongkp/
I would use cache technique to improve my performance.
We can't load our full record on a single page. It will slow down the main page loading.
But we can save loaded data in a variable with some key combination for different filter and page no..
eg. if we are loading data fir index page with no filter, the my key will be index and my variable will be like var cachevar = {"index":{1:"<my response>"}}, here "1" is page number
And if data is using filter, then my variable index key will be combination of filter ids saperated by '-'.
eg var cachevar = {"index":{1:"<my response>"}, "index-2-5-3":{1:"my response"}}
If user request a page, I just have to check if that page is available in cache or no, if it's available in cache variable, then show it, else request it from server.

How to get the array of <form> elements in php?

With php, I dynamically create a form with a variable number of "select" in it.
When user has done his selections, he hits a button that launches another php.
I now want to browse through all form elements, but have no idea on how to get the array of form elements with their respective name.
I know how to retrieve the value for a given select when I have its name, but as the select elements in the form are different each time, I cant use the name directly, but would need the array of form elements.
So, as I understand the question: form is created dynamically (with dynamic names) so you don't know what's being POST'd and what the other options were in your handler. I suggest using javascript to solve this - in the form, add an onSubmit="saveForm();" and then, in that function saveForm, you'll have to grab all the form elements and put them into some format your PHP can interpret. Pseudocode:
function saveForm(){
var outputString="[";
var theInputs=document.querySelectorAll("input, select");
for (var x=0; x<theInputs.length; x++){
outputString+="\""+theInputs.name+"\", ";
}
outputString=outputString.substring(0,outputString.length-2)+"]";
var hiddenInput=document.createElement("input");
hiddenInput.name="formNames";
hiddenInput.value=outputString;
document.body.appendChild(hiddenInput);
}
That way, a variable will be set in $_POST['formNames'] that will be equivalent to a string representation of an array containing all the names of the form elements. You can loop through that array to get the $_POST data from each one of them.
I found the solution. I can do:
foreach($_POST as $eid){
and $eid will then be every element I have in my form

How to send info on HTML elements via POST?

I want to send the properties of HTML elements as data via POST, for example whether an element is visible or not?
You cannot do it with PHP and HTML alone, since the HTML form would only post a form input's name. You would need to add some JavaScript, which at the time the form is submitted, would iterate over all its inputs and modify their values to include the attribute values as well.
Example:
yourform.onbeforesubmit = function() {
// Loop over form elements and append -visible or -hidden to its value based on CSS style
// jQuery selectors like .is(":visisble") would help a lot here.
// This is just a basic example though - it would require an explicit visibility CSS rule on each
// input element...
for (var i=0; i<yourform.elements.length; i++) {
yourform.elements[i].value = += "-" + yourform.elements[i].style.visibility;
}
}
Another method would be rather than to modify the values of the inputs themselves, keep a hidden input for each visible user input and set the attributes as the value to the hidden input rather than the visible input.
You can not do this with PHP. You will need to use Javascript to determine this information and then either send an Ajax Request or add this information to an existing form.
To elaborate a bit more: PHP is executed Server Side and then sent to the Client (Browser). The Server is not aware of the state of the HTML Elements in the Browser.
As far as i can tell you have a form that is submitted anyway? So add a piece of javascript which is called before the form is submitted (onsubmit property of the form) and have it read out the status of the elements (visible, hidden, ...) and set this information to some hidden form fields.
Make sure the javascript that is called before the form is submitted is returning true, otherwise the action gets cancelled.
In ajax.
Try Prototype Framework, it is really easy to use!
http://prototypejs.org/api/ajax/request
If you want to do that I suppose you will have to create some hidden fields and javascript that would fill them in with information depending on your elements attributes. As far as I know there is no other way.
You have to define your data definition standard first: what do you want to store, and under what name.
then, imho you have to serialize the result and send it through POST, for finally unserializing it once at the server.
Use JSON serialization for an effective way of proceeding.
Include Hidden inputs using PHP like the following:
<input type="hidden" id="hidden1" name="hidden1" value="<?php if(condition) echo "default"; else echo "default";?>">
This default value can be set by PHP during page load, for transferring extra hidden data from one page load to another. But can also be modified by javascript after page load:
<script type="text/javascript">
document.getElementById("hidden1").value="true";
</script>
Note: PHP can change the value of any hidden or non-hidden element only during the next page load. It doesn't have any control over the HTML it sends to the browser. This is why you need Javascript(Client side scripting).

beginner Javascript ajax form help

Hello all I'm new to this whole thing still.
I would like some help figuring out how to do this please. I can pull info out of a database and put stuff in using ajax/javascript but I cant figure out how to complete the problem below. I want to be able to make my php form submit and update with out page refresh.
Example.
Page1. Main page
-Drop down
javascript/Ajax on change of dropdown get info from page 2.
Form from page two now displays without page refresh on change of drop down.
When submit button from page two is pressed inserts form data into Mysql database.
Once new data is submitted into sql data base the form updates and shows data in mysql database for the specific ID in the drop down.
Page2.
form drop down info.
Form is filled with info if there is data in the database for it.
Javascript/Ajax on button submit sends input fields to page 3
Page 3.
insert data into mysql using javascript/ajax so no page refresh is required
Thanks
You need to loop through all the input fields in your form, package them into a query string, and send that to your form processing page.
Something like
var queryString = '';
for(var i = 0; i < document.formName.elements.length; ++i) {
queryString += document.formName.elements[i].name + '=';
queryString += document.formName.elements[i].value + '&';
}
//trim off the last '&' here
If you're using select boxes, you'll have to identify them in the loop above and extract their value a little differently. The query string format I used here is for a POST query; in a GET query, you need to append this to the url of the form processing page with a '?'
Consider the following example using jQuery (though you could adapt this to raw js or a different js library):
function doSubmit(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
type: 'post',
data: $this.serilaize(),
success(responseHtml) {
// assume responseHtml is the next form
var newForm = ajaxifiyForm($('form', responseHtml));
$this.unbind('submit').replaceWith(newForm);
}
});
return false;
}
function ajaxifyForm(form) {
return $(form).submit(doSubmit);
}
$(document).ready(function(){
ajaxifyForm($('#your-form'));
});
Here we rely on the first page load to have the form already included on the server side. When the DOM is ready we attach an event handler to the submit event of the form. This handler overrides the normal submission process and instead uses ajax. It submits to the URL we specified in the action attribute.
When a post is successful it takes the HTML response from that post and replaces the original form with it after applying the same handler we used on the original form. This relies on the assumption that the php script(s) we are posting to always return the next form with all its values filled out.
Keep in mind you can submit file data in this way. Youd need to use an iframe as an intermediary to do that (there are other ways to do this as well that doesnt use an iframe). you can google ajax file upload for solutions to that problem.

Get form checkbox values and pass them through pagination?

I need to get values from some selected checkboxes and pass those values through pagination in php/mysql. If on another page user selects other checkboxes, I need to add their values to array selected earlier.
I need this for a product comparison page. In short I need to:
get the checkbox values
store them
include the checkbox values from other pages in pagination
and when user selects "compare" send that array to compare page.
Anybody know how to do this? Related examples would be appreciated?
There are different ways to maintain state across pages, including cookies, session variables, hidden inputs, passing them in the querystring, persisting to database, etc. In this case I would probably use a session variable.
For more info on PHP session see PHP Sessions.
One solution would be to load all of the pages at once in their own divs inside of a form. When you click on a new page link, hide all divs except the one you need to show. That way all checkboxes are submitted in the same form, making it easier to handle server-side. That of course depends on how heavy each individual page is and how many pages there are.
Another solution would be to keep a session variable, tracking what was clicked. Each time someone clicks to go to another page. POST to the server a list of the checkboxes.
You could do it by using javascript to store the checkbox selection in a cookie. Here's some sample code to get you going in the right direction.
var aa_checkbox;
function init_checkbox(){
//setup blank cb cookie
if(!Cookie.read('cb')){
Cookie.write('cb', JSON.encode({}));
}
//setup "associative array" to match what is currently in the cookie
aa_checkbox = JSON.decode(Cookie.read('cb'));
//set up each checkbox with class="remember_cb"
$$('input.remember_cb').each(function(el){
//mark checked if it is in the cookie
if(aa_checkbox[el.name]){
el.checked = 'checked'
}
//setup onclick event to put checkbox status in the
el.addEvent('click', function(){
if(el.checked){
aa_checkbox[el.name] = 1;
}else{
delete(aa_checkbox[el.name]);
}
})
})
//save aa_checkbox back into cookie upon leaving a page
window.onbeforeunload = function(){Cookie.write('cb', JSON.encode(aa_checkbox));};
setup_form();
return true;
}
function setup_form(){
//set up form so that it adds the inputs upon submit.
$$('form.remember_cb_form').each(function(form){
form.addEvent('submit', function(ev){
//clean up previously inserted inputs
var aa_hidden_insert = $$('input.hidden_insert');
$each(aa_hidden_insert, function(el){
el.parentNode.removeChild(el);
})
var el_form = this;
//insert hidden elements representing the values stored in aa_checkbox
$each(aa_checkbox, function(i_value, s_name){
if(i_value){
var el_input = document.createElement('input');
el_input.type = 'hidden';
el_input.value = i_value;
el_input.name = s_name;
el_input.setAttribute('class', 'hidden_insert');
el_form.appendChild(el_input);
}
});
});
});
}
window.addEvent('domready', init_checkbox);
There is a working demo here and a more thorough explanation here
Your pagination links could actually perform a form POST, then read the checkbox[] in ur php script, and update a hidden form element or add the value to a session, anything stateful. so your anchor could look something like
<a href="#" onclick="document.myform.submit()">next&lt/a>

Categories