I am experiencing some issues with a form I am making. I have the code to post a form to my PHP script that is meant to handle the data with this code:
<script type="text/javascript">
$(document).ready(function()
{
$("#submit").click(function()
{
var q1 = $("#q1").val();
var q2 = $("#q2").val();
var answers = "page=1&q1="+q1+"&q2="+q2;
$.ajax({
type:'POST',
url:'add.php',
data:answers,
success:function(response)
{
$("#answers").html(response);
}
});
});
});
</script>
This form is then received in my PHP script like this:
$page = $_POST['page'];
$q1 = $_POST['q1'];
$q2 = $_POST['q2'];
echo "Page: " .$page . "<br/>Question 1: " . $q1 . "<br/>Question 2: " . $q2;
The issue of it all is that I want this form to be able to handle X amount of inputs and also handle input I do not know the name of. Like I can get 5 textboxes, or 2 textboxes + a string of radiobuttons and so on. Is there a way to collect ALL $_POST data and then explode it or something similar so I can get it ready for the database? I wish to recover all question id's(values) and all answer values(could be a string or an int representing a radiobutton id).
You can iterate through all POST and GET request parameters by simply treating POST and GET as an array. For an example:
print_r($_POST);
Alternatively:
foreach ($_POST as $key => $value) {
echo $key." = ".$value."<br>";
}
If you want to handle a variating amount of input fields, you can define an incrementing naming convention and use loops to gather them all to an array.
with print_r($_POST); you can look at all values.
or something like this:
foreach ( $_POST AS $key => $value) {
echo $key." => ".$value."<br>";
}
First: Let jQuery build your data string, your current method requires you to know each field in advance and can't handle data with special characters in it.
url:'add.php',
data: $('#myForm').serialize(),
success:function(response)
Second: Name your fields using the PHP multiple fields with the same name convention:
<input type="radio" name="answer[1]" value="foo">
<input type="radio" name="answer[1]" value="bar">
You can then access them as:
$_POST['answer'][]
It is an array, so you can get the '1' and the 'foo' or the 'bar' in a loop.
Related
I'm working on a project where I have retrieved the name and values from selected checkboxes using jquery/ajax. I have set the names and values of the checkboxes using php on the main page. I would like to extract the names using $_POST in a seperate php script so that I can use these names to delete projects out of MySQL.
$("#deleteproject").click(function () {
var names = [];
$('#projectcheckbox input:checked').each(function() {
//all checkbox names are put in array
names.push({name: $(this).attr('name'), value: $(this).val()});
});
alert($.param(names));
return false;
});
The above alert($.param) returns the selected checkbox in a val1.name and val1.value format.
//run delete_project.php to erase projects from database
$.ajax({
type: "post",
url:"delete_project.php",
data: names,
cache: false,
success:function() {
alert(names + ' deleted')
}
});
I have searched for an answer the last couples days and I would appreciate some help figuring this out.
I would prefer using html part in this way first, cos it's more flexible and easy in your case;
<input type="checkbox" name="projectcheckbox[]" value="foo_project" />
<input type="checkbox" name="projectcheckbox[]" value="bar_project" />
...
Or printing out the db results at first;
foreach ($projects as $project) {
print '<input type="checkbox" name="projectcheckbox[]" value="'.$project.'" />';
}
Then calling jQuery.serialize will give you a data stuff like;
projectcheckbox[]=foo_project&projectcheckbox[]=bar_project ...
PHP part (after post);
foreach ((array) $_POST['projectcheckbox'] as $pro) {
// do something with $pro = foo_project or bar_project etc...
// THIS PART FOR SECURITY GUYS :)
// BUT! DO NOT FORGET TO SECURE YOUR DATA ($pro) HERE!!!!!
}
Is it possible to get some other attribute's value than attribute named value with $_POST
example: <option value="FusRo" name="Dah"></option>
Normally when i use $_POST['Dah'] The php grabs FusRo (the value).
But I want to grab another attribute's value than attribute named value. I hope you understand.
If I cant use $_POST to grab some other value, is it some other comand i can use?
Another example:
If i use
<option value="FusRo" name="Dah"></option>
Can I get the "Dah" with $_POST instead of "Fusro" ?
You can put your other value in a hidden field:
<input type="hidden" name="DahHidden" value="somethingelse" />
Then get it from $_POST with:
$_POST['DahHidden']
If this value has to dynamically change based on what's in the <select>, then you'll need JavaScript.
If you want to grab the keys from $_POST (i.e. the name attributes from your form fields), you can iterate over $_POST like this:
foreach( $_POST as $key => $value)
echo $key . ' => ' . $value; // Will print Dah => value (eventually)
Note that iterating over $_POST will likely produce more output than just that one form element (unless 'Dah' is the only thing you submitted in your form.
The only way is to use JavaScript to modify the posted data, or even simpler use jQuery
then it would look like something like this :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.js"></script>
</head>
<body>
<form name="skyrim" id="skyrim">
<input type="text" value="FusRo" name="Dah" data-name="dhovakin" data-race="kajit" />
<form>
<script>
$('#skyrim').submit(function( e ){
data = {};
url = 'http://sandbox.local/testpost.php';
e.preventDefault();
$('input, textarea', this).each(function(){
var pcs = $( this ).data();
var ename = $( this ).attr('name');
if(undefined == data[ ename ] ){
data[ ename ] = {};
data[ ename ]['_'] = $(this).val();
}
$.each(pcs, function(k, v){
data[ ename ][k] = v;
});
});
$.ajax({
url : url
,data : data
,type : "POST"
}).done(function(){
});
});
</script>
</body>
</html>
The above code will add all the attributes starting with data- to the post .
the result of the above is :
Dah[_] FusRo // default value
Dah[name] dhovakin // data-name
Dah[race] kajit // data-race
$_POST only gives you the names of the field, and their corresponding value, nothing more.
No, you cannot post anything else then the "value" of an inputfield.
You could hack your way into it by using javascript. Something like
document.getElementById('FORM').onsubmit = function() {
document.getElementById('FIELD').value = document.getElementById('FIELD').customAttribute
}
However, if javascript is disabled, your form will submit the wrong values. Not a really solid solution.
Sounds to me more like you will have to redefine your values, I can't really imagine why you would like to alter this behavior.
I am using jQuery to create as many input textboxes as the user needs like so:
<script type="text/javascript">
$(document).ready(function() {
$('#names').on({
blur: function() {
var name = $("<p><input class='input' type='text' /></p>")
var nullFields = 0;
$(this).closest('div#names').find('input.input').each(function(){
if($(this).val() == ""){
nullFields++;
}
});
console.log(nullFields);
if(nullFields <= 1){
$('#names').append(name.fadeIn(500));
}
}
}, 'input');
});
</script>
Inserting a static textbox into a database isn't a problem using $_POST['blah'] andmysql_query("INSERT INTO ..."), but how do I insert the values of the dynamically created textboxes? I know I'll have to give the textboxes different names as they're created and I presume the MySQL query will be by way of some sort of loop.
EDIT
The website in question is here, specifically at step 4. As mentioned above, step 3 was quite straightforward.
This is an example to get you started, not the complete solution.
You create an array for the names then have the php insert each array item
var currentArrayNum = 1;
$('#someClickable').click(function(){
$('#td').append('<input name="arrayName['+currentArrayNum+']" value="" />');
currentArrayNum += 1;
});
php:
foreach ($_POST as $key){
if (is_array($key)){
foreach ($key as $key2 => $value){
//$key2 will equal arrayName[currentArrayNum]
//$value will equal the user input for the text field
do some stuff
}
You can create arrays out of name, simply try this:
<input type="text" name="post_input[input_1]" value="">
<input type="text" name="post_input[input_2]" value="">
After Submit, you would get an Array out of $_POST["post_input"] with the keys input_1 and input_2 and their assigned values. Then you just loop them as a normal array, for example
$aTextFields = $_POST["post_input"];
foreach( $aTextFields as $sValue ) {
...
}
I'm sending the following info to a php file. data contains 'one' and 'two'. 'One' contains the serialized form and two contains similar custom info. How can i read those post values with php. I want to be able to differentiated between the value contained in one and value contains into two.
$('form').submit(function() {
x = $(this).serialize(),
test = 'testing=whatever&something=else';
$.ajax({
type: 'POST',
data: {'one':x, 'two':test}
...
})
})
How can i read the values in php in such a way where i can do
$one = $_POST['one'];
foreach($one as $key=>$value){ $message.= $key.": ".$value."\r\n"; }
I'm not sure what you want to do with the serialised version of the form (x) but you can get access to both of the variables in the receiving PHP script using $_POST as per usual and then probably use parse_str (http://au.php.net/manual/en/function.parse-str.php) to break 'test' out into the various parameters, but I question why you are taking this route instead of breaking the parameters up and passing them as individual arguments in the data argument:
data: {'testing' : whatever, 'something' : else}
you need to cancel the default behavior of submit
$('form').submit(function(e) {
e.preventDefault();
x = $(this).serialize();
test = 'testing=whatever&something=else';
$.ajax({
type: 'POST',
data: {one:x, two:test}
...
})
})
on the php side
$one = $_POST['one'];
$two = $_POST['two'];
update:
im not that well versed in php but i think the following should work
$one = $_POST['one'];
$two = $_POST['two'];
$cols = explode("&", $one);
foreach($cols as $col) {
$key_values = explode("=", $col);
$key = urldecode($key_values[0]);
$values = urldecode(key_values[1]);
}
echo $key, $values;
If your form contains checkboxes or radioboxes (inputs with same names) use $(this).serializeArray() instead of $(this).serialize() to distinguish between them
You need to first convert your form data into JSON! not the query string which serialize does, for that see This, JSON can give you ability to have nested keys.
Then you can put seperate data in different keys in JSON like:
var myData =
{
'one': $('form').serializeObject(),
'two': 'testing=whatever&something=else',
};
$('form').submit(function() {
$.ajax({
type: 'POST',
data: myData,
...
});
});
And the on PHP side you can easily get it using the way you want to:
$one = $_POST['one']
foreach($one as $key=>$value) { $message.= $key.": ".$value."\r\n"; }
I'm using this jquery to serialize my form and pass it to a PHP script called write.php;
$("form").submit(function(){
var_form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "write.php",
data: var_form_data,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
Normally, lets say I had a form with the fields Address F_name and S_name, I'd do something like this to get the values into PHP vars;
$Address = $_POST["Address"];
$F_name = $_POST["F_name"];
$S_name = $_POST["S_name"];
I'd then go onto persist these to the DB
However, this particular form is liable to change on a regular basis. Therefore, I'd like to be able to get at all of the data that was passed through the ajax request in the form of a string that I can explode or an array.
I can then loop through the items in the array and persist them to the DB one by one (i think!).
I hope this makes sense, if I have missed anything or you would like me to explain further please let me know.
As always - all help is very much appreciated.
foreach($_POST as $form_key => $form_val){ }
you will not want to query each time inside this loop, however. Instead append each time to a string that you will query with afterwards.
var $results = '';
foreach ($_POST as $key => $value) {
echo $results .= "$key = $value;";
}
// $results holds the posted values
foreach($_POST as $k => $v)
but this is pretty risky as malicious user could manually add post values to the request and do crappy stuff with your code. Make a list of allowed value maybe ;)