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 ;)
Related
I´m still learning and trying to write my code as small and effective as possible.
So my regular approach while insert data to mySql from a HTML form is by
fetch input values with Jquery:
var formdata = {};
$('.formdata').each(function(){
formdata[ $(this).attr('name') ] = $(this).val();
});
Send it to PHP with Ajax:
$.ajax({
url: 'file.php',
method: 'post',
data: {formdata: formdata},
success: function(result){
console.log(result)
}
});
Grab POST and put it into a array:
$params_array = array(
':artNr' => $_POST['formdata']['artNr'],
':etc' => $_POST['formdata']['etc'],
);
And finally put it into mySql:
$query = "INSERT INTO table SET artNr = :artNr, etc = :etc";
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($params_array);
}
catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
My question is now:
Is it a bad approach to loop in values from POST to array?
foreach( $_POST['formdata'] as $name => $value ){
$params_array[$name] = $value;
}
Reason for asking is that i don´t know if you are able to send stuff into my JS "formdata[]" from the console and do hacking stuff?
What i mean is that i´m looping whatever exist in the HTML form.. into my database. Without any hardcoded keys in my "params_array"..
Maby there is even more security holes that i´m not aware of?
I know PDO is pretty secure from SQL injections?!
Always consider user input to be (potentially) dangerous. If you expect an integer, make sure it actually is one. Validation on the client side wouldn't ensure security. I can still make a POST request to your endpoint, providing the parameters I want.
I wouldn't loop through the formdata array on the backend. It could break your prepared statement if the number of parameters don't add up the number of placeholders.
So, you were doing just fine:
$data = $_POST['formdata'];
$params = [
':artNr' => intval($data['artNr']),
':etc' => htmlspecialchars($data['etc']),
];
Also, use jQuery's serialize method to encode a set of form elements as a string. It's a more efficient approach to obtain the form values.
var $form = $('#myForm');
$form.submit(function(event) {
var request = $.post('https://endpoint.com', $form.serialize());
request
.done(function(data) {
console.log('Done', data);
})
.fail(function(error) {
console.log('Request fail', error);
});
event.preventDefault();
});
This way you wouldn't need to loop through each .formdata element.
I think what I want to do is really simple but can't get it to work. I'm looping through a table and getting some values from the existing rows, that part works. Then I'm using AJAX to try and make a multidimensional array without duplicates but something isn't working. What I really want to do is delete the duplicate part, reorder the array and array_push new values. Here's what I have:
AJAX:
function getData(){
$("#table .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
$.ajax({
type: "POST",
async: false,
data: {key: key, s: sel, q: q}
});
});
}
PHP:
if(isset($_POST['key'])){
$title = $_POST['key'];
$s = $_POST['s'];
$q = $_POST['q'];
if(!empty($_SESSION['check'])){
foreach ($_SESSION['check'] as $key=>$value){
if(in_array($title, $value)){
unset ($_SESSION['check'][$title]);
$_SESSION['check'] = array_values($_SESSION['check']);
array_push($_SESSION['check'], array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
}else{
$_SESSION['check'] = array(array("key"=>$title, "s"=>$s, "q"=>$q));
}
}
Is there something wrong with the logic? It seems like it should work. The same foreach loop works when trying to delete a table row. It finds the correct KEY and deletes it. Why doesn't it work here?
Here's the answer I got by hours and hours of searching. I avoided using serialize since...well I don't understand how to use it. In JS I'm looping to find values in the table and making an array like this:
function getData(){
var checkArray = new Array();
$("#shopCart .mainTR").each(function(){
var key = $(this).find(".key").text();
var sel = $(this).find(".s").val();
var q = $(this).find(".q").val();
checkArray.push(key);
checkArray.push(sel);
checkArray.push(q);
});
$.ajax({
type: "POST",
data: {ch: checkArray}
});
}
In my PHP is where I found a cool trick. Since I'm controlling the data in the array, I know how many values will be in it. The trick I found is "array_chunk" so for the 3 values I'm doing this:
if(isset($_POST['ch']) && (!empty($_POST['ch']))){
unset($_SESSION['check']);
$_SESSION['check'] = array_chunk($_POST['ch'], 3);
}
So I'm just clearing the session variable and adding the new values. That eliminates all the checking and clearing and all that. I'm sure there are better ways to do this but this method is short and works and that's what I'm looking for. Hope this helps someone!
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.
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"; }
With thanks to Elf Sternberg (I couldn't get your solution working, sorry), I think I am heading in the right direction, but I am having trouble writing the php to the mysql database.
The original post: jQuery AJAX POST to mysql table for dynamic table data- Am I doing this in anything like the right way?
Firstly, the dynamic table form on my webpage has multiple user input data, and I am using this jQuery function and the AJAX call to send to a php file. Am I correctly creating the multidimensional array here? Firebug shows dataString to have all the data I want, but the POST parameters and source just say dataString. Also the alert function shows the data is all there:
EDIT: With thanks to Jancha and Andrew, I have changed the data source for the AJAX post. The database is being written to now, but only BLANK data gets written, for as many entries as were in the table. The firebug console is showing all the data as it should look in the post. I just don't know how to structure the php loop now.
jQuery(function() {
jQuery(".button1").click(function() {
// process form here
var rowCount = jQuery('#dataTable tr').length;
var dataString = [];
dataString.length = rowCount - 2;
for(var i=2; i<rowCount; i++) {
var txtRow1 = jQuery('#txtRow' + (i-1)).val();
var tickerRow1 = jQuery('#tickerRow' + (i-1)).val();
var quantRow1 = jQuery('#quantRow' + (i-1)).val();
var valueRow1 = jQuery('#valueRow' + (i-1)).val();
// previous code: dataString[i-2] = 'txtRow1='+ txtRow1 + '&tickerRow1=' + tickerRow1 + '&quantRow1=' + quantRow1 + '&valueRow1=' + valueRow1;
// new code:
dataString[i-2] = [txtRow1, tickerRow1, quantRow1, valueRow1];
}
//alert (dataString);return false;
jQuery.ajax({
type: "POST",
url: "form_action2.php",
data: { 'data': dataString }
});
return false;
});
});
If this is sending the data okay then I am thinking that the php function needs to look something like this:
Could I have help with the php function please. Thankyou for your time.
$data = $_POST['data'];
foreach ($data as $key => $value){
$txtRow1 = $data['txtRow1'];
$tickerRow1 = $data['tickerRow1'];
$quantRow1 = $data['quantRow1'];
$valueRow1 = $data['valueRow1'];
$sqlinsert = "INSERT INTO stock_port (name, ticker, quantity, value) VALUES ('$txtRow1', '$tickerRow1', '$quantRow1', '$valueRow1')";
mysql_query($sqlinsert, $conn);
}
FINAL EDIT: Ok so this works to enter the data into the database:
$data = $_POST['data'];
foreach ($data as $value){
$txtRow1 = $value[0];
$tickerRow1 = $value[1];
$quantRow1 = $value[2];
$valueRow1 = $value[3];
$sqlinsert = "INSERT INTO stock_port (name, ticker, quantity, value) VALUES ('$txtRow1', '$tickerRow1', '$quantRow1', '$valueRow1')";
mysql_query($sqlinsert, $conn);
}
It seems using data: {'data':dataString} in the AJAX jQuery call means I lost all the variable names of the data sent in the array to POST. Even though this is working, it doesn't feel like the way it should have been done. I have seen others use array structure in their id or names for input on forms, and that seems like it should have been the way to go.
change data: "dataString" to data: dataString or else you are not passing variable but a 'string'.
there is a problem with your foreach statement try this
$data = $_POST['datastring'];
foreach($data as $key => $value){
$txtRow1 = $data['txtRow1'];
}
It is not tested still you try once