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.
Related
I am trying to make a system that gets the value of all textareas into one array and then send it to php for processing, if a page only has textareas with textbox like here:
<div class='form-group'>
<textarea class='col-sm-2' id='" + counter + "'></textarea>
<div class='col-sm-10'>
<input type='text' class='form-control'></input>
</div>
</div>
Everything goes fine. However if the page includes radio boxes:
<div class='form-group'>
<textarea class='col-sm-2' id='" + counter + "'></textarea>
<div class='radio'>
<input type='radio' name='optradio'></input>
<textarea class='col-sm-2' id='" + counter + "'></textarea>
</div>
<div class='radio'>
<input type='radio' name='optradio'></input>
<textarea id='" + counter + "'></textarea>
</div>
</div>
The jquery code does not collect all textareas and does not successfully send it to the php code for processing.
$("#save").click(function () {
for (var i = 0; i < counter; i++) {
form1[i].push($("#" + i).val());
}
$.post("FormResponse.php", {form: form1, formid:$("#formnum").val()}, function (response, status) {
document.write(response);
});
Update:
I changed my jquery code around to get both the type and the textarea values in one place and it still doesn't work. I didn't want to use objects because I want it to be easy for my php code to differentiate which textareas belong to which inputs.
Here is the code revision:
$("#save").click(function () {
var ind = 0;
for (var i = 0; i < inputcounter; i++) {
if (document.getElementById("input#" + i) !== null) {
form1.push($("input#" + i).type());
ind = ind + 1;
}
form1[ind].push($("textarea#" + i).val());
}
document.write(form1);
$.post("FormResponse.php", {form: form1, formid: $("#formnum").val()}, function (response, status) {
document.write(response);
});
});
Haven't tested it but try this.
$("#save").click(function () {
var data = {};
$.each($('textarea'),function(){
var $this = $(this);
data[$this.id] = $this.val();
})
$.post("FormResponse.php",data,function(rep){
console.log(rep);
});
});
Edit
I have no idea what your comment means.
You do realize that you sending a object in your code right?
The PHP code still accesses the data in the same way.
If you mean that you don't know what index the data will be in, then try the code below.
$("#save").click(function () {
var data = {};
$.each($('textarea'),function(){
var $this = $(this);
data[$this.id] = $this.val();
})
$.post("FormResponse.php",{form:data, formid:$("#formnum").val()},function(rep){
console.log(rep);
});
});
I have read several of the posts regarding the PHP date inserting into MySQL as 12/31/1969, but not seeing how to do that with AJAX.
My data/form flow:
- Use a datepicker to select date (Y-m-d)
- Submit form
- Passes through AJAX form in Header
- Is passed to a Processing page to INSERT into db.
*****MY AJAX FORM IN THE HEADER:*****
<script><!--BEGIN: AJAX PROCESS FORM-->
$(document).ready(function() {
$("#subformgeneral").click(function() {
// IF VISIBLE CHECKBOX IS CHECKED THEN = Y ELSE = N
if ($('#usersalevisible').is(":checked"))
{
var user_salevisible = 'Y';
} else {
var user_salevisible = 'N';
}
// END CHECKBOX CONDITIONAL
var user_title = $("#title").val();
var user_startdate = $("#startdate").val();
var user_enddate = $("#enddate").val();
var user_restrictions = $("#salerestrictions").val();
var user_numsellers = $("#numsellers").val();
var user_form = $("#formid").val();
var user_saleid = $("#saleID").val();
$.post("usr-update-sale-process-2.php",{title:user_title,startdate:user_startdate,enddate:user_enddate,salerestrictions:user_restrictions,numsellers:user_numsellers,salevisible:user_salevisible,formid:user_form,saleID:user_saleid},function(data){
$("#result").html(data);
});
});
});
</script>
My DATE INPUT field from my form:
<!-- Start Date -->
<label class="control-label" for="username">Start Date</label>
<div class="controls">
<input type="text" id="datepicker" name="startdate" placeholder="Start Date" class="input-xlarge form-control" value="12/31/1969">
</div>
<input type="hidden" value="formgeneral" id="formid">
<input name="saleID" type="hidden" id="saleID" value="3262" />
<input class="btn btn-primary" type="submit" name="subformgeneral" id="subformgeneral" value="Update General" />
I read an article from here regarding how to do StrToTime conversion, and that worked... on a regular form, but somehow it gets lost when passing through the AJAX form.
I do not have my Processing page code here, where I am at the moment, but it just receives my AJAX POST for STARTDATE, and INSERTS into MySQL.
I assume some sort of conversion has to take place on the Processing page (and I have tried, all I know to do), but not sure how, exactly.
You should handle the success error outcomes.
var user_title = $("#title").val();
var user_startdate = $("#startdate").val();
var user_enddate = $("#enddate").val();
var user_restrictions = $("#salerestrictions").val();
var user_numsellers = $("#numsellers").val();
$.ajax({
url: "usr-update-sale-process-2.php",
type: "POST",
data: {
user_title: user_title,
user_startdate: user_startdate,
user_enddate: user_enddate,
user_restrictions: user_restrictions,
user_numsellers: user_numsellers
},
cache: false,
success: function(data) {
// Success message
},
error: function(data) {
// Fail message
},
});
Things to note: data the key is what the server will look for. Example:
$_POST['user_title'] will be equal to the var user_title = $("#title").val();
Also you can return true and false from the server which will be success and error respectively.
I use a css style for personal information cards.
For example:
<strong>Name: </strong><p>Bla Bla</p>
<h1>Contact Info</h1>
<p>E-mail: blablabla</p>
Now I want to do this with PHP. I've designed my code and template for this. When you fill two textboxes (name, e-mail) and click the button, it gives me the HTML code.
But some people has more than one e-mail. So I've to add second (3rd, 4th) textbox for them. How can I do this without losing the old textbox datas?
Name: filled
E-mail: filled
I need to enter another e-mail so lets click this button for another textbox.
Boom
Name: empty
E-mail: empty
Email2: empty
How to prevent that?
I believe it would be beneficial for everybody if you could post snippet of the code you attempted.
Anyway I have to admit I don't really understand what exactly you're trying to achieve but you may want to check out the variable passing in php PHP variable passing
If I understodd.
To do this has two ways:
1) do in Jquery.
<html>
<head>
<title>jQuery add / remove textbox example</title>
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<style type="text/css">
div{
padding:8px;
}
</style>
</head>
<body>
<h1>jQuery add / remove textbox example</h1>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head><body>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
</body>
</html>
2) in PHP using Session
Store variable in a Session after you submit your form
I have scenario here, input and display page are generated dynamically from php code.
enter code here
<div>Aeroplane</div>
<input id="Item556" type='number' onchange="funCal('Item556', this.value, 'Aeroplane')">
<input class="disp" name="Item556" type="text" disabled>
<div>Plane</div>
<input id="Item557" type='number' onchange="funCal('Item557', this.value, 'Plane')">
<input class="disp" name="Item557" type="text" disabled>
<div>Bikes</div>
<input id="Item558" type='number' onchange="funCal('Item558', this.value, 'Bikes')">
<input class="disp" name="Item558" type="text" disabled >
<div>Cars</div>
<input id="Item559" type='number' onchange="funCal('Item559', this.value, 'Cars')">
<input class="disp" name="Item559" type="text" disabled >
Ajax is :
function funCal(ID, value, name){
var ID1 = ID; var value1 = value; var name1 = name;
$.ajax({
type:"post",
url:"calculate.php",
data: "id="+ID1+"&value="+value1,
cache: false,
dataType: 'json',
success:function(data){
<span>pound;+ data.output +</span>
//added similar to self.next().val(data.output); and tweak around it to work.
updateTotal();
}
});
};
);
function updateTotal() {
var total = 0;
$("input.disp").each(function() {
getPrices = parseFloat($(this).val().replace(/,/g, ''));
total += getPrices;
});
$("span#total").html("£" + total.toFixed(2)).digits();
}
1 . What I want to achieve is when value is entered in input box the corresponding box (with class "disp" box should display the calculated value.)
ex, the input id with Item559 should display after the ajax success value on input box with name"Item559".
Any experts advice will be valuable and much appreciated , because I am very new to ajax and php.---I got the answer for the first as Bhadra suggested below
2 . How do I add-up or sum the total value from the input.disp box? Suggestion or recommendation much appreciated Please!
Thanks in advance
function updateTotal() {
var total = 0;
$(".disp").each(function() {
var getPrices = parseFloat($(this).val().replace(/,/g, '').replace('pound;',''),10);
total += getPrices;
});
$("span#total").html("£" + total.toFixed(2)).digits();
}
I'm following the following tutorial to place a form on my website using PHP, AJAX, and JQUERY that will send the form information to my email:
http://www.spruce.it/noise/simple-ajax-contact-form/
The problem is, when I have the jquery outside the document ready I get no message at all, and when I place it in the document ready i get the error text, but when there is information in the fields nothing happens at all. Please, can someone look and see what might be the problem with my html, jquery, php, or AJAX? I'm about to pull out all of my hair. I'm testing it in Wampserver.
The HTML file is in the root directory with the PHP file. In the root directory there is a folder called "includes" that the Javascript is in. Here is the relevant code for each:
HTML:
<form id="repairform" method="post">
<p id="p1">Name:</p>
<input id="one" type="text" name="name" />
<p id="p2">How would you prefer to be reached?: </p>
<select id="two" name="Contact methods">
<option value="Phone">Email</option>
<option value="Email">Phone</option>
</select>
<p id="p3">What kind of computer are you having trouble with?</p>
<p id="p3-2">Give as much or as little info. as you'd like.</p>
<p id="p3-3">(Laptop PC, desktop Macintosh, etc)</p>
<textarea id="four" name="pc type" rows="3" cols="30"></textarea>
<p id="p4">What problems are you having with your computer/ what needs to be fixed?</p>
<textarea id="five" name="problem" rows="5" cols="30"></textarea>
<input id="three" type="submit" value="Submit Request" />
<p id="p5">What is your Email?</p>
<input id="six" type="text" name="Email/Phone" />
<p id="p7">What is your Phone Number?</p>
<input id="eight" type="text" name="Email/Phone2" />
<p id="p6">What time of day would you prefer to be reached?</p>
<input id="seven" type="text" name="Preferred Contact Time" />
</form>
JQuery:
$(document).ready(function () {
$("#repairform").submit(function (e) {
e.preventDefault();
if (!$("#six").val()) {
$("#six").val("shanew#ufl.edu");
}
var name = $("#one").val();
var email = $("#six").val();
var text = $("#five").val();
var reachpreference = $("#two").val();
var computertype = $("#four").val();
var phonenumber = $("#eight").val();
var timeofday = $("#seven").val();
var dataString = 'name=' + name + '&email=' + email + '&text=' + text
+ '&reachpreference=' + reachpreference + '&computertype=' + computertype
+ '&phonenumber=' + phonenumber + '&timeofday=' + timeofday;
function isValidEmail(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (text.length > 2) && (name.length > 1)) {
$.ajax({
type: "POST",
url: "../functions.php",
data: dataString,
success: function () {
alert("Thank you! Your message has been delivered. I will be back with you shortly");
}
});
} else {
alert("Some of the form information was not filled out correctly. Ensure all of the correct fields are filled out.");
}
return false;
});
PHP:
<?php
// Email Submit
if (isset($_POST['email']) && isset($_POST['name']) && isset($_POST['text'])){
//send email
mail("shanew#ufl.edu", "Contact Form: ".$_POST['name'],
$_POST['text'], $_POST['reachpreference'], $_POST['computertype']
$_POST['phonenumber'], $_POST['timeofday'], "From:" . $_POST['email']);
}
?>
Use
data: $('#repairform').serializeArray()
instead of the datastring object you're creating.
The datastring will be treated as a String, and you'll never be able to access it using $_POST['text'] and all. You may try using using $_GET instead. The datastring will be accessible that way only.
I think you miss some of closing branch });
And I think you should use name attribute for variable name that will be used in php..
<form id="theForm">
<input type="text" name="email" />
</form>
and in javascript you can use serialize so less line and easier to read.
$.ajax({
type:'POST'
url:'../functions.php'
data:$('#theForm').serialize();
})
and in php
echo $_POST['email']