How to deal with php POST when form is dynamic - php

My client page (form builder) is dynamic, i.e. User can build a form with 2 text areas and 1 text field or any amount needed.
Ive been able to do it and change their IDS too. Now I have to send these data to server side PHP.
Now what if the user enters more fields or less? like 5 text areas 10 text fields. How can Write the server side code?
Client side e.g
<textarea type="text" name="TxtArea1" /></textarea>
<textarea type="text" name="TxtArea2" /></textarea>
<input type="text" name="Txt1" />
Ajax post e.g
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$("#main").load("test.php");
},
error: function(jqXHR, textStatus, errorThrown)
{
$("#main").load("An err occured");
}
Server side e.g
$f1 = $_POST[ 'TxtArea1' ];
$f2 = $_POST[ 'TxtArea2' ];
$f3 = $_POST[ 'Txt1' ];

You can use array notation to have your form elements show up as an array on the server side in the respective $_POST index
<textarea type="text" name="TxtArea[]" /></textarea>
<input type="text" name="Txt[]" />
Then you can loop over $_POST['TxtArea']

Related

How can we fetch data from database in PHP using ajax and display in value of input type?

I am working with two forms where if user submitted first form the data is inserted using ajax to database and user is redirected to second form(Both Forms are in same file).
When user which is present on second form presses back button the value on the input type text for form1 one to be fetched from db which is stored when user submitted the first form.
My doubt is how can we pass value from ajax call to input type text
Here is my code which i have done uptill now
//Form 1
<form id="titlechange">
<div id="step1">
<input type="text" name="tbl_title" id="title" value="" class="form-control">
<input type="text" name="tbl_description" id="description" value="" class="form-control">
<button type="button" onclick="addTitle()" name="firstsubmit" class="update-btn" >Next</button>
</div>
</form>
//Form 2
<form id="detailsubmit">
<div id="step2">
<div class = "data"> //input type hidden retreived after submitting from 1 inside class data
<input type="hidden" value="<?php echo $insertData ?>" class="form-control">
</div>
<input type="text" name="city" id="city" value="" class="form-control">
<input type="text" name="state" id="state" value="" class="form-control">
<button type="button" onclick="addTitle()" name="firstsubmit" class="update-btn" >Next</button>
<button type="button" onclick="editModeForStep1()" name="firstsubmit" class="update-btn" >Back</button>
</div>
</form>
Ajax Call for back button
function editModeForStep1()
{
var formData = new FormData($('#detailsubmit')[0]);
formData.append('action', 'retreive');
$.ajax({
method: 'post',
processData: false,
contentType: false,
cache: false,
enctype: 'multipart/form-data',
url: 'ClientData.php',
data: formData,
success:function(msg){
//what should be written here for displaying value received from `ClientData.php` to value attribute of input type text in form 1
$('#step1').addClass('in active');
alert('success');
}
});
}
ClientData.php
if(isset($_POST["action"]) && $_POST["action"]=="retreive"){
$insertData = $_POST['insertdata'];
$slideOne = $objMaster->getSlideForEdit($insertData);
foreach($slideOne as $key=>$value)
{
echo $title = $value['title'];
echo $description = $value['description'];
}
}
First, let's change ClientData.php to return data in a more usable form.
if(isset($_POST["action"]) && $_POST["action"]=="retreive"){
$insertData = $_POST['insertdata'];
//select first row of results for getSlideForEdit by adding `[0]`
$slideOne = $objMaster->getSlideForEdit($insertData)[0];
//notice array keys match form1 form elements ID
//notice there is no need for a loop here
echo json_encode(
array(
'title' => $slideOne['title'],
'description' => $slideOne['description']
)
);
//if you want to update EVERYTHING from $slideOne, you can just do
//echo json_encode($slideOne);
//instead of the above json_encode()
}
Now our return will contain JSON data instead of plain strings. We can update your success method to update those input boxes.
...
data: formData,
//set dataType to json because we are receiving json from the server
dataType: 'json',
success:function(msg){
$('#step1').addClass('in active');
//if you don't set dataType to json you can also do
//msg = JSON.parse(msg);
//loop through returned array.
$.each(msg, function(index, value) {
//select element by index e.g `#title`, set value
$('#' + index).val(value);
});
alert('success');
}
This solution will dynamically update any input on your page as long as you return a key=>value pair for it from your server.

Sending Multiple Dynamix TextField Values Through Ajax

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();
});
});

jQuery send post variable using ajax and submit form

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
});

How to use server validation & client-side validation with jQuery Tools?

Ok, so I have the following form in a jQuery overlay:
<div class="profile_about_edit_container" id="profile_about_edit_container">
<form id="profile_edit_form" name="profile_edit_form" method="post" action="validation.php">
<label>First Name:</label>
<input type="text" name="firstname" maxlength="50" size="30">
<label>Last Name:</label>
<input type="text" name="lastname" maxlength="50" size="30">
<button type="submit" class="save">Save</button>
<button class="close">Cancel</button>
</form>
</div>
This is displayed using an <a> with class="profile_popups_form" and the following Javascript:
$(document).ready(function() {
$(".profile_popups_form").overlay({
});
});
This shows correctly, and validation.php then echo's an array of error messages like so:
if (count($errors) > 0) {
echo json_encode($errors);
}
But now I'm trying to use jQuery client & server validation on this form.
I tried this:
$(document).ready(function(){
var form = $("#profile_edit_form");
$("#profile_edit_form").submit(function(e) {
e.preventDefault();
var input = $("#profile_edit_form").validator();
$.getJSON(form.attr("action") + "?" + form.serialize(), function(json) {
if (json !== '') {
input.data("validator").invalidate(json);
}
else
$('#profile_edit_form').unbind('submit').submit();
});
});
With the objective of submitting the form and displaying this array of error messages in the normal way jQuery Tools Validation does. But I'm having no luck.
Am I approaching this right? If so, what am I doing wrong? I'm not sure if it's the Javascript causing the issue, or if I'm approaching this right logically. I can find literally no resources explaining how to use JQuery Tools Validation with PHP successfully.
Currently the array is just displayed on the screen as if you echo'd text.
I used the following resource to get the code for returning the array:
http://www.abdullahyahya.com/2012/06/20/javascript-client-side-form-validation-using-server-side-form-validation/
Try doing an ajax request to a php file and get back the response from server. The client side can be done with various ways; from HTML5 tags to plain regex
data = $(this).serializeArray();
//we serialized the data of the form and then we do the ajax request
$.ajax({
url: 'validate.php',
type: 'post',
data: data,
dataType : 'json',
success: function (dat) {
if(dat.error==0){
//dat.error is my returned error from the php file
}else{
//handle the errors
}
}
},
error: function(){
//that's if something is wrong with sent data
alert('failure');
}
});

send multiple requests using ajax in php

I am trying to send Push Notifications to android devices using a php script. This works fine if i send it to one device each time, but i have more than 1000 devices and want to send it to all of them at one go. I tried using a loop but it's not working.
<script type="text/javascript">
$(document).ready(function(){
});
function sendToAll(totalUsers){
for(var i=0;i<totalUsers;i++)
{
sendPushNotification(i);
}
}
function sendPushNotification(id){
var data = $('form#1').serialize();
$('form#1').unbind('submit');
$.ajax({
url: "send_message.php",
type: 'GET',
data: data,
beforeSend: function() {
},
success: function(data, textStatus, xhr) {
$('.txt_message').val("");
$('.txt_excerpt').val("");
},
error: function(xhr, textStatus, errorThrown) {
}
});
return false;
}
</script>
This is my HTML form. $no_of_users variable contains the total rows fetched in the select query i.e. the total number of users in the table.
<form id="1" name="" method="post" onsubmit="return sendToAll('<?php echo $no_of_users; ?>')">
<label>Send Message to All the Users</label>
<div class="clear"></div>
<div class="send_container">
<textarea rows="3" name="excerpt" cols="10" class="txt_excerpt" placeholder="Type excerpt here"></textarea>
<textarea rows="3" name="message" cols="25" class="txt_message" placeholder="Type message here"></textarea>
<input type="submit" class="send_btn" value="Send" onclick=""/>
You should use asyncronous requisitions to make all at "same time", use this instruction on your ajax call:
async: true,
You want to push some message to approx. 1000 devices from server. And you want to initiate this with the form and script you presented in the question. But you must also think about the way how server will communicate with devices. There must be some way for you server to reach clients.
One way - instruct you clients to poll server for new messages every N seconds for example. This generates unnecessary traffic and loads the server.
Second way - to use websocket on clients and have server-side support for this. It can be not so trivial as it can appear to be
And one more way - is to use long polling.
Anyways - devices must be instructed in some way how can they receive push messages from server.

Categories