Passing in form field value to PHP file - php

I'd like to do a dynamic search function using jQuery and PHP.
I'm struggling passing the HTML form field to the JQUERY function (which would then get passed to the PHP file).
My major questions are:
1) How do I pass form "Input" field into Jquery function?
2) How do I get the PHP result in the form "Output" field?
I currently have... (simplified)
JQUERY:
$.get("SEARCH.php", {"_input" : $('input[name=input]').val()},
function(returned_data)
{
$("input[name=output]").val(returned_data);
}
SEARCH.php:
$input = 'Welcome ' . $_GET['_input'];
echo $input;
//should be "Welcome" plus whatever I type in to "input"
HTML FORM:
input: <input type="text" name="input" value="" />
output: <input type="text" name="output" id="output" />
Thank you!

jQuery
$.get("SEARCH.php", {"_input" : $('input[name=input]').val() },
function(returned_data) {
$("input[name=output]").val( returned_data );
}
HTML
input: <input type="text" name="input" value="" />
output: <input type="text" name="output" />
PHP Use echo instead of return since it looks that your code isn't in function:
$input = $_GET['_input'];
do some parsing of the input
echo $result;

jQuery
$.get("SEARCH.php", {"_input" : $('input[name=input]').val() },
function(returned_data) {
$('#output').val(returned_data);
});
PHP
$input = $_GET['_input'];
do some parsing of the input
echo $result; // not return
HTML
input: <input type="text" name="input" value="" />
output: <input type="text" name="result" id="output" value="" />

Related

Workaround for 'max_input_vars' limit

Currently I'm working on a large form with dynamic number of input fields, it can get extremely large (above 3k variables or more) and it causes problems with 'max_input_vars' option.
I'm looking for a workaround for this issue (I'm not interested in increasing the value of 'max_input_vars' option), so currently I'm trying to join all form fields values into single field (using jQuery serialize() method) and then recreate the variables on the server side.
This is what I have so far:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Workaround for max_input_vars</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<?php
if($_SERVER["REQUEST_METHOD"]==="POST" && !empty($_POST["data"])) {
$vars = explode("&", $_POST["data"]);
$data = array();
foreach($vars as $var) {
parse_str($var, $variable);
assign_var($_POST, $variable);
}
echo "<pre>";
var_dump($_POST);
echo "</pre>";
}
function assign_var(&$target, $var) {
$key = key($var);
if(is_array($var[$key]))
assign_var($target[$key], $var[$key]);
else {
if($key==0)
$target[] = $var[$key];
else
$target[$key] = $var[$key];
}
}
?>
<form id="myForm" method="POST">
<input type="text" name="var_1" value="<?php echo htmlentities("double quote: \"hello\"");?>"/><br/>
<input type="text" name="var_2" value="<?php echo htmlentities("single quote: 'hello'");?>"/><br/>
<input type="text" name="var_3" value="<?php echo htmlentities("text with & ampersant");?>"/><br/>
<input type="text" name="var_4" value="<?php echo htmlentities("animals");?>"/><br/>
<input type="text" name="matrix[]" value="1"/><br/>
<input type="text" name="matrix[]" value="2"/><br/>
<input type="text" name="matrix[]" value="3"/><br/>
<input type="text" name="matrix[]" value="4"/><br/>
<input type="text" name="matrix[]" value="5"/><br/>
<input type="text" name="matrix[]" value="6"/><br/>
<input type="text" name="matrix[]" value="7"/><br/>
<input type="text" name="var_5" value="abc"/><br/>
<input type="text" name="var_6" value="bcd"/><br/>
<input type="text" name="var_7" value="cde"/><br/>
<input type="text" name="var_8" value="def"/><br/>
<input type="text" name="multi_matrix[colors][]" value="red"/><br/>
<input type="text" name="multi_matrix[colors][]" value="blue"/><br/>
<input type="text" name="multi_matrix[colors][]" value="green"/><br/>
<input type="text" name="multi_matrix[weight][]" value="75"/><br/>
<input type="text" name="multi_matrix[weight][]" value="83"/><br/>
<input type="text" name="multi_matrix[weight][]" value="62"/><br/>
<input type="text" name="multi_matrix[height][]" value="170"/><br/>
<input type="submit" value="Send">
</form>
<style>
input {
margin: 5px 0;
}
</style>
<script type="text/javascript">
(function(){
$(function(){
$("#myForm").submit(function(event) {
var $this = $(this);
var data = $this.serialize();
$this.find("input, textarea, select, button").remove();
$this.append("<input type='hidden' class='data' name='data'/>");
$this.find("input.data").val(data);
});
});
})(jQuery);
</script>
</body>
</html>
As you can see, I'm intercepting the submit event and replace all form fields with single 'data' field. On PHP side I'm using explode() and pars_str() methods to recreate the variable, lastly I want to put the variable into $_POST array, so I created simple recursive function that can handle simple values and multidimensional associative arrays.
The result is a $_POST array filled with form values, as if the form was submitted normally.
What do you think about above method ? Maybe there's a much simpler solution to the problem that I hadn't noticed earlier ? If not, are there any options to improve the above code ? Are there any negative side effects of the above solution ?
Thanks in advance !

Javascript and Php (MVC)

i'm creating my own MVC Framework.
I have a basic form in my view
<form action="?" method="post" >
<input type="hidden" name="envoie" value="envoie" />
<?php dico('INSCRIPTION_NOM'); ?><input id="name" type="text" name="name" /><br />
<?php dico('INSCRIPTION_EMAIL'); ?><input id="email" type="text" name="email" /><br />
<?php dico('INSCRIPTION_PWD'); ?><input id="pwd" type="password" name="pwd" /><br />
<input type="button" value="<?php dico('INSCRIPTION_SINSCRIRE'); ?>" onclick="verifForm(document.getElementById('email').value);"/>
</form>
when I clock on the button they have a javascript function like that :
function verifForm(email) {
var url ="?c=Inscription&a=VerifForm&email="+email;
$.get(url, function(data){
alert('resultat == '+data);
});
}
Inscription was my controllers and VerifForm an method of the controller. email was the value of a input.
The Php function was :
public function actionVerifForm() {
echo "OK";
}
When i click on the button i have all the code of the page on my alert but i only want the message "OK".
Thanks for helping me
what you are doing is AJAX, am i right? the data parameter IS your result. AJAX returns the echo-ed page as a string. if you mean to place it in the page, try jQuery .html() or .text() for a text only, escaped version.
function verifForm(email) {
var url ="?c=Inscription&a=VerifForm&email="+email;
$.get(url, function(data){
$('#container-id-here').html(data); //html insert
$('#container-id-here').text(data); //text insert
});
}
and in your PHP, since you are doing AJAX, you should only echo what you need returned, and not the whole HTML mark-up (which means no <html><head>...</head></html>

How to get Input value 1 by 1 from jquery to PHP

<script type="text/javascript">
// index.php
function get(){
$('#age').hide();
$.post('data.php',{ name: $('form').serialize() },
function (output){
$('#age').html(output).fadeIn(1000);
});
}
</script>
<body>
<form name="form" action="a.php">
<input type="text" name="name[]" value="1"/>
<input type="text" name="name[]" value="2"/>
<input type="button" value="Get" onclick="get();"/>
</form>
<div id="age">
</div>
but result show
Array ( [name] => name%5B%5D=1&name%5B%5D=2 )
I want to get 1 by 1 value. so that I can collect data from database running a query to based on value please, kindly help me
data.php:
<?php //data.php
echo "<pre>";
print_r($_POST);
echo "</pre>";
?>
This approach only works when you POST the form normally, using submit.
You now need to unserialize the data:
<?php
var_dump(unserialize($_POST['name']));
?>
This line
$.post('data.php',{ name: $('form').serialize() },
Says that you post your form (serialized) as the value of key 'name'. While this is possible, I presume you just want your values.
If you take a quick look over at the jquery post manual youc an see that you can make an object like this:
{ name: "John", time: "2pm" }
Just read your form-values with jquery and put them in an object like that, instead of serializing the form.
I'm not sure if I understand your question, but I'm guessing you're not receiving the correct value in your php file?
Try this --
In your HTML file, use this:
<script type="text/javascript">
// index.php
function get()
{
$('#age').hide();
$.post('data.php',
{
"name1":$('#name1').val(),
"name2":$('#name2').val()
},
function (output){
$('#age').html(output).fadeIn(1000);
});
}
</script>
<body>
<form name="form" action="a.php">
<input type="text" name="name1" id="name1" value="1"/>
<input type="text" name="name2" id="name2" value="2"/>
<input type="button" value="Get" onclick="get();"/>
</form>
and in your php page, have this:
<?php
echo "<pre>";
echo "this is the first input: " . $_POST['name1'] . "<br />";
echo "this is the second input: " . $_POST['name2'] . "<br />";
echo "</pre>";
?>
Hope I interpreted your question correctly.

Removing empty Input Elements from a form

I have a simple form that goes on to create all the form and validation requirements for codeigniter. What I want to do is filter out any empty inputs prior to serialization so that I do not create form inputs and form validation set rules. I am at a loss as to how to go about this. Where I have the alert in the Jquery is where I want to remove any empty inputs(again prior to serialization). At this point what I am using does not detect empty form fields. Without the detection code the entire system works fine. Here is what I am using
<h1>Field Name</h1>
<form action="Form.php" onsubmit="return false;" id="form" method="post">
<input type="text" name="v1" id="v1" />
<input type="text" name="v2" id="v2" />
<input type="text" name="v3" id="v3" />
<input type="text" name="v4" id="v4" />
<input type="text" name="v5" id="v5" />
<input type="text" name="v6" id="v6" />
<input type="submit" name="send" id="send" value="Send" />
</form>
<hr />
<script>
$(function(){
$('#send').click(function(){
---------------------------------------
$(":input").each(function() {
if($(this).val() === "")
alert("Empty Fields!!"); //using alert just to see if empty fields are detected.
return false;
});
-----------------------------------------
var data = $('#form').serialize();
$.ajax({
type: "POST",
data: data,
url: "Form.php",
success: function(msg){
if(msg){
$('#display').html(msg).show();
}else{
$('#display').text("<p>nothing came back</p>");
}
}
});
return false;
});
});
I am simply trying to avoid printing out empty form fields
<p>
<label for=""></label> <br />
<input type="text" name="" id="" /> <br />
<label class="error" id=""> This field is required</label> <br />
<p/>
Thank you for your time
This will remove all the text fields which have a value of length 0:
$('#send').click(function(){
$(':input[type="text"]').filter(function(e){
if (this.value.length===0){
return true;
}
}).remove();
});
example: http://jsfiddle.net/niklasvh/ZBSyX/
You should use a regex expression using \s as the search query. So /^(\s)*$/ as the regex and just make sure input does not match this.
Sorry but I am not familiar with Jquery or I would write the code out exactly.
$('#send').click(function(){
//---------------------------------------
$(":input").each(function() {
if($(this).val() === "")
alert("Empty Fields!!"); //using alert just to see if empty fields are detected.
return false;
});
And you're not getting an error from this? The first lambda's scope isn't closed.
Use Firebug to highlight errors that you might be getting and post those.
To hide elements that have no value assigned:
$('input:text[value=""]').hide();
But, of course, if a value="x" attribute is provided in the html this will result in the element being shown.

jQuery: find id of of a form field

I am creating a dynamic form where the user will have the ability to add a set of inputs to the form. The html looks like this:
<form>
<input id="title1" class="title" name="title1" type="text" value="">
<input id="productionCompany1" name="productionCompany1" type="text" value="">
<input id="year1" name="year1" type="text" value="">
<input id="role1" name="role1" type="text" value="">
<div id="newCredit"> </div>
add another credit
</form>
When the user clicks the link with the id of "addCredit" the following jQuery script is called:
$(document).ready(function() {
var $ac = $('#addCredit');
$ac.click(function() {
/* the following two lines are where the problem lies? */
var $credInt = $(this).prev(".title");
$.get("addCredit.php", {num: $credInt},
function(data){
$('#newCredit').append(data);});
return false;
});
});
The jQuery function queries a php file called "addCredit.php", which looks like this:
<?php
$int = $_GET["num"];
$int = substr($int, -1);
$int++;
?>
<input id="title<?php echo $int;?>" class="title" name="title<?php echo $int;?>" type="text" value="">
<input id="productionCompany<?php echo $int;?>" name="productionCompany<?php echo $int;?>" type="text" value="">
<input id="year<?php echo $int;?>" name="year<?php echo $int;?>" type="text" value="">
<input id="role<?php echo $int;?>" name="role<?php echo $int;?>" type="text" value="">
My problem is getting the javascript variable $credInt set properly so that it can be sent to the addCredit.php page and update the form fields accordingly. I also need to be sure that every time the form is appended, the next value sent is the incremented value.
Any thoughts on how I might accomplish this? Thank you for your help.
This is the wrong way of doing it; PHP can handle array syntax in a variable name. This makes it much easier to handle. It is also unnecessary to call the server to clone the form. You should name your fields like this:
<form>
<div id="originalCredit">
<input name="title[]" type="text" value="">
<input name="productionCompany[]" type="text" value="">
<input name="year[]" type="text" value="">
<input name="role[]" type="text" value="">
</div>
add another credit
</form>
And then your Javascript can be like this:
$(function() {
$('#addCredit').click(function() {
var newCredit = $('#originalCredit').clone(); // create new set
newCredit.find('input').val(''); // empty input fields
$(this).before(newCredit); // append at the end
return false;
});
});
When the form is finally sent to the server, because the variables are in the format of name[] PHP will recognize they are an array and then you can do this:
<? foreach($_POST['title'] as $k => $v) { ?>
Title: <?=$_POST['title'][$k]?><br>
Company: <?=$_POST['productionCompany'][$k]?><br>
Year: <?=$_POST['year'][$k]?><br>
Role: <?=$_POST['role'][$k]?><br>
<? } ?>
Obviously this is just displaying it as an example, but you can then save/update/whatever with it.

Categories