I have already submitted forms using ajax,
i have a query with my dynamic text fields I need to pass their value through ajax. i have done this trough PHP, but I need to use ajax function to do that.
Below is my PHP code how i did it.
<form>
<h3>Day 1 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<h3>Day 2 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<h3>Day 3 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<h3>Day 4 Details</h3>
<input type="text" name="b_destinations[]">
<input type="number" name="b_nights[]">
<!------- button for adding more textfields for day deatils--->
<button name="" onclick="somefunctiontoaddmoretextfield">
</form>
this is my php code. i use foreach for my dynamic textfield as i have a button to add as many Day details i need.
but my conern is how can i pass this multiple textfield values in the ajax.
i have tried many thing and also search on stack but never found any answer.please help me with this how i can post this data using ajax.
<?php
foreach($_POST['b_destinations'] as $p_destination) {
$pdata[] = preg_replace("/[^A-Za-z0-9?! ]/","",$p_destination);
}
$pData[] = $pdata;
$b_destinations = json_encode($pData);
foreach($_POST['b_nights'] as $p_nights) {
$pdata1[] = filter_var($p_nights,FILTER_SANITIZE_NUMBER_INT);
}
$pData1[] = $pdata1;
$b_nights = json_encode($pData1);
?>
this is my ajax code. what needs to done here
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'destinations' : $('input[name=b_destinations]').val(),
'nights' : $('input[name=b_nights]').val()
};
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
Related
I'm getting my multiple forms using a while loop (fetch data in the database).
<form id="form" class="form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test1">
<input type="text" class="form-control" name="car_type">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>
<form id="form" class="form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test2">
<input type="text" class="form-control" name="car_type" value="test2">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>
Here's my ajax (It only works in the 1st form but the rest not working):
$(document).ready(function(){
$(".form").submit(function(e) {
e.preventDefault();
$("#buttona").html('...');
$("#buttona").attr("disabled", "disabled");
sendInfo();
});
});
Function for ajax:
function sendInfo() {
$.ajax({
type: 'POST',
url: '../process.php',
data: $(".form").serialize(),
success: function(data){
if(data == 'Success') {
$('#text_errora').html('added');
}else {
$('#text_errora').html('not aadded');
}
}
})
return false;
}
How can I set or how ajax will recognize the button I click/submit to process the form?
You don't close your <form> tag.
You use the same id twice.
You select anything with class form, not ID form.
Actually, I am amazed it works even one time.
Try this (no need to touch the JavaScript), your form should submit, but the button changing might not work (you use identical IDs there too; tip: an id has to be unique within the entire HTML DOM).
<form class="form form-horizontal" method="post" >
<input type="text" class="form-control" name="name" value="test1">
<input type="text" class="form-control" name="car_type">
<button type="submit" class="buttona" id="buttona">Send</button>
</form>
Using "this" keyword inside submit handler, you will receive a reference to the form to which the clicked button belongs.
$(document).ready(function(){
$(".form").submit(function(e) {
e.preventDefault();
var form_to_submit = this;
$("#buttona").html('...');
$("#buttona").attr("disabled", "disabled");
sendInfo(form_to_submit);
});
});
function sendInfo(form_to_submit) {
$.ajax({
type: 'POST',
url: '../process.php',
data: $(form_to_submit).serialize(),
success: function(data){
if(data == 'Success') {
$('#text_errora').html('added');
}else {
$('#text_errora').html('not aadded');
}
}
})
return false;
}
Is it possible to submit two forms using a single submit button?
like if a user clicks submit on a form, that form runs test.php and form.php with the variables still intact?
If not then is it possible when the user clicks submit on a form it runs only test.php then test.php runs form.php with the variables still intact.
I don't think this is possible on a normal form submission, but you can try to utilize an AJAX request on both forms on demand. (This is just an example, not tested, just a guide or an idea.).
<!-- forms -->
<fieldset><legend>Form #1</legend>
<form id="form_1" action="test.php">
<label>Username: <input type="text" name="username" /></label>
<label>Password: <input type="text" name="password" /></label>
</form>
</fieldset>
<br/>
<fieldset><legend>Form #2</legend>
<form id="form_2" action="form.php">
<label>Firstname: <input type="text" name="fname" /></label>
<label>Lastname: <input type="text" name="lname" /></label>
</form>
</fieldset>
<button id="submit" type="button">Submit</button>
<!-- the forms is just an example -->
<!-- it would be weird to separate such fields in to different forms -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit').on('click', function(){
$.ajax({
url: $('#form_1').attr('action'),
data: $('#form_1').serialize(),
type: 'POST', // or whatever get
dataType: 'JSON', // or whatever xml script html
success: function(response) {
}
});
$.ajax({
url: $('#form_2').attr('action'),
data: $('#form_2').serialize(),
type: 'POST', // or whatever get
dataType: 'JSON', // or whatever xml script html
success: function(response) {
}
});
});
});
</script>
The form can have only one action, if you want to pass data to a different page then you can do that by calling an ajax function..
I have html form with dynamical number of fields, for example:
<form id="myform">
<input type="text" id="input1">
<input type="text" id="input2">
<input type="text" id="input3">
...
<input type="text" id="inputN">
<span id="button_click"> CLICK </span>
</form>
and jQuery which is:
$("#button_click").click(function(){
$.post("myfile.php",
{
XXXX:YYYY
},
function(data,status){
// do anyting
});
});
I don't know the exact number of fields, so I can't fill XXXX - post variable name, and YYYY - field data from web page.... so I can't count/write one by one...
How can I submit whole form, through post variables, using AJAX and click button?
Sounds like you're looking for the .serialize() method:
$.post("myfile.php",
$("#myform").serialize(),
function(data,status){
// do anyting
});
http://api.jquery.com/serialize/
//rough code for general puporse of storing values for post
var obj = $("#myform"),
data = {};//to hold the values
obj.find('[name]').each(function(index, value) {
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.post("myfile.php",
data: data,
function(data,status){
// do anyting
});
i'm new to programming. I need to develop a rating system with check boxes and text-fields where user clicks the subjects from the list and add his rating/experience in the text field as shown in below image.
This is my HTML code.
<form action="" method="post">
<input type="checkbox" id="1" name="cb[1]" value="" onclick="document.getElementById('t1').disabled=!this.checked;" />
<label for="1">Checkbox No. 1</label>
<input type="number" max="5" min="1" id="t1" name="t[1]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="2" name="cb[2]" value="" onclick="document.getElementById('t2').disabled=!this.checked;"/>
<label for="2">Checkbox No. 2</label>
<input type="number" max="5" min="1"id="t2" name="t[2]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="3" name="cb[3]" value="" onclick="document.getElementById('t3').disabled=!this.checked;"/>
<label for="3">Checkbox No. 3</label>
<input type="number" max="5" min="1"id="t3" name="t[3]" value="" disabled="disabled" /><br /><br />
<input type="checkbox" id="4" name="cb[4]" value="" onclick="document.getElementById('t4').disabled=!this.checked;"/>
<label for="4">Checkbox No. 4</label>
<input type="number" max="5" min="1"id="t4" name="t[4]" value="" disabled="disabled" /><br /><br />
<input name="submit" type="submit" value="Submit" />
</form>
This is my php function.
global $usedTexts;
$usedTexts = array();
function postdata(){
if ( isset($_POST['submit']) && array_key_exists("t", $_POST) && is_array($_POST["t"]) && array_key_exists("cb", $_POST) && is_array($_POST["cb"])) {
$usedTexts = array_intersect_key($_POST["t"], $_POST["cb"]);
foreach($usedTexts as $subjectId=>$subjectExp){
if($subjectExp!=null){
echo "This is checkbox id = " . $subjectId . " and This is text field value = " . $subjectExp . "<br />";
}
}
}
}
I'm using wordpress and I want to submit checkbox ID and text Field value without refreshing the browser using Ajax. And also I want to display check box id and value as shown in the picture. I would be very much appreciated if someone can provide ajax code for this. Thanks :)
You can code this using XMLHttpRequest Object or an easier not necessary better is using JQuery. JQUERY AJAX API
Then you can do something like this
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
To find out what fields they enabled and selected the values I have added a script here.
http://jsfiddle.net/eMEYP/10/
var votes = {}; // initialize it globally
$('#form').submit(function (event) {
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
var json = JSON.stringify(votes); //you can send DATA as the HASH or stringify it.
});
FULL CODE *
$('form').submit(function(event) { //make sure you give your form an ID
event.preventDefault();
var votes = {}; // reset and empty the votes
$('input[type=number]:enabled').each(function (i) { // Check inputs by type and which are enabled and run a for each
votes[$(this).attr('id')] = $(this).val(); // Add items to the hashmap
});
$.ajax({ // Initiate an ajax call
type: "POST", // You seem to want post HTTP call
url: "URLPATH/youphpcode.php",
dataType: "json", // this is the data type to return usually JSON
data: votes,//data to send USUALLY JSON or hashmap/array
success: function(d)
{
$('#displayMSG').HTML('Your Votes have been submitted') // Maybe display a message or error.
}
});
});
Use JQuery to prevent the default submit behavior of the form when you click the Submit button. It is like this but it is incomplete:
$('#form').submit(function(event){
event.preventDefault(); //This line prevents the default submit action of the id #form
//Put your AJAX code here that will submit your checkbox and textbox data
})
See http://api.jquery.com/submit/
I have a form that is called via the fancybox plugin login example.
Here is the code I have:
Form:
<form method="post" action="" id="events_form">
<p class="clearfix"><label for="Name">Name:</label> <input type="text" name="Name" id="Name" /></p>
<p class="clearfix"><label for="Company">Company:</label> <input type="text" name="Company" id="Company" /></p>
<p class="clearfix"><label for="Email">Email:</label> <input type="text" name="Email" id="Email" /></p>
<p class="clearfix"><label for="Tel">Tel:</label> <input type="text" name="Tel" id="Tel"/></p>
<p class="clearfix"><input type="submit" value="Submit details" /></p>
</form>
JavaScript / jQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#event_trigger").fancybox({
'padding' : 0,
'scrolling' : 'no',
'titleShow' : false,
});
$("#events_form").bind("submit", function() {
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "/events/index.php",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
return false;
});
});
</script>
The PHP file returns and empty array. However the Firebug post tab displays the form data.
Also, I noticed that if I do
print_r($_SERVER['REQUEST_METHOD'])
This returns GET, even though I have specified POST.
$(this).serializeArray()
with the name of the form CSS id (#my-form-ID, in this example) like this:
$("#my-form-ID").serializeArray()
Hope that solves it. It worked for me. ;-D
$.ajax expects the parameter data to be an object or a string.
http://api.jquery.com/jQuery.ajax/ scroll down to data.
If you wrap your data in an object e.g. data: {array:$(this).serializeArray()} it may work. I'm not 100% sure on that though.
You are doing an AJAX request on a form submit.
Unless the AJAX request is synchronous (which I wouldn't recommend, anyway) there is a danger that your form will be submitted before there is any chance for the AJAX request will return.
In the line:
$(this).serializeArray()
$(this) is referring to the the form element you have selected in the bind method. I'm assuming this is intended