Pre-fill a form (no control over form code) - php

I'm using a form plugin / addon where I don't have control over how the form is generated.
The form generates HTML which looks like this:
<form>
<label>First Name</label><input name="Question25" type="text" value="" />
<input class="formBlockSubmitButton" name="add" type="submit" value="Submit" />
</form>
I would like to prefill some of the form values but I can't write, say
<input name="Question25" type="text" value="<?php echo $my_value; ?>" />
Because the form addon generates that HTML. I can write PHP or Javascript before this block, is there a way to search for an input with a name of "Question25" and then prefill it when the block comes up?

You could use jQuery and the .val() method:
<script type="text/javascript">
$(function() {
$('input[name="Question25"]').val('some value');
});
</script>
and if the value must come from the server:
<script type="text/javascript">
$(function() {
var obj = <?php echo json_encode(array('value' => $my_value)); ?>;
$('input[name="Question25"]').val(obj.value);
});
</script>

You can emit all the values you'd like to search as an array of fieldname/values, and then emit a function that tries to map those values to those fields.
<script type="text/javascript">
var values = [{fieldName:'Question25', value:'MyValue'}]; // iterate through your values in PHP and generate the {fieldName:'value',value:'value'} object
$(function() {
$.each(values, function(index, item) {
$('input[name=' + item.fieldName + ']').val(item.value);
});
});
</script>

var value='<?php echo $my_value; ?>'
$("input:text[name='Question25']").val(value);
use something like this

Use Javascript. With jQuery, you could do something along the lines of:
$("input[name=Question25]").val(my_value);
You can then insert PHP vairables into the Javascript with echo, load them with AJAX, or whatever you need.

Related

$_POST for text in DIV elements

Because of my web style, i don't want to use input & textarea and get information by using $_POST[] and i need to get information that is in DIV element.
For example , I want to get information in this :
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
and :
$_POST[myname];
But i can't do it with $_POST , How can i do it ??
And if this method can't do this , do you know any other method to get information from DIV like this ?
you can call a onsubmit function and make a hidden field at the time of form submission like this
HTML
need to give a id to your form id="my_form"
<form action="submit.php" method="post" id="my_form">
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="submit" value="submit" name="submit" />
</form>
Jquery call on submit the form
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.mine').text();
$(this).append("<input type='hidden' name='myname' value=' " + hvalue + " '/>");
});
});
PHP : submit.php
echo $_POST['myname'];
You can use this method. First, with javascript get content of <div>
Code:
<script type="text/javascript">
var MyDiv1 = Document.getElementById('DIV1');
</script>
<body>
<div id="DIV1">
//Some content goes here.
</div>
</body>
And with ajax send this var to page with get or post method.
You would need some JavaScript to make that work, e.g. using jQuery:
$.post('http://example.org/script.php', {
myname: $('.mine').text()
});
It submits text found inside your <div> to a script of your choosing.
You can use following structure;
JS:
$(document).ready(function() {
$("#send").on("click", function() {
$.ajax({
url: "your_url",
method: "POST",
data: "myname=" + $(".mine").text(),
success: function(response) {
//handle response
}
})
})
})
HTML:
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="button" name="send" id="send" value="Send"/>
You can see a simulation here: http://jsfiddle.net/cubuzoa/2scaJ/
Do this in jquery
$('.mine').text();
and post data using ajax.
Put the content of DIV in a variable like below:
var x = document.getElementById('idname').innerHTML;

compact all form-data with javascript

I would like to compact all data from a huge HTML-form with over a 1000 variables to circumvent the max_input_vars limit in PHP versions before 5.3.9.
How can I read all data in the HTML-form with javascript, serialize it (or create json) to put it all in only one hidden field that contains the whole data then?
On the receiving side I would uncompress it with PHP (for example with json_decode)
Just sent a ajax post?
form.html with javascript
<form action="process.php" method="post" id="form">
<input type="text" name="name">
<input type="text" name="username">
<button type="submit" id="sendForm">Send</button>
</form>
<!-- YOUR JAVASCRIPT -->
<script type="text/javacript">
$('#sendForm').click(function() {
$.ajax({
type: 'POST',
url: $('#form').attr('action'),
data: $('#form').serialize(),
success: function(data) {
// WHATEVER YOU WANT HERE
}
});
return false;
});
</script>
process.php
<?php
$name = $_POST['name'];
// other form fields here
}
Serialize it using JQuery. You can then parse the URL string using PHP.
perhaps serialize and JSON.stringify may work together, though I have not tried it.
I created a script that does the job on all post forms automatically:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
// this disables all form elements and creates only one new element that contains all data serialized
$('form[method="post"]').submit(function() {
var num_form_elements=$(this).find('input, select, textarea').not('[type="submit"]').length;
var num_elements_already_disabled=$(this).find('input:disabled, select:disabled, textarea:disabled').length;
enabled=(num_form_elements-num_elements_already_disabled);
if($('textarea[name="serialized_data"]', this).length > 0) {
alert("Backbutton is not supported yet!");
return false;
}
if($('textarea[name="serialized_data"]', this).length > 0 || enabled<=0) {
alert("Reload of the form is not supported yet!");
return false;
}
var data=$(this).serialize();
$(this).find('input, select, textarea').not('[type="submit"]').attr("disabled", true);
$(this).append(' <input type="hidden" name="num_form_elements" value="'+num_form_elements+'">');
$(this).append(' <input type="hidden" name="num_elements_already_disabled" value="'+num_elements_already_disabled+'">');
$(this).append(' <textarea style="display:true" name="serialized_data">'+(data)+'</textarea>');
// maybe in the textarea I have to .replace(/</g,'<') ?
});
</script>
On the receiving side you cannot use the PHP parse_str() function because the max_input_vars directive affects this function too, so you need something else: I took my_parse_str() from https://gist.github.com/rubo77/6821632
<?php
$params=my_parse_str($_REQUEST['serialized_data']);
echo count($params,1)." serialized variables:<br>";
var_export($params);
?>
Example script on https://gist.github.com/rubo77/6815945

sending form data to php using ajax

I Have an requirement to pass form data to php using ajax and implement it in php to calculate the sum , division and other arithmetic methods I am a new to ajax calls trying to learn but getting many doubts....
It would be great help if some one helps me out with this
index.html
<script type="text/javascript">
$(document).ready(function(){
$("#submit_btn").click(function() {
$.ajax({
url: 'count.php',
data: data,
type: 'POST',
processData: false,
contentType: false,
success: function (data) {
alert('data');
}
})
});
</script>
</head>
<form name="contact" id="form" method="post" action="">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
In count.php i want to implement
<?php
$FNO = ($_POST['FNO']);
$SNO=($_post['SNO']);
$output=$FNO+$SNO;
echo $output;
?>
(i want to display output in count.php page not in the first page index.html)
Thanks for your help in advance.
You can use a simple .post with AJAX. Take a look at the following code to be able to acheive this:
$('#form').submit(function() {
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("count.php",$(this).serialize(),function(data){
alert(data); //check to show that the calculation was successful
});
return false; // return false to stop the page submitting. You could have the form action set to the same PHP page so if people dont have JS on they can still use the form
});
This sends all of your form variables to count.php in a serialized array. This code works if you want to display your results on the index.html.
I saw at the very bottom of your question that you want to show the count on count.php. Well you probably know that you can simply put count.php into your form action page and this wouldn't require AJAX. If you really want to use jQuery to submit your form you can do the following but you'll need to specify a value in the action field of your form:
$("#submit_btn").click(function() {
$("#form").submit();
});
I have modified your PHP code as you made some mistakes there. For the javscript code, i have written completely new code for you.
Index.html
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<form name="contact" id="contactForm" method="post" action="count.php">
<label for="FNO">Enter First no:</label>
<input type="text" name="FNO" id="FNO" value="" />
<label for="SNO">SNO:</label>
<input type="text" name="SNO" id="SNO" value="" />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</form>
<!-- The following div will use to display data from server -->
<div id="result"></div>
</body>
<script>
/* attach a submit handler to the form */
$("#contactForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
//Get the first value
value1 = $form.find( 'input[name="SNO"]' ).val(),
//get second value
value2 = $form.find( 'input[name="FNO"]' ).val(),
//get the url. action="count.php"
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { SNO: value1, FNO: value2 } );
/* Put the results in a div */
posting.done(function( data ) {
$( "#result" ).empty().append( data );
});
});
</script>
</html>
count.php
<?php
$FNO = $_POST['FNO'];
$SNO= $_POST['SNO'];
$output = $FNO + $SNO;
echo $output;
?>
There are a few things wrong with your code; from details to actual errors.
If we take a look at the Javascript then it just does not work. You use the variable data without ever setting it. You need to open the browser's Javascript console to see errors. Google it.
Also, the javascript is more complicated than is necessary. Ajax requests are kind-of special, whereas in this example you just need to set two POST variables. The jQuery.post() method will do that for you with less code:
<script type="text/javascript">
$(document).ready(function(){
$("#form").on("submit", function () {
$.post("/count.php", $(this).serialize(), function (data) {
alert(data);
}, "text");
return false;
});
});
</script>
As for the HTML, it is okay, but I would suggest that naming (i.e. name="") the input fields using actual and simple words, as opposed to abbreviations, will serve you better in the long run.
<form method="post" action="/count.php" id="form">
<label for="number1">Enter First no:</label>
<input type="number" name="number1" id="number1">
<label for="number2">Enter Second no:</label>
<input type="number" name="number2" id="number2">
<input type="submit" value="Calculate">
</form>
The PHP, as with the Javascript, just does not work. PHP, like most programming languages, are very picky about variables names. In other words, $_POST and $_post are not the same variable! In PHP you need to use $_POST to access POST variables.
Also, you should never trust data that you have no control over, which basically means anything that comes from the outside. Your PHP code, while it probably would not do much harm (aside from showing where the file is located on the file system, if errors are enabled), should sanitize and validate the POST variables. This can be done using the filter_input function.
<?php
$number1 = filter_input(INPUT_POST, 'number1', FILTER_SANITIZE_NUMBER_INT);
$number2 = filter_input(INPUT_POST, 'number2', FILTER_SANITIZE_NUMBER_INT);
if ( ! ctype_digit($number1) || ! ctype_digit($number2)) {
echo 'Error';
} else {
echo ($number1 + $number2);
}
Overall, I would say that you need to be more careful about how you write your code. Small errors, such as in your code, can cause everything to collapse. Figure out how to detect errors (in jQuery you need to use a console, in PHP you need to turn on error messages, and in HTML you need to use a validator).
You can do like below to pass form data in ajax call.
var formData = $('#client-form').serialize();
$.ajax({
url: 'www.xyz.com/index.php?' + formData,
type: 'POST',
data:{
},
success: function(data){},
error: function(data){},
})

Jquery Onclick Change hidden parameter and submit

Hi i'm using php and jquery. I have create dinamically a list of a div like that
<div class="divclass" id="<?php echo $i-1;?>">
<a href=" <?php echo $this->url(array('controller'=>'controller name','action'=>'action name'));?>">
<span>Date: </span>
</a>
</div>
My javasctipt script is, i pick the name of the id clicked, i set the hidden parameter to the name of the id and i want to submit the form
<script type="text/javascript">
$(document).ready(function() {
$('.divclass').click(function(){
var idarray = $(this).attr("id");
document.getElementById('testo').value=idarray;
document.forms["prova"].submit();
});
});
The form is:
<form id="prova" method="post" action="<?php echo Zend_Controller_Front::getInstance()->getBaseUrl().'/controller-name/action-name';?>">
<input type="hidden" value="" id="testo">
</form>
</script>
But in the next page i don't have the post parameter.
You need to give name attribute to #testo and then try this:
e.g
<input type="hidden" value="" id="testo" name="testo">
Your form is within <script> tag, Place it outside of <script> tag.
and write following code within DOM ready like follwing:
<script type="text/javascript">
$(function() {
// after DOM ready
$('.divclass').click(function(){
var idarray = $(this).attr("id"); // or this.id do the same thing
$('#testo').val(idarray); // set value to testo
$("form#prova").submit(); // submit the form
});
});
</script>

submit form using Jquery Ajax Form Plugin and php?

this a simple example in how to submit form using the Jquery form plugins and retrieving data using html format
html Code
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',
// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>
<form id="htmlForm" action="post.php" method="post">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>
PHP Code
<?php
echo '<div style="background-color:#ffa; padding:20px">' . $_POST['message'] . '</div>';
?>
this just work fine
what i need to know if what if i need to Serialize the form fields so how to pass this option through the JS function
also i want show a loading message while form processed
how should i do that too
thank you
To serailize and post that to a php page, you need only jQuery in your page. no other plugin needed
$("#htmlForm").submit(function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData}, function(data) {
//do whatever with the response here
});
});
If you want to show a loading message, you can do that before you start the post call.
Assuming you have div with id "divProgress" present in your page
HTML
<div id="divProgress" style="display:none;"></div>
Script
$(function(){
$("#htmlForm").submit(function(){
$("#divProgress").html("Please wait...").fadeIn(400,function(){
var serializedData= $("#htmlForm").serialize();
$.post("post.php", { dat: serializedData},function(data) {
//do whatever with the response here
});
});
});
});
The answer posted by Shyju should work just fine. I think the 'dat' should be given in quotes.
$.post("post.php", { 'dat': serializedData},function(data) {
...
}
OR simply,
$.post("post.php", serializedData, function(data) {
...
}
and access the data using $_POST in PHP.
NOTE: Sorry, I have not tested the code, but it should work.
Phery library does this behind the scenes for you, just create the form with and it will submit your inputs in form automatically. http://phery-php-ajax.net/
<?php
Phery::instance()->set(array(
'remote-function' => function($data){
return PheryResponse::factory('#htmlExampleTarget')->fadeIn('slow');
}
))->process();
?>
<?php echo Phery::form_for('remote-function', 'post.php', array('id' => ''); ?> //outputs <form data-remote="remote-function">
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</form>
<div id="htmlExampleTarget"></div>
</body>
</html>

Categories