Generating multiple AJAX codes for dynamically generated elements in Javascript, - javascript

I have a script which dynamically generates form elements with their corresponding ID, for e.g.
response from MySQL db says - 4, then
<form ID="form0">
<Input>....
<Button type="submit>....
</form>
<form ID="form1">
<Input>....
<Button type="submit>....
</form>
<form ID="form2">
<Input>....
<Button type="submit>....
</form>
<form ID="form3">
<Input>....
<Button type="submit>....
</form>
once this list of forms are generated, I have an AJAX code which detects the submit buttons and send the input values off to db via PHP page, something like this below,
$(document.body).on('submit', '#form' ,function(e){
e.preventDefault();
var postData = $("#form").serialize();
$.post("../../../functions/processing.php",postData,function(data, status){
var selectedData = JSON.parse(data);
$.each( selectedData, function( i, val ) {
// do something here...
});
});
});
So my question is that, for the list of forms, I have to somehow generate multiple of this AJAX code for form0, form1, form2, form3.. and because I can't anticipate how many forms will be generated, I can't just write one AJAX code like the one above.. is there anyway to dynamically generate AJAX codes for dynamically generated multiple forms?

Give the form a class that identifies it as a form to be handled by your AJAX handler. Then, inside the handler, reference this to get the form element that is being submitted.
<form ID="form0" class="js-ajax-form">
<input>....
<button type="submit>....
</form>
Handler
$(document).on('submit', '.js-ajax-form' ,function(e){
e.preventDefault();
var postData = $(this).serialize();
$.post("../../../functions/processing.php",postData,function(data, status){
var selectedData = JSON.parse(data);
$.each( selectedData, function( i, val ) {
// do something here...
});
});
});

Related

Accessing value of dynamically created elements with javascript in PHP code

I created some textbox dynamically with javascript.
here is javascript code:
$(document).on('click','#AddHaContactNumberButton',function(e){
e.preventDefault();
var outerDiv = document.getElementById("HaContactDiv");
var textboxDiv = document.createElement('div');
textboxDiv.className = 'inputs';
var input = document.createElement('input');
input.type = "text";
input.setAttribute('name','numbersshowbox[number]');
textboxDiv.appendChild(input);
numberinfoDiv.appendChild(textboxDiv);
outerDiv.appendChild(numberinfoDiv);
});
Now, I want to access these textbox values in php code on submit button click and then save it to database.
here is html code:
<FORM ID="AddFORM" NAME="AddFORM" ACTION="./admin.php" METHOD=POST><br>
<div class="clear">
<INPUT CLASS="button" TYPE=SUBMIT NAME="AddHaContactNumberButton" VALUE="Add" ID="AddHaContactNumberButton">
</div>
<div class="left-text-align relative-position">
<INPUT CLASS="button" TYPE=SUBMIT NAME="AddHaContactButton" VALUE="Save" ID="AddHaContactButton">
</div>
</FORM>
my php code:
if ($AddHaContactButton == "Save") {
$test = $_REQUEST['numbersshowbox[number]'];
}
the problem is $test is null. I searched and found that since javascript is client side and php is server side I cannot get the value in php unless I use ajax request. So I wrote ajax request as below:
$(document).on('click','#AddHaContactButton',function(e){
e.preventDefault();
currentForm = document.getElementById("AddFORM");
var numberarray= currentForm.elements['numbersshowbox[number]'];
if (numberarray != null) {
var arry = [];
for (var i = 0; i < typearray.length; i++) {
arry.push([typearray[i].value, numberarray[i].value]);
$.ajax({
url: 'savePhoneNumbersInDatabase.php',
type: 'GET',
data: { numbersArray: arry},
success: function(data){
currentForm.submit();
}
});
}
});
Now it is working fine but the problem is that I want to save data in database in postback. I mean I want page to be refreshed after clicking submit button.
If your goal is to simply refresh the page after the click event and $.ajax() call, add the following to end of the success callback in the ajax options:
location.reload();
Beyond simply answering your question, I believe it would be best practice to attach the ajax call to the submit event of the form, rather than the click event of the button. Unless there's a compelling reason you're not doing that already. Something like:
$('#AddFORM').submit(<submit handler>)

jQuery: How to submit an array in a form

I have the following form. Each time the users clicks add_accommodation I want to add to an array that I will return to the end point (http://server/end/point).
<form action="http://localhost:3000/a/b/c" method="post">
<div>
<input type="hidden" id="Accommodation" name="accommodation"><div>
</div>
</form>
<div id="accommodation_component">
<div>
<label for="AccommodationType">Type:</label>
<input type="number" step="1" id="accommodationType" name="accommodation_type" value="0">
</div>
<div>
<button type="button" id="add_accommodation">Add Accommodation</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#add_accommodation').click(function() {
make_accommodation(this);
});
});
function make_accommodation(input) {
var value = {
type : $("#AccommodationType").val(),
};
var accommodation = $('#Accommodation').attr('id', 'accommodation');
accommodation.push(value);
console.log(accommodation);
}
</script>
At my end point I want the result to be and array (accommodation = [{1},{2},{3},{4}]). How can I do this?
Give the form an id, and just append a new hidden(?) input that has a name that has [] at the end of it, it will send the values as an array to the server.
HTML
<form id="myform" ...>
Javascript
function make_accommodation(){
var newInput = $("<input>",{
type:"hidden",
name:"accommodation[]",
value: {
type: $("#AccommodationType").val()
}
});
$("#myform").append(newInput);
}
Also you list the output as [1,2,3,4] but your code shows you setting the value as an object with a property type and setting it to the value of the accommodation input, i am going to assume that was a mistake. If I am mistaken just modify the value property in the code above.
Also in your code you change the id of the input, not sure why you were doing that as it serves no purpose and would have made your code error out so i removed it.
EDIT
Since you are wanting to send an array of objects, you will have to JSON.stringify the array on the client end and decode it on the server end. In this one you do not need multiple inputs, but a single one to contain the stringified data.
var accommodationData = [];
function make_accommodation(){
accommodationData.push({
type: $("#AccommodationType").val()
});
$("#accommodation").val( JSON.stringify(accommodationData) );
}
Then on the server you have to decode, not sure what server language you are using so i am showing example in PHP
$data = json_decode( $_POST['accommodation'] );
If you are using jQuery's ajax method you could simplify this by sending the array data
jQuery.ajax({
url:"yourURLhere",
type:"post"
data:{
accomodation:accommodationData
},
success:function(response){
//whatever here
}
});
Add antorher hidden field in form
<input type="hidden" name="accommodation[]"> // click1
<input type="hidden" name="accommodation[]"> // click2
...
<input type="hidden" name="accommodation[]"> // clickn
Then when you submit form on server you will have array of accommodation.
JS part :
function make_accommodation() {
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'accommodation[]')
.val($("#AccommodationType").val())
.appendTo('form');
}
on server(PHP) :
print_r($_POST['accommodation']);
Since you're using jQuery you can create a function which creates another hidden field, after clicking on the button
<div id='acommodation-wrapper'></div>
<button type="button" id="add_accommodation" onclick="addAnother()">Add Accommodation</button>
<script type="text/javascript">
function addAnother(){
var accWrapper = $('#accommodation-wrapper');
var count = accWrapper.children().length;
var div = "<input type=\"hidden\" class=\"accommodation-"+count+"\" name=\"accommodation["+count+"]\"></div>";
accWrapper.append(div);
}
</script>

How to submit three forms with one submit button

I have 3 forms I would like to submit with one button:
<form id="#formEditUsername">
//Code
</form>
<form id="#formEdituseremail">
//Code
</form>
<form id="#new_password_form">
//Code
</from>
<button type="submit" class="btn btn-success" id="btnUpdate">Save</button>
I understand that the best way to do this is probably Ajax, but am unsure how I would do this; create two AJAX functions for the first two forms and then call the functions when the third is submitted?
Try this
$(document).ready(function() {
$("#btnUpdate").click(function() {
$.post($("#formEditUsername").attr("action"), $("#formEditUsername").serialize(),
function() {
$.post($("#formEdituseremail").attr("action"), $("#formEdituseremail").serialize(),
function() {
$.post($("#new_password_form").attr("action"), $("#new_password_form").serialize(),
function() {
alert('All forms submitted');
});
});
});
});
});
As #Jari mentioned, you can simply collect data from first two forms and submit them all together.
Note: this aproach requires input name attributes to be unique among all three forms.
Simple example of AJAX call:
var firstFormData = $("#formEditUsername").serialize();
var secondFormData = $("#formEdituseremail").serialize();
var thirdFormData = $("#new_password_form").serialize();
$.post(
URL, // target URL of your choice
firstFormData + secondFormData + thirdFormData
);
<form id="#formEditUsername" class="frmToSubmit" method="post">
//Code
</form>
<form id="#formEdituseremail" class="frmToSubmit" method="post">
//Code
<form>
<form id="#new_password_form" class="frmToSubmit" method="post">
//Code
</from>
<script type="text/javascript">
$(document).ready(function() {
$("#btnUpdate").click(function() {
$(".frmToSubmit").submit();
});
});
</script>

Perform JavaScript on submit of form

I use a JavaScript to load new pages on my webpagepage. looks like this:
function loadpage(page,div) {
$.get(page, function(data) {
$(div).html(data)
});
};
So when i submit my form, I want to use that function to load the php-page you normally would set as your "action" attribute in the form-tag. So how do I get the form to POST or GET(doesen't really matter) all its content and use the function.
Now, when I write:
<form action="javascript:loadpage('bla.php','#content');" method="post">
...
</form>
it loads bla.php the way i want it to but no data is being passed byt the POST...
Is there a solution to this problem? Thank you very much in advance.
see form.onsubmit event
Using your method, you would do it as follows:
Javascript:
function loadpage(page, div, form) {
var GETdata = '';
if ( form ) GETdata = $(form).serialize();
$.get(page, GETdata, function(data) {
$(div).html(data)
});
};
HTML:
<form action="javascript:loadpage('bla.php','#content', this);" method="post">
...
</form>
A better way would be to use non-obtrusive Javascript. Remove the inline javascript:
<form id="theForm" action="" method="post">
...
</form>
and bind your event handler from within your Javascript code:
$('#theForm').submit(function(e){
e.preventDefault();
loadpage('bla.php','#content', this);
});

Handling Json results in ASP.NET MVC with jQuery

I am working on a view containing two forms, handled by separate controller actions which return a string serilaized to Json:
return Json(message);
The forms are submitted using jQuery, by clicking on a button outside the two forms.
The button handler:
$('#inviteForm').ajaxSubmit({
success: function(html, status) {
$("#response").text(html);
}
})
$('#trialForm').ajaxSubmit({
success: function(html, status) {
$("#response").append(html);
}
});
The browser receives the result and prompts the user to download as it is interpreted as "application/json".
However, if I only submit one of these forms in the jQuery, the resulting Json message is displayed as a string in the #response element as desired.
Why does adding a second ajaxSubmit() cause this different behaviour?
Thanks.
The view contains the following forms:
<form action="/Controller1/SaveAttachments/<%=Model.ObjectId %>" id="trialForm" method="post" enctype="multipart/form-data">
<input type="file" name="trialForm" size=30/>
<input type="file" name="trialSheet" size=30/>
<input type="file" name="trialApproval" size=30/>
</form>
and...
<form action="/Controller1/UpdateTemplate/<%=Model.ObjectId %>" id="inviteForm" method="post" enctype="multipart/form-data">
<%=Html.TextArea("invitationSheet", Model.InvitationSheet,
new { #name = "invitationSheet"})
<script type="text/javascript">
window.onload = function() {
var sBasePath = '<%=Url.Content("~/Content/FCKeditor/")%>';
var oFCKeditor = new FCKeditor('invitationSheet');
oFCKeditor.BasePath = sBasePath;
oFCKeditor.HtmlEncodeOutput = true;
oFCKeditor.ReplaceTextarea();
}
</script>
</form>
Update:
You can't upload files directly via AJAX so it is doing an actual post of the form containing file inputs. You should look at a plugin that will let you upload files using the hidden iframe technique that works asynchronously instead of trying to upload using AJAX.

Categories

Resources