Adding multiple rows to database from dynamic field event - php

I have a dynamic event in JS in my form which adds another block of fields so my users can add another address:
<script type="text/javascript">
$(document).ready(function() {
$('#btnAdd').click(function() {
var $address = $('#address');
var num = $('.clonedAddress').length;
var newNum = new Number(num + 1);
var newElem = $address.clone().attr('id',
'address' + newNum).addClass('clonedAddress');
//set all div id's and the input id's
newElem.children('div').each (function (i) {
this.id = 'input' + (newNum*11 + i);
});
newElem.find('input').each (function () {
this.id = this.id + newNum;
this.name = this.name + newNum;
});
if (num > 0) {
$('.clonedAddress:last').after(newElem);
} else {
$address.after(newElem);
}
$('#btnDel').removeAttr('disabled');
if (newNum == 3) $('#btnAdd').attr('disabled', 'disabled');
});
$('#btnDel').click(function() {
$('.clonedAddress:last').remove();
$('#btnAdd').removeAttr('disabled');
if ($('.clonedAddress').length == 0) {
$('#btnDel').attr('disabled', 'disabled');
}
});
$('#btnDel').attr('disabled', 'disabled');
});
</script>
However, when I put my form action the page just refreshes when I click my 'add another address' button:
<form action="address.php" method="post" name="regForm" id="regForm" >
These are my fields:
if(empty($err)) {
for($i = 0; $i < 10; $i++)
{
$Street = $_POST['Street'][$i];
$Line2 = $_POST['Line2'][$i];
$Line3 = $_POST['Line3'][$i];
$Town = $_POST['Town'][$i];
$Postcode = $_POST['Postcode'][$i];
$Country = $_POST['Country'][$i];
$Tele = $_POST['Tele'][$i];
$Fax = $_POST['Fax'][$i];
$Type = $_POST['Type'][$i];
$Mobile = $_POST['Mobile'][$i];
$sql_insert = "INSERT into `address`
(`Street`,`Line2`,`Line3`,`Town`, `Postcode` ,`Country`,`Tele`,`Fax`,`Type`
,`Mobile` )
VALUES
('$Street','$Line2','$Line3','$Town','$Postcode','$Country',
'$Tele','$Fax','$Type', '$Mobile'
)";
mysql_query($sql_insert,$link) or die("Insertion Failed:" . mysql_error());
}
I want all addresses to go to mysql database.
I hope this is clear

Define buttons as followed: <input type="button" value="ButtonLabel" />.
My short test resulted in my <button> getting treated as submit type input by firefox. This means <button>FooBar</button> and <input type="submit" value="FooBar" /> are equivalent.
You might also want to simplify your javascript code. You can use the array notation for input names:
<input type="text" name="street[]" />
<input type="text" name="zip[]" />
<input type="text" name="street[]" />
<input type="text" name="zip[]" />
will result in $_POST["street"][0] and $_POST["street"][1] beeing filled with the user's input. This is what you want judging from your php code, anyway.
You don't need ids for all your input tags. Just keep one full set of inputs for one address and append this to your form. Maybe something like:
$('#address').append(
'<div>' +
'<input type="text" name="street[]" />' +
'<input type="text" name="zip[]" />' +
'</div>'
);
Or just have a full set hidden on your page and clone it, then append. I'm sure our jQuery pros will know a better solution.
And finally: Please sanatize your input with mysql_real_escape_string
$Street = mysql_real_escape_string($_POST['Street'][$i]);
// and so on for the other values.

Related

posting array of text fields using jquery and ajax

i dont want to use serialize() function please help me with this. I am a beginner
html
<input type='button' value='Add Tier Flavor' id='Add'>
<input type='button' value='Remove Tier Flavor' id='Remove'>
<div id='batch'>
<div id="BatchDiv1">
<h4>Batch #1 :</h4>
<label>Flavor<input class="textbox" type='text' id="fl1" name="fl[]" value=""/></label></br>
<label>Filling<input class="textbox" type='text' id="fi1" name="fi[]" value="" /></label></br>
<label>Frosting<input class="textbox" type='text' id="fr1" name="fr[]" value=""/></label></br>
</div>
</div>
<br>
</div>
this is a dynamically added fields using javascript the code is:
javascript
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#Add").click(function () {
if(counter>5){
alert("Only 5 Tiers allow");
return false;
}
var newBatchBoxDiv = $(document.createElement('div')).attr("id", 'BatchDiv' + counter);
newBatchBoxDiv.html('<h4>Batch #'+ counter + ' : </h4>' +
'<label> Flavor<input type="text" name="fl[]" id="fl' + counter + '" value=""></label><br>'+
'<label> Filling<input type="text" name="fi[]" id="fi' + counter + '" value=""></label><br>'+
'<label> Frosting<input type="text" name="fr[]" id="fr' + counter + '" value=""></label><br>' );
newBatchBoxDiv.appendTo("#batch");
counter++;
});
$("#Remove").click(function () {
if(counter==1){
alert("No more tier to remove");
return false;
}
counter--;
$("#BatchDiv" + counter).remove();
});
});
</script>
i am trying to post the values in an array to post it onto next .php page
i am using this
var user_cupfl = $('input[name^="fl"]').serialize();
var user_cupfi = $('input[name^="fi"]').serialize();
var user_cupfr = $('input[name^="fr"]').serialize();
serialize is not passing the values. :(
on second page i am trying to mail it using
$message .= "<tr><td><strong>Cake Flavors(according to batches):</strong> </td><td><pre>" .implode("\n", $user_cupfl). "</pre></td></tr>";
$message .= "<tr><td><strong>Filling type (Inside the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfi). "</pre></td></tr>";
$message .= "<tr><td><strong>Frosting type (top of the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfr). "</pre></td></tr>";
i m posting array like this
$user_cupfl=filter_var($_POST["userCupfl"], FILTER_SANITIZE_STRING);
$user_cupfi=filter_var($_POST["userCupfi"], FILTER_SANITIZE_STRING);
$user_cupfr=filter_var($_POST["userCupfr"], FILTER_SANITIZE_STRING);
your replies will be highly appreciated
Just because you name a variable user_* doesn't mean that is what the name of the field is in the serialized POST data. You would still be looking for $_POST['fl'], $_POST['fi'] etc.
I don't understand why you think you need to serialize sets of input groups individually. You should just serialize the whole form at once.
I also see no reason why you need to have all this logic around unique id's with the counter and what not. If you are not using id's at all, just drop them altogether.
You might also consider simply using clone techniques to generate your dynamically added fields. You could greatly simplify all that javascript code by doing these things.
A more reasonable implementation may look like this.
HTML (cleaning up your code - consistent use of double quotes around properties, better strategy for class and id usage, etc.)
<div id="batch">
<div class="batchDiv">
<h4 class="batchLabel">Batch #1 :</h4>
<label>Flavor</label>
<input class="textbox" type="text" name="fl[]" value=""/>
</br>
<label>Filling</label>
<input class="textbox" type="text" name="fi[]" value="" />
</br>
<label>Frosting</label>
<input class="textbox" type="text" name="fr[]" value=""/>
</br>
</div>
</div>
Javascript:
$(document).ready(function() {
$('#Add').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
if (count < 5) {
// get last batch div
var $newBatch = $existingBatches.last().clone();
// reset input values to empty string
$newBatch.find('input').val('');
// change batch label
count++;
$newBatch.find('.batchLabel').html('Batch #' + count + ' :');
// append to document
$newBatch.appendTo('#batch');
} else {
// alert or whatever
}
});
$('#Remove').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
// delete last batch item if more than 1 exists
if(count > 1) {
$existingBatches.last().remove();
} else {
// alert or whatever
}
});
});
Now you haven't shown your AJAX code, but all you would need to do is something like:
var url = '/some/url';
var postData = $('[some form selector]').serialize();
var dataType = '...'; //whatever dataType you are expecting back
$.post(url, postData, function(){
// success handler
}, dataType));
Your data when then be available in PHP script at $_POST['fl'], etc.

Get values inserted for field dynamically

I would like to insert up to 10 fields dynamically 10 into my form :
<form action="" method="post">
...
<div id="dynamicInput">Entry 1
<br>
<input type="text" name="myInputs[]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">
...
<input type="submit" class="btn btn-primary" />
</form>
JS code :
var counter = 1;
var limit = 10;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
After clicking submit in form ( with post method ) I hope to get values inserted in this field in my php page?
For example I inserted 3 values dynamically using the JS code above, so I hope to get in my php page an array like this :
Array(
[0] => value1, [1] => value2, [2] => value3
)
Your initial form :
<div id="dynamicInput">Entry 1
<br><input type="text" name="myInputs[]">
</div>
and your javascript :
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
Give this dynamically generate field the name name='myInputs[]'> myInputs
Therefore when you receive the forms data back into your PHP code you will receive this in the $_POST array:
$_POST['myInputs'][0] = data in the first field
$_POST['myInputs'][1] = data in the second field
$_POST['myInputs'][2] = data in the third field
...
$_POST['myInputs'][9] = data in the tenth field
I don't know how to do with javascript but by using jquery you can do achieve it easily
please add script jquery.js in your site
HTML
<div id="dynamicInput">Entry 1
<input type="text" name="myInputs[]" class="myInputs" />
<input type="button" class="add_input" value="Add another text input" />
</div>
jQuery
$(document).ready(function(){
var limit = 10;
$(".add_input").on('click', function(){
if( $(".myInputs").length == limit ){
alert("You have reached the limit of adding " + limit + " inputs");
return false;
}
$(".myInputs:last").after("<br>Entry "+ ( $(".myInputs").length + 1 )+" <input type='text' name='myInputs[]' class='myInputs' />");
});
});
you can also check example at JSFiddle

User's facebook details not being received into hidden fields

I'm using the facebook javascript sdk to get a logged in user's public data. What I want to do is bind the values to hidden field in the form and when submitted, get the values in a php file which will insert into MySQL database. But when I submit the form, there are no values. Why is that? If I need to provide more info, please let me know. When I login, I can see my facebook name and profile pic on the web app.
//Hidden fields within form
<input type="hidden" name="hdnFacebookId" id="hdnFacebookId" value="">
<input type="hidden" name="hdnUsername" id="hdnUsername" value="">
<input type="hidden" name="hdnFirstName" id="hdnFirstName" value="">
<input type="hidden" name="hdnLastName" id="hdnLastName" value="">
<input type="hidden" name="hdnFacebookImg" id="hdnFacebookImg" value="">
<input type="hidden" name="hdnFacebookUrl" id="hdnFacebookUrl" value="">
<br/>
<input type="submit" id="submit" onclick="setValues()" data-theme="b" value="Submit" class="ui-btn-hidden" aria-disabled="false">
<script>
function updateUserInfo(response) {
FB.api('/me', function(response) {
document.getElementById('myFacebookImg').src = "https://graph.facebook.com/" + response.id + "/picture";
document.getElementById('myFacebookName').innerHTML = response.name;
function setValues(){
document.postAJourneyForm.hdnFacebookId.value = response.id;
document.postAJourneyForm.hdnUsername.value = response.username;
document.postAJourneyForm.hdnFirstName.value = response.first_name;
document.postAJourneyForm.hdnLastName.value = response.last_name;
document.postAJourneyForm.hdnFacebookImg.value = "https://graph.facebook.com/" + response.id + "/picture";
document.postAJourneyForm.hdnFacebookUrl.value = "http://graph.facebook.com/" + response.username;
//document.forms["postAJourneyForm"].submit();
}
});
}
//php file that gets the data to post to database
//I check in the code if it is empty before I can execute the query
//but it is always empty
//get the facebook data
$hdnFacebookId = $_POST['hdnFacebookId'];
$hdnUsername = $_POST['hdnUsername'];
$hdnFirstName = $_POST['hdnFirstName'];
$hdnLastName = $_POST['hdnLastName'];
$hdnFacebookImg = $_POST['hdnFacebookImg'];
$hdnFacebookUrl = $_POST['hdnFacebookUrl'];
//Updated with JSON
<script>
function updateUserInfo(response) {
FB.api('/me', function(response) {
document.getElementById('myFacebookImg').src = "https://graph.facebook.com/" + response.id + "/picture";
document.getElementById('myFacebookName').innerHTML = response.name;
document.getElementById('facebookUrl').href = "https://www.facebook.com/" + response.username;
var JSONObject = {
"facebookId":response.id,
"facebookName":response.username,
"facebookFirstName":response.first_name,
"facebookLastName":response.last_name
};
document.getElementById('hdnFacebookId').innerHTML = JSONObject.facebookId;
document.getElementById('hdnUsername').innerHTML = JSONObject.facebookName;
document.getElementById('hdnFirstName').innerHTML = JSONObject.facebookFirstName;
document.getElementById('hdnLastName').innerHTML = JSONObject.facebookLastName;
document.getElementById('hdnFacebookImg').innerHTML = JSONObject.facebookImage;
document.getElementById('hdnFacebookUrl').innerHTML = JSONObject.facebookUrl;
});
}
</script>
To set values.
$('#hdnFacebookId').val(response.id);
$('#hdnUsername').val(response.username);
$('#hdnFirstName').val(response.first_name);
$('#hdnLastName').val(response.last_name);
$('#hdnFacebookImg').val('https://graph.facebook.com/' + response.id + '/picture');
$('#hdnFacebookUrl').val('http://graph.facebook.com/' + response.username);

How to detect if two input elements like text fields are typed in. (php/javascript)

If two input elements in a form - for example - text fields, lets say username and password, get text input with length > 0, how would you create an event to change a submit button color the moment the user has typed in both fields?
document.getElementById('submit').onclick = function() {
var inputs = document.getElementsByTagName('input'),
empty = 0;
for (var i = 0, len = inputs.length - 1; i < len; i++) {
empty += !inputs[i].value;
}
if (empty == 0) {
//write code for changing the button color
}
};
I like the answer above, and here is a jquery answer if you like the looks better!
$(document).ready(function() {
$("#username").change(checkFunction());
$("#password").change(checkFunction());
}
function checkFunction() {
var user = $("#username").val();
var pass = $("#password").val();
if (user && pass) {
$("#buttonid").css("background-color:#HEXCODE");
}
}
Make a javascript function that checks if both inputs have a value greater than zero and if they do it changes the color of the submit button when called.
Use the onChange attribute in the input tag and place the name of the javascript function in the attribute.
You can also set the attribute by doing
Object.onChange = functionToCall();
onChange fires the function it's set to whenever the input value changes.
If you have Jquery in your project, you can try something like this:
Assuming your inputs have ids:
<input id="username" name="username"/>
<input id="password" name="password"/>
<input type="submit" value="Submit" id="submit" />
You can bind to the keyup event on either input element to change the color of the button:
$('#username, #password').keyup(function(){
if ($.trim($('#username').val()) != '' && $.trim($('#password').val()) != '') {
$('#submit').css('background-color', 'red');
}
});
Here is the running fiddle:
http://jsfiddle.net/NS5z6/
HTML:
<input type=text id=username />
<input type=password id=password />
<input type=submit id=submit />
CSS:
#submit{ background-color: red; }
JS:
$('input[id="username"], input[id="password"]').change(function(){
if ($(this).val()!="")
{
$("input[id='submit']").css("background-color","green");
}else{
$("input[id='submit']").css("background-color","red");
}
});
You can use following logic
<input type = "text" name = "username" class = "text">
<input type = "password" name = "password" class = "text">
<input type = "button" class = "button">
<script>
$(".text").live("keyup", function(){
var filled = true;
$(".text").each(function(i, v){
if($(this).val() == ''){
filled = false
}
});
if(filled){
$(".button").css("background-color:#black");
}
});
</script>

Getting NaN from form PHP form using JS

I'm getting a NaN value if i try to do any math with the two vars i pull form the form. It also gives me NaN if i try it parseInt it. IDK if it helps but the values are pulled from the URL using PHP; example: .../serch.php?animal=all&color=any&sunSd=all&lifeSpn=all&limiterF=5&limiterT=20
limiterF and limiterT are the vars I'm working with.
html:
<form id='serchForm' action="serch.php" method="GET">
...
<fieldset>
From: <input type='text' id = 'limiterFid' name='limiterF' value=<?php if (!empty($_GET['limiterF'])) {echo $limiterF;} else {echo 0;} ?> size="2" /><br />
To: <input type='text' id = 'limiterTid' name='limiterT' value=<?php if (!empty($_GET['limiterT'])) {echo $limiterT;} else {echo 20;} ?> size="2" />
</fieldset>
<input type="submit" id="submitNew" />
<input type="submit" id="nextSerch" />
JS:
$(document).ready(function() {
$("#serchForm input").click(function(e) {
if(e.target.id == 'submitNew') {
e.preventDefault();
$('#limiterFid').attr("value", 0);
$('#limiterTid').attr("value", 20);
$("#serchForm").submit();
} else if (e.target.id == 'nextSerch') {
e.preventDefault();
var limiterF = $('#limiterFid').value,
limiterT = $('#limiterTid').value;
limiterT = limiterF + limiterT;
limiterF = parseInt(limiterF, 5);
$('#limiterFid').attr("value", limiterF);
$('#limiterTid').attr("value", limiterT);
$("#serchForm").submit();
} else {
return;
}
});
});
This is what it will return when you click nextSerch:
.../serch.php?animal=all&color=any&sunSd=all&lifeSpn=all&limiterF=NaN&limiterT=NaN
value is a property of the DOM element not the jQuery object. You can use either val() or value on the original DOM element.
$('element').val()
// OR
$('element')[0].value
Also to set values you typically don't use attr, you use val.
$('element').val('newValue')
Use the .val() method, as value will returned undefined as it is attempting to call the 'value' property of a jQuery object:
$(document).ready(function() {
$("#serchForm input").click(function(e) {
if(e.target.id == 'submitNew') {
e.preventDefault();
$('#limiterFid').val(0);
$('#limiterTid').val(20);
$("#serchForm").submit();
} else if (e.target.id == 'nextSerch') {
e.preventDefault();
var limiterF = $('#limiterFid').val(),
limiterT = $('#limiterTid').val();
limiterT = limiterF + limiterT;
limiterF = parseInt(limiterF, 5);
$('#limiterFid').val(limiterF);
$('#limiterTid').val(limiterT);
$("#serchForm").submit();
} else {
return;
}
});
});

Categories