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
});
Related
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();
});
});
How to update multiple data using AJAX ?
Example :
TableA
id : 1, 2
name : Jack, John
It's only working with id 1, when I am trying to edit name for id 2 it's not working.
I have try with this code but failed.
HTML/PHP :
...
while($row=mysqli_fetch_array($query)){
echo'
<form class="btn-group">
<input type="text" class="form-control" name="id_user" id="id_user" data-user="'.$row['id'].'" value="'.$row['id'].'">
<input type="text" class="form-control" name="id_status" id="id_status" data-status="'.$row['id'].'" value="'.$row['id'].'">
<button type="submit" id="likestatus" class="btn btn-primary btn-outline btn-xs"><i class="fas fa-thumbs-up"></i></button>
</form>
';
}
AJAX :
$(document).ready(function(){
$("#likestatus").click(function(){
var id_user=$("#id_user").data("user");
var id_status=$("#id_status").data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
The problem with your code is that ids should be unique, but in the loop you create elements with same id.
Use this in the event handler to find the siblings of the button that has been clicked - closest returns the parent of type form.
$(document).ready(function(){
$(".btn-primary").click(function(){
var $form = $(this).closest('form');
var id_user=$form.find('[name="id_user"]').data("user");
var id_status=$form.find('[name="id_status"]').data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
You might want to use your own class instead of .btn-primary because this affects all buttons on the page.
Judging from the incomplete PHP, it appears as if you're not assigning to $ruser within your loop. This would mean you're always posting the same id to like-status.php.
PS: Would've posted as comment, but I can't.
Make your ID unique so make them dynamic
<?php
$counter = 0;
while($row=mysqli_fetch_array($query)){
$counter++;
echo'
<form class="btn-group">
<input type="text" class="form-control" id="userid_$counter" data-user="'.$ruser['id'].'" value="'.$ruser['id'].'">
<input type="text" class="form-control" name="id_status" id="status_$counter" data-status="'.$rtimeline['id'].'" value="'.$rtimeline['id'].'">
<button type="submit" id="likestatus_$counter" class="btn btn-primary btn-outline btn-xs"><i class="fas fa-thumbs-up"></i></button>
</form>
';
}
?>
Then
<script type="text/javascript">
$(document).ready(function(){
$('[id^="likestatus_"]').on('click',function(){
var index = $(this).attr('id').split("_")[1];
var id_user=$("#user_"+index).data("user");
var id_status=$("#status_"+index).data("status");
$.ajax({
url:'status/like-status.php',
method:'POST',
data:{
id_user:id_user,
id_status:id_status
},
success:function(response){
alert(response);
}
});
});
});
You're using the id's multiple times. Thus your query for var id_user=$("#id_user").data("user"); always finds the first input field on the page. You should avoid using the same id multiple times on one page (see this Question).
You may subscribe to the jQuery submit event of the form and then search for the input fields within that form, to properly extract the id_user and status_user values. For that you have to add an appropriate event listener to the <form> element. To find the form I would recommend adding a css-class like like-status-form.
$(document).ready(function(){
// We're attaching a submit-event listener to every element with the css class "like-status-form"
$(".like-status-form").submit(function(event){
// Form get's submitted
// Prevent that the Browser reloads the page
event.preventDefault();
// Extract the user id and status from the form element (=== $(this))
var id_user = $(this).find('[name="id_user"]').data('user');
var id_status = $(this).find('[name="id_status"]').data('status');
// TODO Perform AJAX Call here
});
});
To detect the form elements one can use the jQuery Attribute Equals Selector.
Find a working example at https://jsfiddle.net/07yzf8k1/
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 have here Jquery code with ajax/json. First i will discuss the flow. I have 3 textboxes, my item textbox pass it's value to auto-complete.php through ajax to get it's details. The return value is post or place into mode textbox. And if the post value is 1 or 2 the number textbox should change is css into display:none. But the problem this not working, I set the number textbox into readonly. The change function is working when I change directly the value of number textbox. Why isn't working when the value is post value?
<script>
$(document).ready(function() {
$("#number").css("display","none");
$(document).on('change','#mode',function(){
if($("#mode").val() =="1"){
$("#number").css("display","");
} else if($("#mode").val() =="2"){
$("#number").css("display","");
} else {
$("#number").css("display","none");
}
return true;
});
});
</script>
<input name="item" id="item" type="text"/>
<input name="mode" id="mode" type="text"/>
<input name="number" id="number" type="text" readonly />
<script type="text/javascript">
$(document).ready(function()
{
$('#item').change(function()
{
var item= $("#item").val();
$.ajax({
type: "POST",
url: "autocomplete-ajax.php",
data :"item="+item,
dataType:'json',
type:'POST',
success:function(data){
var mode=data.mode;
//send to element ID
$('#mode').val(mode);
}
});
return false;
});
});
</script>
When you change the value using JavaScript it won't trigger events.
A simple fix is to trigger the event yourself after you update the value.
success:function(data){
var mode=data.mode;
//send to element ID
$('#mode').val(mode).change();
/* OR */
$('#mode').val(mode).trigger('change');
}
I have a form for a mailing list script which I am trying to get working with ajax so the form can refresh without reloading. With the $.ajax part of the jquery commented out, the form variables are sent to the URL string.
?email=test%40address.com&sub=sub&submit=Submit+Form
My question is why is the submit=Submit+Form part there given that it isn't part of my "datastring" and will that be a problem when it comes to processing the actual PHP script?
Here is the form :
<form name="email_list" action="">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" name="submit" value="Submit Form" class="email_submit"></p>
</form>
and the JQuery
$(function() {
$('.email_submit').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = '&email=' + email + '&sub=' + sub;
//alert (dataString);return false;
/*$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});*/
});
You should put the submit handler on the form, not on the button, even if is a submit button.
<form name="email_list" action="" id="my_form">
Update the javascript
$(function() {
$('#my_form').submit(function() {
...
});
});
To serialize all the inputs into a string you could use $("#my_form").serialize() which builds a string with all the inputs and their data ready for posting:
var dataString = $("#my_form").serialize();
Also note that having a name attribute defined for the submit input means that its value will be sent also in the form. If you don't need that, you can simply remove the name attribute.
Submit+Form is the urlencoded version of Submit Form. The field submit is sent because you specify a name attribute to <input type="submit" name="submit" ... />. It will most likely not cause any problems for you (can't say without looking at your server-side code though).
Also, you really should specify a method attribute to your <form>. It seems to default to GET, which is why the form fields are added to the query string.
If you let your ajax POST happen, since you'r manually creating your dataString you won't see the Submit=, however when you let it submit 'normally' you see it, since the submit button is an input field with a value.
You won't encounter any issues with this. You can access the submit value just the same as any other POST value $_POST['submit'] though I'm not sure why you'd want to.